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: 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().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.window.platform_window.display().id();
1103        self.refresh();
1104
1105        self.window
1106            .bounds_observers
1107            .clone()
1108            .retain(&(), |callback| callback(self));
1109    }
1110
1111    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1112    pub fn bounds(&self) -> Bounds<DevicePixels> {
1113        self.window.platform_window.bounds()
1114    }
1115
1116    /// Returns whether or not the window is currently fullscreen
1117    pub fn is_fullscreen(&self) -> bool {
1118        self.window.platform_window.is_fullscreen()
1119    }
1120
1121    fn appearance_changed(&mut self) {
1122        self.window.appearance = self.window.platform_window.appearance();
1123
1124        self.window
1125            .appearance_observers
1126            .clone()
1127            .retain(&(), |callback| callback(self));
1128    }
1129
1130    /// Returns the appearance of the current window.
1131    pub fn appearance(&self) -> WindowAppearance {
1132        self.window.appearance
1133    }
1134
1135    /// Returns the size of the drawable area within the window.
1136    pub fn viewport_size(&self) -> Size<Pixels> {
1137        self.window.viewport_size
1138    }
1139
1140    /// Returns whether this window is focused by the operating system (receiving key events).
1141    pub fn is_window_active(&self) -> bool {
1142        self.window.active.get()
1143    }
1144
1145    /// Toggle zoom on the window.
1146    pub fn zoom_window(&self) {
1147        self.window.platform_window.zoom();
1148    }
1149
1150    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1151    pub fn show_window_menu(&self, position: Point<Pixels>) {
1152        self.window.platform_window.show_window_menu(position)
1153    }
1154
1155    /// Tells the compositor to take control of window movement (Wayland and X11)
1156    ///
1157    /// Events may not be received during a move operation.
1158    pub fn start_system_move(&self) {
1159        self.window.platform_window.start_system_move()
1160    }
1161
1162    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1163    pub fn should_render_window_controls(&self) -> bool {
1164        self.window.platform_window.should_render_window_controls()
1165    }
1166
1167    /// Updates the window's title at the platform level.
1168    pub fn set_window_title(&mut self, title: &str) {
1169        self.window.platform_window.set_title(title);
1170    }
1171
1172    /// Sets the application identifier.
1173    pub fn set_app_id(&mut self, app_id: &str) {
1174        self.window.platform_window.set_app_id(app_id);
1175    }
1176
1177    /// Sets the window background appearance.
1178    pub fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
1179        self.window
1180            .platform_window
1181            .set_background_appearance(background_appearance);
1182    }
1183
1184    /// Mark the window as dirty at the platform level.
1185    pub fn set_window_edited(&mut self, edited: bool) {
1186        self.window.platform_window.set_edited(edited);
1187    }
1188
1189    /// Determine the display on which the window is visible.
1190    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1191        self.platform
1192            .displays()
1193            .into_iter()
1194            .find(|display| display.id() == self.window.display_id)
1195    }
1196
1197    /// Show the platform character palette.
1198    pub fn show_character_palette(&self) {
1199        self.window.platform_window.show_character_palette();
1200    }
1201
1202    /// The scale factor of the display associated with the window. For example, it could
1203    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1204    /// be rendered as two pixels on screen.
1205    pub fn scale_factor(&self) -> f32 {
1206        self.window.scale_factor
1207    }
1208
1209    /// The size of an em for the base font of the application. Adjusting this value allows the
1210    /// UI to scale, just like zooming a web page.
1211    pub fn rem_size(&self) -> Pixels {
1212        self.window
1213            .rem_size_override_stack
1214            .last()
1215            .copied()
1216            .unwrap_or(self.window.rem_size)
1217    }
1218
1219    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1220    /// UI to scale, just like zooming a web page.
1221    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1222        self.window.rem_size = rem_size.into();
1223    }
1224
1225    /// Executes the provided function with the specified rem size.
1226    ///
1227    /// This method must only be called as part of element drawing.
1228    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1229    where
1230        F: FnOnce(&mut Self) -> R,
1231    {
1232        debug_assert!(
1233            matches!(
1234                self.window.draw_phase,
1235                DrawPhase::Prepaint | DrawPhase::Paint
1236            ),
1237            "this method can only be called during request_layout, prepaint, or paint"
1238        );
1239
1240        if let Some(rem_size) = rem_size {
1241            self.window.rem_size_override_stack.push(rem_size.into());
1242            let result = f(self);
1243            self.window.rem_size_override_stack.pop();
1244            result
1245        } else {
1246            f(self)
1247        }
1248    }
1249
1250    /// The line height associated with the current text style.
1251    pub fn line_height(&self) -> Pixels {
1252        let rem_size = self.rem_size();
1253        let text_style = self.text_style();
1254        text_style
1255            .line_height
1256            .to_pixels(text_style.font_size, rem_size)
1257    }
1258
1259    /// Call to prevent the default action of an event. Currently only used to prevent
1260    /// parent elements from becoming focused on mouse down.
1261    pub fn prevent_default(&mut self) {
1262        self.window.default_prevented = true;
1263    }
1264
1265    /// Obtain whether default has been prevented for the event currently being dispatched.
1266    pub fn default_prevented(&self) -> bool {
1267        self.window.default_prevented
1268    }
1269
1270    /// Determine whether the given action is available along the dispatch path to the currently focused element.
1271    pub fn is_action_available(&self, action: &dyn Action) -> bool {
1272        let target = self
1273            .focused()
1274            .and_then(|focused_handle| {
1275                self.window
1276                    .rendered_frame
1277                    .dispatch_tree
1278                    .focusable_node_id(focused_handle.id)
1279            })
1280            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1281        self.window
1282            .rendered_frame
1283            .dispatch_tree
1284            .is_action_available(action, target)
1285    }
1286
1287    /// The position of the mouse relative to the window.
1288    pub fn mouse_position(&self) -> Point<Pixels> {
1289        self.window.mouse_position
1290    }
1291
1292    /// The current state of the keyboard's modifiers
1293    pub fn modifiers(&self) -> Modifiers {
1294        self.window.modifiers
1295    }
1296
1297    fn complete_frame(&self) {
1298        self.window.platform_window.completed_frame();
1299    }
1300
1301    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1302    /// the contents of the new [Scene], use [present].
1303    #[profiling::function]
1304    pub fn draw(&mut self) {
1305        self.window.dirty.set(false);
1306        self.window.requested_autoscroll = None;
1307
1308        // Restore the previously-used input handler.
1309        if let Some(input_handler) = self.window.platform_window.take_input_handler() {
1310            self.window
1311                .rendered_frame
1312                .input_handlers
1313                .push(Some(input_handler));
1314        }
1315
1316        self.draw_roots();
1317        self.window.dirty_views.clear();
1318
1319        self.window
1320            .next_frame
1321            .dispatch_tree
1322            .preserve_pending_keystrokes(
1323                &mut self.window.rendered_frame.dispatch_tree,
1324                self.window.focus,
1325            );
1326        self.window.next_frame.focus = self.window.focus;
1327        self.window.next_frame.window_active = self.window.active.get();
1328
1329        // Register requested input handler with the platform window.
1330        if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
1331            self.window
1332                .platform_window
1333                .set_input_handler(input_handler.unwrap());
1334        }
1335
1336        self.window.layout_engine.as_mut().unwrap().clear();
1337        self.text_system().finish_frame();
1338        self.window
1339            .next_frame
1340            .finish(&mut self.window.rendered_frame);
1341        ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1342            let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1343            if percentage >= 80. {
1344                log::warn!("elevated element arena occupation: {}.", percentage);
1345            }
1346            element_arena.clear();
1347        });
1348
1349        self.window.draw_phase = DrawPhase::Focus;
1350        let previous_focus_path = self.window.rendered_frame.focus_path();
1351        let previous_window_active = self.window.rendered_frame.window_active;
1352        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1353        self.window.next_frame.clear();
1354        let current_focus_path = self.window.rendered_frame.focus_path();
1355        let current_window_active = self.window.rendered_frame.window_active;
1356
1357        if previous_focus_path != current_focus_path
1358            || previous_window_active != current_window_active
1359        {
1360            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1361                self.window
1362                    .focus_lost_listeners
1363                    .clone()
1364                    .retain(&(), |listener| listener(self));
1365            }
1366
1367            let event = FocusEvent {
1368                previous_focus_path: if previous_window_active {
1369                    previous_focus_path
1370                } else {
1371                    Default::default()
1372                },
1373                current_focus_path: if current_window_active {
1374                    current_focus_path
1375                } else {
1376                    Default::default()
1377                },
1378            };
1379            self.window
1380                .focus_listeners
1381                .clone()
1382                .retain(&(), |listener| listener(&event, self));
1383        }
1384
1385        self.reset_cursor_style();
1386        self.window.refreshing = false;
1387        self.window.draw_phase = DrawPhase::None;
1388        self.window.needs_present.set(true);
1389    }
1390
1391    #[profiling::function]
1392    fn present(&self) {
1393        self.window
1394            .platform_window
1395            .draw(&self.window.rendered_frame.scene);
1396        self.window.needs_present.set(false);
1397        profiling::finish_frame!();
1398    }
1399
1400    fn draw_roots(&mut self) {
1401        self.window.draw_phase = DrawPhase::Prepaint;
1402        self.window.tooltip_bounds.take();
1403
1404        // Layout all root elements.
1405        let mut root_element = self.window.root_view.as_ref().unwrap().clone().into_any();
1406        root_element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1407
1408        let mut sorted_deferred_draws =
1409            (0..self.window.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1410        sorted_deferred_draws.sort_by_key(|ix| self.window.next_frame.deferred_draws[*ix].priority);
1411        self.prepaint_deferred_draws(&sorted_deferred_draws);
1412
1413        let mut prompt_element = None;
1414        let mut active_drag_element = None;
1415        let mut tooltip_element = None;
1416        if let Some(prompt) = self.window.prompt.take() {
1417            let mut element = prompt.view.any_view().into_any();
1418            element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1419            prompt_element = Some(element);
1420            self.window.prompt = Some(prompt);
1421        } else if let Some(active_drag) = self.app.active_drag.take() {
1422            let mut element = active_drag.view.clone().into_any();
1423            let offset = self.mouse_position() - active_drag.cursor_offset;
1424            element.prepaint_as_root(offset, AvailableSpace::min_size(), self);
1425            active_drag_element = Some(element);
1426            self.app.active_drag = Some(active_drag);
1427        } else {
1428            tooltip_element = self.prepaint_tooltip();
1429        }
1430
1431        self.window.mouse_hit_test = self.window.next_frame.hit_test(self.window.mouse_position);
1432
1433        // Now actually paint the elements.
1434        self.window.draw_phase = DrawPhase::Paint;
1435        root_element.paint(self);
1436
1437        self.paint_deferred_draws(&sorted_deferred_draws);
1438
1439        if let Some(mut prompt_element) = prompt_element {
1440            prompt_element.paint(self)
1441        } else if let Some(mut drag_element) = active_drag_element {
1442            drag_element.paint(self);
1443        } else if let Some(mut tooltip_element) = tooltip_element {
1444            tooltip_element.paint(self);
1445        }
1446    }
1447
1448    fn prepaint_tooltip(&mut self) -> Option<AnyElement> {
1449        let tooltip_request = self.window.next_frame.tooltip_requests.last().cloned()?;
1450        let tooltip_request = tooltip_request.unwrap();
1451        let mut element = tooltip_request.tooltip.view.clone().into_any();
1452        let mouse_position = tooltip_request.tooltip.mouse_position;
1453        let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self);
1454
1455        let mut tooltip_bounds = Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1456        let window_bounds = Bounds {
1457            origin: Point::default(),
1458            size: self.viewport_size(),
1459        };
1460
1461        if tooltip_bounds.right() > window_bounds.right() {
1462            let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1463            if new_x >= Pixels::ZERO {
1464                tooltip_bounds.origin.x = new_x;
1465            } else {
1466                tooltip_bounds.origin.x = cmp::max(
1467                    Pixels::ZERO,
1468                    tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1469                );
1470            }
1471        }
1472
1473        if tooltip_bounds.bottom() > window_bounds.bottom() {
1474            let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
1475            if new_y >= Pixels::ZERO {
1476                tooltip_bounds.origin.y = new_y;
1477            } else {
1478                tooltip_bounds.origin.y = cmp::max(
1479                    Pixels::ZERO,
1480                    tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
1481                );
1482            }
1483        }
1484
1485        self.with_absolute_element_offset(tooltip_bounds.origin, |cx| element.prepaint(cx));
1486
1487        self.window.tooltip_bounds = Some(TooltipBounds {
1488            id: tooltip_request.id,
1489            bounds: tooltip_bounds,
1490        });
1491        Some(element)
1492    }
1493
1494    fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1495        assert_eq!(self.window.element_id_stack.len(), 0);
1496
1497        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1498        for deferred_draw_ix in deferred_draw_indices {
1499            let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1500            self.window
1501                .element_id_stack
1502                .clone_from(&deferred_draw.element_id_stack);
1503            self.window
1504                .text_style_stack
1505                .clone_from(&deferred_draw.text_style_stack);
1506            self.window
1507                .next_frame
1508                .dispatch_tree
1509                .set_active_node(deferred_draw.parent_node);
1510
1511            let prepaint_start = self.prepaint_index();
1512            if let Some(element) = deferred_draw.element.as_mut() {
1513                self.with_absolute_element_offset(deferred_draw.absolute_offset, |cx| {
1514                    element.prepaint(cx)
1515                });
1516            } else {
1517                self.reuse_prepaint(deferred_draw.prepaint_range.clone());
1518            }
1519            let prepaint_end = self.prepaint_index();
1520            deferred_draw.prepaint_range = prepaint_start..prepaint_end;
1521        }
1522        assert_eq!(
1523            self.window.next_frame.deferred_draws.len(),
1524            0,
1525            "cannot call defer_draw during deferred drawing"
1526        );
1527        self.window.next_frame.deferred_draws = deferred_draws;
1528        self.window.element_id_stack.clear();
1529        self.window.text_style_stack.clear();
1530    }
1531
1532    fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1533        assert_eq!(self.window.element_id_stack.len(), 0);
1534
1535        let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1536        for deferred_draw_ix in deferred_draw_indices {
1537            let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1538            self.window
1539                .element_id_stack
1540                .clone_from(&deferred_draw.element_id_stack);
1541            self.window
1542                .next_frame
1543                .dispatch_tree
1544                .set_active_node(deferred_draw.parent_node);
1545
1546            let paint_start = self.paint_index();
1547            if let Some(element) = deferred_draw.element.as_mut() {
1548                element.paint(self);
1549            } else {
1550                self.reuse_paint(deferred_draw.paint_range.clone());
1551            }
1552            let paint_end = self.paint_index();
1553            deferred_draw.paint_range = paint_start..paint_end;
1554        }
1555        self.window.next_frame.deferred_draws = deferred_draws;
1556        self.window.element_id_stack.clear();
1557    }
1558
1559    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
1560        PrepaintStateIndex {
1561            hitboxes_index: self.window.next_frame.hitboxes.len(),
1562            tooltips_index: self.window.next_frame.tooltip_requests.len(),
1563            deferred_draws_index: self.window.next_frame.deferred_draws.len(),
1564            dispatch_tree_index: self.window.next_frame.dispatch_tree.len(),
1565            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1566            line_layout_index: self.window.text_system.layout_index(),
1567        }
1568    }
1569
1570    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
1571        let window = &mut self.window;
1572        window.next_frame.hitboxes.extend(
1573            window.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
1574                .iter()
1575                .cloned(),
1576        );
1577        window.next_frame.tooltip_requests.extend(
1578            window.rendered_frame.tooltip_requests
1579                [range.start.tooltips_index..range.end.tooltips_index]
1580                .iter_mut()
1581                .map(|request| request.take()),
1582        );
1583        window.next_frame.accessed_element_states.extend(
1584            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1585                ..range.end.accessed_element_states_index]
1586                .iter()
1587                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1588        );
1589        window
1590            .text_system
1591            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1592
1593        let reused_subtree = window.next_frame.dispatch_tree.reuse_subtree(
1594            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
1595            &mut window.rendered_frame.dispatch_tree,
1596        );
1597        window.next_frame.deferred_draws.extend(
1598            window.rendered_frame.deferred_draws
1599                [range.start.deferred_draws_index..range.end.deferred_draws_index]
1600                .iter()
1601                .map(|deferred_draw| DeferredDraw {
1602                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
1603                    element_id_stack: deferred_draw.element_id_stack.clone(),
1604                    text_style_stack: deferred_draw.text_style_stack.clone(),
1605                    priority: deferred_draw.priority,
1606                    element: None,
1607                    absolute_offset: deferred_draw.absolute_offset,
1608                    prepaint_range: deferred_draw.prepaint_range.clone(),
1609                    paint_range: deferred_draw.paint_range.clone(),
1610                }),
1611        );
1612    }
1613
1614    pub(crate) fn paint_index(&self) -> PaintIndex {
1615        PaintIndex {
1616            scene_index: self.window.next_frame.scene.len(),
1617            mouse_listeners_index: self.window.next_frame.mouse_listeners.len(),
1618            input_handlers_index: self.window.next_frame.input_handlers.len(),
1619            cursor_styles_index: self.window.next_frame.cursor_styles.len(),
1620            accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1621            line_layout_index: self.window.text_system.layout_index(),
1622        }
1623    }
1624
1625    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
1626        let window = &mut self.window;
1627
1628        window.next_frame.cursor_styles.extend(
1629            window.rendered_frame.cursor_styles
1630                [range.start.cursor_styles_index..range.end.cursor_styles_index]
1631                .iter()
1632                .cloned(),
1633        );
1634        window.next_frame.input_handlers.extend(
1635            window.rendered_frame.input_handlers
1636                [range.start.input_handlers_index..range.end.input_handlers_index]
1637                .iter_mut()
1638                .map(|handler| handler.take()),
1639        );
1640        window.next_frame.mouse_listeners.extend(
1641            window.rendered_frame.mouse_listeners
1642                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
1643                .iter_mut()
1644                .map(|listener| listener.take()),
1645        );
1646        window.next_frame.accessed_element_states.extend(
1647            window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1648                ..range.end.accessed_element_states_index]
1649                .iter()
1650                .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1651        );
1652        window
1653            .text_system
1654            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1655        window.next_frame.scene.replay(
1656            range.start.scene_index..range.end.scene_index,
1657            &window.rendered_frame.scene,
1658        );
1659    }
1660
1661    /// Push a text style onto the stack, and call a function with that style active.
1662    /// Use [`AppContext::text_style`] to get the current, combined text style. This method
1663    /// should only be called as part of element drawing.
1664    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
1665    where
1666        F: FnOnce(&mut Self) -> R,
1667    {
1668        debug_assert!(
1669            matches!(
1670                self.window.draw_phase,
1671                DrawPhase::Prepaint | DrawPhase::Paint
1672            ),
1673            "this method can only be called during request_layout, prepaint, or paint"
1674        );
1675        if let Some(style) = style {
1676            self.window.text_style_stack.push(style);
1677            let result = f(self);
1678            self.window.text_style_stack.pop();
1679            result
1680        } else {
1681            f(self)
1682        }
1683    }
1684
1685    /// Updates the cursor style at the platform level. This method should only be called
1686    /// during the prepaint phase of element drawing.
1687    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
1688        debug_assert_eq!(
1689            self.window.draw_phase,
1690            DrawPhase::Paint,
1691            "this method can only be called during paint"
1692        );
1693        self.window
1694            .next_frame
1695            .cursor_styles
1696            .push(CursorStyleRequest {
1697                hitbox_id: hitbox.id,
1698                style,
1699            });
1700    }
1701
1702    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
1703    /// during the paint phase of element drawing.
1704    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
1705        debug_assert_eq!(
1706            self.window.draw_phase,
1707            DrawPhase::Prepaint,
1708            "this method can only be called during prepaint"
1709        );
1710        let id = TooltipId(post_inc(&mut self.window.next_tooltip_id.0));
1711        self.window
1712            .next_frame
1713            .tooltip_requests
1714            .push(Some(TooltipRequest { id, tooltip }));
1715        id
1716    }
1717
1718    /// Invoke the given function with the given content mask after intersecting it
1719    /// with the current mask. This method should only be called during element drawing.
1720    pub fn with_content_mask<R>(
1721        &mut self,
1722        mask: Option<ContentMask<Pixels>>,
1723        f: impl FnOnce(&mut Self) -> R,
1724    ) -> R {
1725        debug_assert!(
1726            matches!(
1727                self.window.draw_phase,
1728                DrawPhase::Prepaint | DrawPhase::Paint
1729            ),
1730            "this method can only be called during request_layout, prepaint, or paint"
1731        );
1732        if let Some(mask) = mask {
1733            let mask = mask.intersect(&self.content_mask());
1734            self.window_mut().content_mask_stack.push(mask);
1735            let result = f(self);
1736            self.window_mut().content_mask_stack.pop();
1737            result
1738        } else {
1739            f(self)
1740        }
1741    }
1742
1743    /// Updates the global element offset relative to the current offset. This is used to implement
1744    /// scrolling. This method should only be called during the prepaint phase of element drawing.
1745    pub fn with_element_offset<R>(
1746        &mut self,
1747        offset: Point<Pixels>,
1748        f: impl FnOnce(&mut Self) -> R,
1749    ) -> R {
1750        debug_assert_eq!(
1751            self.window.draw_phase,
1752            DrawPhase::Prepaint,
1753            "this method can only be called during request_layout, or prepaint"
1754        );
1755
1756        if offset.is_zero() {
1757            return f(self);
1758        };
1759
1760        let abs_offset = self.element_offset() + offset;
1761        self.with_absolute_element_offset(abs_offset, f)
1762    }
1763
1764    /// Updates the global element offset based on the given offset. This is used to implement
1765    /// drag handles and other manual painting of elements. This method should only be called during
1766    /// the prepaint phase of element drawing.
1767    pub fn with_absolute_element_offset<R>(
1768        &mut self,
1769        offset: Point<Pixels>,
1770        f: impl FnOnce(&mut Self) -> R,
1771    ) -> R {
1772        debug_assert_eq!(
1773            self.window.draw_phase,
1774            DrawPhase::Prepaint,
1775            "this method can only be called during request_layout, or prepaint"
1776        );
1777        self.window_mut().element_offset_stack.push(offset);
1778        let result = f(self);
1779        self.window_mut().element_offset_stack.pop();
1780        result
1781    }
1782
1783    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
1784    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
1785    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
1786    /// element offset and prepaint again. See [`List`] for an example. This method should only be
1787    /// called during the prepaint phase of element drawing.
1788    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
1789        debug_assert_eq!(
1790            self.window.draw_phase,
1791            DrawPhase::Prepaint,
1792            "this method can only be called during prepaint"
1793        );
1794        let index = self.prepaint_index();
1795        let result = f(self);
1796        if result.is_err() {
1797            self.window
1798                .next_frame
1799                .hitboxes
1800                .truncate(index.hitboxes_index);
1801            self.window
1802                .next_frame
1803                .tooltip_requests
1804                .truncate(index.tooltips_index);
1805            self.window
1806                .next_frame
1807                .deferred_draws
1808                .truncate(index.deferred_draws_index);
1809            self.window
1810                .next_frame
1811                .dispatch_tree
1812                .truncate(index.dispatch_tree_index);
1813            self.window
1814                .next_frame
1815                .accessed_element_states
1816                .truncate(index.accessed_element_states_index);
1817            self.window
1818                .text_system
1819                .truncate_layouts(index.line_layout_index);
1820        }
1821        result
1822    }
1823
1824    /// When you call this method during [`prepaint`], containing elements will attempt to
1825    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
1826    /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
1827    /// that supports this method being called on the elements it contains. This method should only be
1828    /// called during the prepaint phase of element drawing.
1829    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
1830        debug_assert_eq!(
1831            self.window.draw_phase,
1832            DrawPhase::Prepaint,
1833            "this method can only be called during prepaint"
1834        );
1835        self.window.requested_autoscroll = Some(bounds);
1836    }
1837
1838    /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
1839    /// described in [`request_autoscroll`].
1840    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
1841        debug_assert_eq!(
1842            self.window.draw_phase,
1843            DrawPhase::Prepaint,
1844            "this method can only be called during prepaint"
1845        );
1846        self.window.requested_autoscroll.take()
1847    }
1848
1849    /// Remove an asset from GPUI's cache
1850    pub fn remove_cached_asset<A: Asset + 'static>(
1851        &mut self,
1852        source: &A::Source,
1853    ) -> Option<A::Output> {
1854        self.asset_cache.remove::<A>(source)
1855    }
1856
1857    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1858    /// Your view will be re-drawn once the asset has finished loading.
1859    ///
1860    /// Note that the multiple calls to this method will only result in one `Asset::load` call.
1861    /// The results of that call will be cached, and returned on subsequent uses of this API.
1862    ///
1863    /// Use [Self::remove_cached_asset] to reload your asset.
1864    pub fn use_cached_asset<A: Asset + 'static>(
1865        &mut self,
1866        source: &A::Source,
1867    ) -> Option<A::Output> {
1868        self.asset_cache.get::<A>(source).or_else(|| {
1869            if let Some(asset) = self.use_asset::<A>(source) {
1870                self.asset_cache
1871                    .insert::<A>(source.to_owned(), asset.clone());
1872                Some(asset)
1873            } else {
1874                None
1875            }
1876        })
1877    }
1878
1879    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1880    /// Your view will be re-drawn once the asset has finished loading.
1881    ///
1882    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1883    /// time.
1884    ///
1885    /// This asset will not be cached by default, see [Self::use_cached_asset]
1886    pub fn use_asset<A: Asset + 'static>(&mut self, source: &A::Source) -> Option<A::Output> {
1887        let asset_id = (TypeId::of::<A>(), hash(source));
1888        let mut is_first = false;
1889        let task = self
1890            .loading_assets
1891            .remove(&asset_id)
1892            .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1893            .unwrap_or_else(|| {
1894                is_first = true;
1895                let future = A::load(source.clone(), self);
1896                let task = self.background_executor().spawn(future).shared();
1897                task
1898            });
1899
1900        task.clone().now_or_never().or_else(|| {
1901            if is_first {
1902                let parent_id = self.parent_view_id();
1903                self.spawn({
1904                    let task = task.clone();
1905                    |mut cx| async move {
1906                        task.await;
1907
1908                        cx.on_next_frame(move |cx| {
1909                            if let Some(parent_id) = parent_id {
1910                                cx.notify(parent_id)
1911                            } else {
1912                                cx.refresh()
1913                            }
1914                        });
1915                    }
1916                })
1917                .detach();
1918            }
1919
1920            self.loading_assets.insert(asset_id, Box::new(task));
1921
1922            None
1923        })
1924    }
1925
1926    /// Obtain the current element offset. This method should only be called during the
1927    /// prepaint phase of element drawing.
1928    pub fn element_offset(&self) -> Point<Pixels> {
1929        debug_assert_eq!(
1930            self.window.draw_phase,
1931            DrawPhase::Prepaint,
1932            "this method can only be called during prepaint"
1933        );
1934        self.window()
1935            .element_offset_stack
1936            .last()
1937            .copied()
1938            .unwrap_or_default()
1939    }
1940
1941    /// Obtain the current content mask. This method should only be called during element drawing.
1942    pub fn content_mask(&self) -> ContentMask<Pixels> {
1943        debug_assert!(
1944            matches!(
1945                self.window.draw_phase,
1946                DrawPhase::Prepaint | DrawPhase::Paint
1947            ),
1948            "this method can only be called during prepaint, or paint"
1949        );
1950        self.window()
1951            .content_mask_stack
1952            .last()
1953            .cloned()
1954            .unwrap_or_else(|| ContentMask {
1955                bounds: Bounds {
1956                    origin: Point::default(),
1957                    size: self.window().viewport_size,
1958                },
1959            })
1960    }
1961
1962    /// Provide elements in the called function with a new namespace in which their identiers must be unique.
1963    /// This can be used within a custom element to distinguish multiple sets of child elements.
1964    pub fn with_element_namespace<R>(
1965        &mut self,
1966        element_id: impl Into<ElementId>,
1967        f: impl FnOnce(&mut Self) -> R,
1968    ) -> R {
1969        self.window.element_id_stack.push(element_id.into());
1970        let result = f(self);
1971        self.window.element_id_stack.pop();
1972        result
1973    }
1974
1975    /// Updates or initializes state for an element with the given id that lives across multiple
1976    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
1977    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1978    /// when drawing the next frame. This method should only be called as part of element drawing.
1979    pub fn with_element_state<S, R>(
1980        &mut self,
1981        global_id: &GlobalElementId,
1982        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1983    ) -> R
1984    where
1985        S: 'static,
1986    {
1987        debug_assert!(
1988            matches!(
1989                self.window.draw_phase,
1990                DrawPhase::Prepaint | DrawPhase::Paint
1991            ),
1992            "this method can only be called during request_layout, prepaint, or paint"
1993        );
1994
1995        let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
1996        self.window
1997            .next_frame
1998            .accessed_element_states
1999            .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2000
2001        if let Some(any) = self
2002            .window
2003            .next_frame
2004            .element_states
2005            .remove(&key)
2006            .or_else(|| self.window.rendered_frame.element_states.remove(&key))
2007        {
2008            let ElementStateBox {
2009                inner,
2010                #[cfg(debug_assertions)]
2011                type_name,
2012            } = any;
2013            // Using the extra inner option to avoid needing to reallocate a new box.
2014            let mut state_box = inner
2015                .downcast::<Option<S>>()
2016                .map_err(|_| {
2017                    #[cfg(debug_assertions)]
2018                    {
2019                        anyhow::anyhow!(
2020                            "invalid element state type for id, requested {:?}, actual: {:?}",
2021                            std::any::type_name::<S>(),
2022                            type_name
2023                        )
2024                    }
2025
2026                    #[cfg(not(debug_assertions))]
2027                    {
2028                        anyhow::anyhow!(
2029                            "invalid element state type for id, requested {:?}",
2030                            std::any::type_name::<S>(),
2031                        )
2032                    }
2033                })
2034                .unwrap();
2035
2036            let state = state_box.take().expect(
2037                "reentrant call to with_element_state for the same state type and element id",
2038            );
2039            let (result, state) = f(Some(state), self);
2040            state_box.replace(state);
2041            self.window.next_frame.element_states.insert(
2042                key,
2043                ElementStateBox {
2044                    inner: state_box,
2045                    #[cfg(debug_assertions)]
2046                    type_name,
2047                },
2048            );
2049            result
2050        } else {
2051            let (result, state) = f(None, self);
2052            self.window.next_frame.element_states.insert(
2053                key,
2054                ElementStateBox {
2055                    inner: Box::new(Some(state)),
2056                    #[cfg(debug_assertions)]
2057                    type_name: std::any::type_name::<S>(),
2058                },
2059            );
2060            result
2061        }
2062    }
2063
2064    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2065    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2066    /// when the element is guaranteed to have an id.
2067    pub fn with_optional_element_state<S, R>(
2068        &mut self,
2069        global_id: Option<&GlobalElementId>,
2070        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2071    ) -> R
2072    where
2073        S: 'static,
2074    {
2075        debug_assert!(
2076            matches!(
2077                self.window.draw_phase,
2078                DrawPhase::Prepaint | DrawPhase::Paint
2079            ),
2080            "this method can only be called during request_layout, prepaint, or paint"
2081        );
2082
2083        if let Some(global_id) = global_id {
2084            self.with_element_state(global_id, |state, cx| {
2085                let (result, state) = f(Some(state), cx);
2086                let state =
2087                    state.expect("you must return some state when you pass some element id");
2088                (result, state)
2089            })
2090        } else {
2091            let (result, state) = f(None, self);
2092            debug_assert!(
2093                state.is_none(),
2094                "you must not return an element state when passing None for the global id"
2095            );
2096            result
2097        }
2098    }
2099
2100    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2101    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2102    /// with higher values being drawn on top.
2103    ///
2104    /// This method should only be called as part of the prepaint phase of element drawing.
2105    pub fn defer_draw(
2106        &mut self,
2107        element: AnyElement,
2108        absolute_offset: Point<Pixels>,
2109        priority: usize,
2110    ) {
2111        let window = &mut self.window;
2112        debug_assert_eq!(
2113            window.draw_phase,
2114            DrawPhase::Prepaint,
2115            "this method can only be called during request_layout or prepaint"
2116        );
2117        let parent_node = window.next_frame.dispatch_tree.active_node_id().unwrap();
2118        window.next_frame.deferred_draws.push(DeferredDraw {
2119            parent_node,
2120            element_id_stack: window.element_id_stack.clone(),
2121            text_style_stack: window.text_style_stack.clone(),
2122            priority,
2123            element: Some(element),
2124            absolute_offset,
2125            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2126            paint_range: PaintIndex::default()..PaintIndex::default(),
2127        });
2128    }
2129
2130    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2131    /// of geometry that are non-overlapping and have the same draw order. This is typically used
2132    /// for performance reasons.
2133    ///
2134    /// This method should only be called as part of the paint phase of element drawing.
2135    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2136        debug_assert_eq!(
2137            self.window.draw_phase,
2138            DrawPhase::Paint,
2139            "this method can only be called during paint"
2140        );
2141
2142        let scale_factor = self.scale_factor();
2143        let content_mask = self.content_mask();
2144        let clipped_bounds = bounds.intersect(&content_mask.bounds);
2145        if !clipped_bounds.is_empty() {
2146            self.window
2147                .next_frame
2148                .scene
2149                .push_layer(clipped_bounds.scale(scale_factor));
2150        }
2151
2152        let result = f(self);
2153
2154        if !clipped_bounds.is_empty() {
2155            self.window.next_frame.scene.pop_layer();
2156        }
2157
2158        result
2159    }
2160
2161    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2162    ///
2163    /// This method should only be called as part of the paint phase of element drawing.
2164    pub fn paint_shadows(
2165        &mut self,
2166        bounds: Bounds<Pixels>,
2167        corner_radii: Corners<Pixels>,
2168        shadows: &[BoxShadow],
2169    ) {
2170        debug_assert_eq!(
2171            self.window.draw_phase,
2172            DrawPhase::Paint,
2173            "this method can only be called during paint"
2174        );
2175
2176        let scale_factor = self.scale_factor();
2177        let content_mask = self.content_mask();
2178        for shadow in shadows {
2179            let mut shadow_bounds = bounds;
2180            shadow_bounds.origin += shadow.offset;
2181            shadow_bounds.dilate(shadow.spread_radius);
2182            self.window.next_frame.scene.insert_primitive(Shadow {
2183                order: 0,
2184                blur_radius: shadow.blur_radius.scale(scale_factor),
2185                bounds: shadow_bounds.scale(scale_factor),
2186                content_mask: content_mask.scale(scale_factor),
2187                corner_radii: corner_radii.scale(scale_factor),
2188                color: shadow.color,
2189            });
2190        }
2191    }
2192
2193    /// Paint one or more quads into the scene for the next frame at the current stacking context.
2194    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2195    /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2196    ///
2197    /// This method should only be called as part of the paint phase of element drawing.
2198    pub fn paint_quad(&mut self, quad: PaintQuad) {
2199        debug_assert_eq!(
2200            self.window.draw_phase,
2201            DrawPhase::Paint,
2202            "this method can only be called during paint"
2203        );
2204
2205        let scale_factor = self.scale_factor();
2206        let content_mask = self.content_mask();
2207        self.window.next_frame.scene.insert_primitive(Quad {
2208            order: 0,
2209            pad: 0,
2210            bounds: quad.bounds.scale(scale_factor),
2211            content_mask: content_mask.scale(scale_factor),
2212            background: quad.background,
2213            border_color: quad.border_color,
2214            corner_radii: quad.corner_radii.scale(scale_factor),
2215            border_widths: quad.border_widths.scale(scale_factor),
2216        });
2217    }
2218
2219    /// Paint the given `Path` into the scene for the next frame at the current z-index.
2220    ///
2221    /// This method should only be called as part of the paint phase of element drawing.
2222    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
2223        debug_assert_eq!(
2224            self.window.draw_phase,
2225            DrawPhase::Paint,
2226            "this method can only be called during paint"
2227        );
2228
2229        let scale_factor = self.scale_factor();
2230        let content_mask = self.content_mask();
2231        path.content_mask = content_mask;
2232        path.color = color.into();
2233        self.window
2234            .next_frame
2235            .scene
2236            .insert_primitive(path.scale(scale_factor));
2237    }
2238
2239    /// Paint an underline into the scene for the next frame at the current z-index.
2240    ///
2241    /// This method should only be called as part of the paint phase of element drawing.
2242    pub fn paint_underline(
2243        &mut self,
2244        origin: Point<Pixels>,
2245        width: Pixels,
2246        style: &UnderlineStyle,
2247    ) {
2248        debug_assert_eq!(
2249            self.window.draw_phase,
2250            DrawPhase::Paint,
2251            "this method can only be called during paint"
2252        );
2253
2254        let scale_factor = self.scale_factor();
2255        let height = if style.wavy {
2256            style.thickness * 3.
2257        } else {
2258            style.thickness
2259        };
2260        let bounds = Bounds {
2261            origin,
2262            size: size(width, height),
2263        };
2264        let content_mask = self.content_mask();
2265
2266        self.window.next_frame.scene.insert_primitive(Underline {
2267            order: 0,
2268            pad: 0,
2269            bounds: bounds.scale(scale_factor),
2270            content_mask: content_mask.scale(scale_factor),
2271            color: style.color.unwrap_or_default(),
2272            thickness: style.thickness.scale(scale_factor),
2273            wavy: style.wavy,
2274        });
2275    }
2276
2277    /// Paint a strikethrough into the scene for the next frame at the current z-index.
2278    ///
2279    /// This method should only be called as part of the paint phase of element drawing.
2280    pub fn paint_strikethrough(
2281        &mut self,
2282        origin: Point<Pixels>,
2283        width: Pixels,
2284        style: &StrikethroughStyle,
2285    ) {
2286        debug_assert_eq!(
2287            self.window.draw_phase,
2288            DrawPhase::Paint,
2289            "this method can only be called during paint"
2290        );
2291
2292        let scale_factor = self.scale_factor();
2293        let height = style.thickness;
2294        let bounds = Bounds {
2295            origin,
2296            size: size(width, height),
2297        };
2298        let content_mask = self.content_mask();
2299
2300        self.window.next_frame.scene.insert_primitive(Underline {
2301            order: 0,
2302            pad: 0,
2303            bounds: bounds.scale(scale_factor),
2304            content_mask: content_mask.scale(scale_factor),
2305            thickness: style.thickness.scale(scale_factor),
2306            color: style.color.unwrap_or_default(),
2307            wavy: false,
2308        });
2309    }
2310
2311    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2312    ///
2313    /// The y component of the origin is the baseline of the glyph.
2314    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2315    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2316    /// This method is only useful if you need to paint a single glyph that has already been shaped.
2317    ///
2318    /// This method should only be called as part of the paint phase of element drawing.
2319    pub fn paint_glyph(
2320        &mut self,
2321        origin: Point<Pixels>,
2322        font_id: FontId,
2323        glyph_id: GlyphId,
2324        font_size: Pixels,
2325        color: Hsla,
2326    ) -> Result<()> {
2327        debug_assert_eq!(
2328            self.window.draw_phase,
2329            DrawPhase::Paint,
2330            "this method can only be called during paint"
2331        );
2332
2333        let scale_factor = self.scale_factor();
2334        let glyph_origin = origin.scale(scale_factor);
2335        let subpixel_variant = Point {
2336            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2337            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2338        };
2339        let params = RenderGlyphParams {
2340            font_id,
2341            glyph_id,
2342            font_size,
2343            subpixel_variant,
2344            scale_factor,
2345            is_emoji: false,
2346        };
2347
2348        let raster_bounds = self.text_system().raster_bounds(&params)?;
2349        if !raster_bounds.is_zero() {
2350            let tile =
2351                self.window
2352                    .sprite_atlas
2353                    .get_or_insert_with(&params.clone().into(), &mut || {
2354                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2355                        Ok((size, Cow::Owned(bytes)))
2356                    })?;
2357            let bounds = Bounds {
2358                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2359                size: tile.bounds.size.map(Into::into),
2360            };
2361            let content_mask = self.content_mask().scale(scale_factor);
2362            self.window
2363                .next_frame
2364                .scene
2365                .insert_primitive(MonochromeSprite {
2366                    order: 0,
2367                    pad: 0,
2368                    bounds,
2369                    content_mask,
2370                    color,
2371                    tile,
2372                    transformation: TransformationMatrix::unit(),
2373                });
2374        }
2375        Ok(())
2376    }
2377
2378    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2379    ///
2380    /// The y component of the origin is the baseline of the glyph.
2381    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2382    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2383    /// This method is only useful if you need to paint a single emoji that has already been shaped.
2384    ///
2385    /// This method should only be called as part of the paint phase of element drawing.
2386    pub fn paint_emoji(
2387        &mut self,
2388        origin: Point<Pixels>,
2389        font_id: FontId,
2390        glyph_id: GlyphId,
2391        font_size: Pixels,
2392    ) -> Result<()> {
2393        debug_assert_eq!(
2394            self.window.draw_phase,
2395            DrawPhase::Paint,
2396            "this method can only be called during paint"
2397        );
2398
2399        let scale_factor = self.scale_factor();
2400        let glyph_origin = origin.scale(scale_factor);
2401        let params = RenderGlyphParams {
2402            font_id,
2403            glyph_id,
2404            font_size,
2405            // We don't render emojis with subpixel variants.
2406            subpixel_variant: Default::default(),
2407            scale_factor,
2408            is_emoji: true,
2409        };
2410
2411        let raster_bounds = self.text_system().raster_bounds(&params)?;
2412        if !raster_bounds.is_zero() {
2413            let tile =
2414                self.window
2415                    .sprite_atlas
2416                    .get_or_insert_with(&params.clone().into(), &mut || {
2417                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
2418                        Ok((size, Cow::Owned(bytes)))
2419                    })?;
2420            let bounds = Bounds {
2421                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2422                size: tile.bounds.size.map(Into::into),
2423            };
2424            let content_mask = self.content_mask().scale(scale_factor);
2425
2426            self.window
2427                .next_frame
2428                .scene
2429                .insert_primitive(PolychromeSprite {
2430                    order: 0,
2431                    grayscale: false,
2432                    bounds,
2433                    corner_radii: Default::default(),
2434                    content_mask,
2435                    tile,
2436                });
2437        }
2438        Ok(())
2439    }
2440
2441    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2442    ///
2443    /// This method should only be called as part of the paint phase of element drawing.
2444    pub fn paint_svg(
2445        &mut self,
2446        bounds: Bounds<Pixels>,
2447        path: SharedString,
2448        transformation: TransformationMatrix,
2449        color: Hsla,
2450    ) -> Result<()> {
2451        debug_assert_eq!(
2452            self.window.draw_phase,
2453            DrawPhase::Paint,
2454            "this method can only be called during paint"
2455        );
2456
2457        let scale_factor = self.scale_factor();
2458        let bounds = bounds.scale(scale_factor);
2459        // Render the SVG at twice the size to get a higher quality result.
2460        let params = RenderSvgParams {
2461            path,
2462            size: bounds
2463                .size
2464                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
2465        };
2466
2467        let tile =
2468            self.window
2469                .sprite_atlas
2470                .get_or_insert_with(&params.clone().into(), &mut || {
2471                    let bytes = self.svg_renderer.render(&params)?;
2472                    Ok((params.size, Cow::Owned(bytes)))
2473                })?;
2474        let content_mask = self.content_mask().scale(scale_factor);
2475
2476        self.window
2477            .next_frame
2478            .scene
2479            .insert_primitive(MonochromeSprite {
2480                order: 0,
2481                pad: 0,
2482                bounds,
2483                content_mask,
2484                color,
2485                tile,
2486                transformation,
2487            });
2488
2489        Ok(())
2490    }
2491
2492    /// Paint an image into the scene for the next frame at the current z-index.
2493    ///
2494    /// This method should only be called as part of the paint phase of element drawing.
2495    pub fn paint_image(
2496        &mut self,
2497        bounds: Bounds<Pixels>,
2498        corner_radii: Corners<Pixels>,
2499        data: Arc<ImageData>,
2500        grayscale: bool,
2501    ) -> Result<()> {
2502        debug_assert_eq!(
2503            self.window.draw_phase,
2504            DrawPhase::Paint,
2505            "this method can only be called during paint"
2506        );
2507
2508        let scale_factor = self.scale_factor();
2509        let bounds = bounds.scale(scale_factor);
2510        let params = RenderImageParams { image_id: data.id };
2511
2512        let tile = self
2513            .window
2514            .sprite_atlas
2515            .get_or_insert_with(&params.clone().into(), &mut || {
2516                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
2517            })?;
2518        let content_mask = self.content_mask().scale(scale_factor);
2519        let corner_radii = corner_radii.scale(scale_factor);
2520
2521        self.window
2522            .next_frame
2523            .scene
2524            .insert_primitive(PolychromeSprite {
2525                order: 0,
2526                grayscale,
2527                bounds,
2528                content_mask,
2529                corner_radii,
2530                tile,
2531            });
2532        Ok(())
2533    }
2534
2535    /// Paint a surface into the scene for the next frame at the current z-index.
2536    ///
2537    /// This method should only be called as part of the paint phase of element drawing.
2538    #[cfg(target_os = "macos")]
2539    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2540        debug_assert_eq!(
2541            self.window.draw_phase,
2542            DrawPhase::Paint,
2543            "this method can only be called during paint"
2544        );
2545
2546        let scale_factor = self.scale_factor();
2547        let bounds = bounds.scale(scale_factor);
2548        let content_mask = self.content_mask().scale(scale_factor);
2549        self.window
2550            .next_frame
2551            .scene
2552            .insert_primitive(crate::Surface {
2553                order: 0,
2554                bounds,
2555                content_mask,
2556                image_buffer,
2557            });
2558    }
2559
2560    #[must_use]
2561    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2562    /// layout is being requested, along with the layout ids of any children. This method is called during
2563    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2564    ///
2565    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2566    pub fn request_layout(
2567        &mut self,
2568        style: Style,
2569        children: impl IntoIterator<Item = LayoutId>,
2570    ) -> LayoutId {
2571        debug_assert_eq!(
2572            self.window.draw_phase,
2573            DrawPhase::Prepaint,
2574            "this method can only be called during request_layout, or prepaint"
2575        );
2576
2577        self.app.layout_id_buffer.clear();
2578        self.app.layout_id_buffer.extend(children);
2579        let rem_size = self.rem_size();
2580
2581        self.window.layout_engine.as_mut().unwrap().request_layout(
2582            style,
2583            rem_size,
2584            &self.app.layout_id_buffer,
2585        )
2586    }
2587
2588    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2589    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2590    /// determine the element's size. One place this is used internally is when measuring text.
2591    ///
2592    /// The given closure is invoked at layout time with the known dimensions and available space and
2593    /// returns a `Size`.
2594    ///
2595    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2596    pub fn request_measured_layout<
2597        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
2598            + 'static,
2599    >(
2600        &mut self,
2601        style: Style,
2602        measure: F,
2603    ) -> LayoutId {
2604        debug_assert_eq!(
2605            self.window.draw_phase,
2606            DrawPhase::Prepaint,
2607            "this method can only be called during request_layout, or prepaint"
2608        );
2609
2610        let rem_size = self.rem_size();
2611        self.window
2612            .layout_engine
2613            .as_mut()
2614            .unwrap()
2615            .request_measured_layout(style, rem_size, measure)
2616    }
2617
2618    /// Compute the layout for the given id within the given available space.
2619    /// This method is called for its side effect, typically by the framework prior to painting.
2620    /// After calling it, you can request the bounds of the given layout node id or any descendant.
2621    ///
2622    /// This method should only be called as part of the prepaint phase of element drawing.
2623    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
2624        debug_assert_eq!(
2625            self.window.draw_phase,
2626            DrawPhase::Prepaint,
2627            "this method can only be called during request_layout, or prepaint"
2628        );
2629
2630        let mut layout_engine = self.window.layout_engine.take().unwrap();
2631        layout_engine.compute_layout(layout_id, available_space, self);
2632        self.window.layout_engine = Some(layout_engine);
2633    }
2634
2635    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2636    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2637    ///
2638    /// This method should only be called as part of element drawing.
2639    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2640        debug_assert_eq!(
2641            self.window.draw_phase,
2642            DrawPhase::Prepaint,
2643            "this method can only be called during request_layout, prepaint, or paint"
2644        );
2645
2646        let mut bounds = self
2647            .window
2648            .layout_engine
2649            .as_mut()
2650            .unwrap()
2651            .layout_bounds(layout_id)
2652            .map(Into::into);
2653        bounds.origin += self.element_offset();
2654        bounds
2655    }
2656
2657    /// This method should be called during `prepaint`. You can use
2658    /// the returned [Hitbox] during `paint` or in an event handler
2659    /// to determine whether the inserted hitbox was the topmost.
2660    ///
2661    /// This method should only be called as part of the prepaint phase of element drawing.
2662    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2663        debug_assert_eq!(
2664            self.window.draw_phase,
2665            DrawPhase::Prepaint,
2666            "this method can only be called during prepaint"
2667        );
2668
2669        let content_mask = self.content_mask();
2670        let window = &mut self.window;
2671        let id = window.next_hitbox_id;
2672        window.next_hitbox_id.0 += 1;
2673        let hitbox = Hitbox {
2674            id,
2675            bounds,
2676            content_mask,
2677            opaque,
2678        };
2679        window.next_frame.hitboxes.push(hitbox.clone());
2680        hitbox
2681    }
2682
2683    /// Sets the key context for the current element. This context will be used to translate
2684    /// keybindings into actions.
2685    ///
2686    /// This method should only be called as part of the paint phase of element drawing.
2687    pub fn set_key_context(&mut self, context: KeyContext) {
2688        debug_assert_eq!(
2689            self.window.draw_phase,
2690            DrawPhase::Paint,
2691            "this method can only be called during paint"
2692        );
2693        self.window
2694            .next_frame
2695            .dispatch_tree
2696            .set_key_context(context);
2697    }
2698
2699    /// Sets the focus handle for the current element. This handle will be used to manage focus state
2700    /// and keyboard event dispatch for the element.
2701    ///
2702    /// This method should only be called as part of the paint phase of element drawing.
2703    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
2704        debug_assert_eq!(
2705            self.window.draw_phase,
2706            DrawPhase::Paint,
2707            "this method can only be called during paint"
2708        );
2709        self.window
2710            .next_frame
2711            .dispatch_tree
2712            .set_focus_id(focus_handle.id);
2713    }
2714
2715    /// Sets the view id for the current element, which will be used to manage view caching.
2716    ///
2717    /// This method should only be called as part of element prepaint. We plan on removing this
2718    /// method eventually when we solve some issues that require us to construct editor elements
2719    /// directly instead of always using editors via views.
2720    pub fn set_view_id(&mut self, view_id: EntityId) {
2721        debug_assert_eq!(
2722            self.window.draw_phase,
2723            DrawPhase::Prepaint,
2724            "this method can only be called during prepaint"
2725        );
2726        self.window.next_frame.dispatch_tree.set_view_id(view_id);
2727    }
2728
2729    /// Get the last view id for the current element
2730    pub fn parent_view_id(&mut self) -> Option<EntityId> {
2731        self.window.next_frame.dispatch_tree.parent_view_id()
2732    }
2733
2734    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2735    /// platform to receive textual input with proper integration with concerns such
2736    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2737    /// rendered.
2738    ///
2739    /// This method should only be called as part of the paint phase of element drawing.
2740    ///
2741    /// [element_input_handler]: crate::ElementInputHandler
2742    pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2743        debug_assert_eq!(
2744            self.window.draw_phase,
2745            DrawPhase::Paint,
2746            "this method can only be called during paint"
2747        );
2748
2749        if focus_handle.is_focused(self) {
2750            let cx = self.to_async();
2751            self.window
2752                .next_frame
2753                .input_handlers
2754                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2755        }
2756    }
2757
2758    /// Register a mouse event listener on the window for the next frame. The type of event
2759    /// is determined by the first parameter of the given listener. When the next frame is rendered
2760    /// the listener will be cleared.
2761    ///
2762    /// This method should only be called as part of the paint phase of element drawing.
2763    pub fn on_mouse_event<Event: MouseEvent>(
2764        &mut self,
2765        mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
2766    ) {
2767        debug_assert_eq!(
2768            self.window.draw_phase,
2769            DrawPhase::Paint,
2770            "this method can only be called during paint"
2771        );
2772
2773        self.window.next_frame.mouse_listeners.push(Some(Box::new(
2774            move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
2775                if let Some(event) = event.downcast_ref() {
2776                    handler(event, phase, cx)
2777                }
2778            },
2779        )));
2780    }
2781
2782    /// Register a key event listener on the window for the next frame. The type of event
2783    /// is determined by the first parameter of the given listener. When the next frame is rendered
2784    /// the listener will be cleared.
2785    ///
2786    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2787    /// a specific need to register a global listener.
2788    ///
2789    /// This method should only be called as part of the paint phase of element drawing.
2790    pub fn on_key_event<Event: KeyEvent>(
2791        &mut self,
2792        listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
2793    ) {
2794        debug_assert_eq!(
2795            self.window.draw_phase,
2796            DrawPhase::Paint,
2797            "this method can only be called during paint"
2798        );
2799
2800        self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
2801            move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
2802                if let Some(event) = event.downcast_ref::<Event>() {
2803                    listener(event, phase, cx)
2804                }
2805            },
2806        ));
2807    }
2808
2809    /// Register a modifiers changed event listener on the window for the next frame.
2810    ///
2811    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2812    /// a specific need to register a global listener.
2813    ///
2814    /// This method should only be called as part of the paint phase of element drawing.
2815    pub fn on_modifiers_changed(
2816        &mut self,
2817        listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
2818    ) {
2819        debug_assert_eq!(
2820            self.window.draw_phase,
2821            DrawPhase::Paint,
2822            "this method can only be called during paint"
2823        );
2824
2825        self.window
2826            .next_frame
2827            .dispatch_tree
2828            .on_modifiers_changed(Rc::new(
2829                move |event: &ModifiersChangedEvent, cx: &mut WindowContext<'_>| {
2830                    listener(event, cx)
2831                },
2832            ));
2833    }
2834
2835    fn reset_cursor_style(&self) {
2836        // Set the cursor only if we're the active window.
2837        if self.is_window_active() {
2838            let style = self
2839                .window
2840                .rendered_frame
2841                .cursor_styles
2842                .iter()
2843                .rev()
2844                .find(|request| request.hitbox_id.is_hovered(self))
2845                .map(|request| request.style)
2846                .unwrap_or(CursorStyle::Arrow);
2847            self.platform.set_cursor_style(style);
2848        }
2849    }
2850
2851    /// Dispatch a given keystroke as though the user had typed it.
2852    /// You can create a keystroke with Keystroke::parse("").
2853    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
2854        let keystroke = keystroke.with_simulated_ime();
2855        let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
2856            keystroke: keystroke.clone(),
2857            is_held: false,
2858        }));
2859        if !result.propagate {
2860            return true;
2861        }
2862
2863        if let Some(input) = keystroke.ime_key {
2864            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
2865                input_handler.dispatch_input(&input, self);
2866                self.window.platform_window.set_input_handler(input_handler);
2867                return true;
2868            }
2869        }
2870
2871        false
2872    }
2873
2874    /// Represent this action as a key binding string, to display in the UI.
2875    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
2876        self.bindings_for_action(action)
2877            .into_iter()
2878            .next()
2879            .map(|binding| {
2880                binding
2881                    .keystrokes()
2882                    .iter()
2883                    .map(ToString::to_string)
2884                    .collect::<Vec<_>>()
2885                    .join(" ")
2886            })
2887            .unwrap_or_else(|| action.name().to_string())
2888    }
2889
2890    /// Dispatch a mouse or keyboard event on the window.
2891    #[profiling::function]
2892    pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
2893        self.window.last_input_timestamp.set(Instant::now());
2894        // Handlers may set this to false by calling `stop_propagation`.
2895        self.app.propagate_event = true;
2896        // Handlers may set this to true by calling `prevent_default`.
2897        self.window.default_prevented = false;
2898
2899        let event = match event {
2900            // Track the mouse position with our own state, since accessing the platform
2901            // API for the mouse position can only occur on the main thread.
2902            PlatformInput::MouseMove(mouse_move) => {
2903                self.window.mouse_position = mouse_move.position;
2904                self.window.modifiers = mouse_move.modifiers;
2905                PlatformInput::MouseMove(mouse_move)
2906            }
2907            PlatformInput::MouseDown(mouse_down) => {
2908                self.window.mouse_position = mouse_down.position;
2909                self.window.modifiers = mouse_down.modifiers;
2910                PlatformInput::MouseDown(mouse_down)
2911            }
2912            PlatformInput::MouseUp(mouse_up) => {
2913                self.window.mouse_position = mouse_up.position;
2914                self.window.modifiers = mouse_up.modifiers;
2915                PlatformInput::MouseUp(mouse_up)
2916            }
2917            PlatformInput::MouseExited(mouse_exited) => {
2918                self.window.modifiers = mouse_exited.modifiers;
2919                PlatformInput::MouseExited(mouse_exited)
2920            }
2921            PlatformInput::ModifiersChanged(modifiers_changed) => {
2922                self.window.modifiers = modifiers_changed.modifiers;
2923                PlatformInput::ModifiersChanged(modifiers_changed)
2924            }
2925            PlatformInput::ScrollWheel(scroll_wheel) => {
2926                self.window.mouse_position = scroll_wheel.position;
2927                self.window.modifiers = scroll_wheel.modifiers;
2928                PlatformInput::ScrollWheel(scroll_wheel)
2929            }
2930            // Translate dragging and dropping of external files from the operating system
2931            // to internal drag and drop events.
2932            PlatformInput::FileDrop(file_drop) => match file_drop {
2933                FileDropEvent::Entered { position, paths } => {
2934                    self.window.mouse_position = position;
2935                    if self.active_drag.is_none() {
2936                        self.active_drag = Some(AnyDrag {
2937                            value: Box::new(paths.clone()),
2938                            view: self.new_view(|_| paths).into(),
2939                            cursor_offset: position,
2940                        });
2941                    }
2942                    PlatformInput::MouseMove(MouseMoveEvent {
2943                        position,
2944                        pressed_button: Some(MouseButton::Left),
2945                        modifiers: Modifiers::default(),
2946                    })
2947                }
2948                FileDropEvent::Pending { position } => {
2949                    self.window.mouse_position = position;
2950                    PlatformInput::MouseMove(MouseMoveEvent {
2951                        position,
2952                        pressed_button: Some(MouseButton::Left),
2953                        modifiers: Modifiers::default(),
2954                    })
2955                }
2956                FileDropEvent::Submit { position } => {
2957                    self.activate(true);
2958                    self.window.mouse_position = position;
2959                    PlatformInput::MouseUp(MouseUpEvent {
2960                        button: MouseButton::Left,
2961                        position,
2962                        modifiers: Modifiers::default(),
2963                        click_count: 1,
2964                    })
2965                }
2966                FileDropEvent::Exited => {
2967                    self.active_drag.take();
2968                    PlatformInput::FileDrop(FileDropEvent::Exited)
2969                }
2970            },
2971            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
2972        };
2973
2974        if let Some(any_mouse_event) = event.mouse_event() {
2975            self.dispatch_mouse_event(any_mouse_event);
2976        } else if let Some(any_key_event) = event.keyboard_event() {
2977            self.dispatch_key_event(any_key_event);
2978        }
2979
2980        DispatchEventResult {
2981            propagate: self.app.propagate_event,
2982            default_prevented: self.window.default_prevented,
2983        }
2984    }
2985
2986    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
2987        let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
2988        if hit_test != self.window.mouse_hit_test {
2989            self.window.mouse_hit_test = hit_test;
2990            self.reset_cursor_style();
2991        }
2992
2993        let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
2994
2995        // Capture phase, events bubble from back to front. Handlers for this phase are used for
2996        // special purposes, such as detecting events outside of a given Bounds.
2997        for listener in &mut mouse_listeners {
2998            let listener = listener.as_mut().unwrap();
2999            listener(event, DispatchPhase::Capture, self);
3000            if !self.app.propagate_event {
3001                break;
3002            }
3003        }
3004
3005        // Bubble phase, where most normal handlers do their work.
3006        if self.app.propagate_event {
3007            for listener in mouse_listeners.iter_mut().rev() {
3008                let listener = listener.as_mut().unwrap();
3009                listener(event, DispatchPhase::Bubble, self);
3010                if !self.app.propagate_event {
3011                    break;
3012                }
3013            }
3014        }
3015
3016        self.window.rendered_frame.mouse_listeners = mouse_listeners;
3017
3018        if self.has_active_drag() {
3019            if event.is::<MouseMoveEvent>() {
3020                // If this was a mouse move event, redraw the window so that the
3021                // active drag can follow the mouse cursor.
3022                self.refresh();
3023            } else if event.is::<MouseUpEvent>() {
3024                // If this was a mouse up event, cancel the active drag and redraw
3025                // the window.
3026                self.active_drag = None;
3027                self.refresh();
3028            }
3029        }
3030    }
3031
3032    fn dispatch_key_event(&mut self, event: &dyn Any) {
3033        if self.window.dirty.get() {
3034            self.draw();
3035        }
3036
3037        let node_id = self
3038            .window
3039            .focus
3040            .and_then(|focus_id| {
3041                self.window
3042                    .rendered_frame
3043                    .dispatch_tree
3044                    .focusable_node_id(focus_id)
3045            })
3046            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3047
3048        let dispatch_path = self
3049            .window
3050            .rendered_frame
3051            .dispatch_tree
3052            .dispatch_path(node_id);
3053
3054        if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3055            let KeymatchResult { bindings, pending } = self
3056                .window
3057                .rendered_frame
3058                .dispatch_tree
3059                .dispatch_key(&key_down_event.keystroke, &dispatch_path);
3060
3061            if pending {
3062                let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3063                if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
3064                {
3065                    currently_pending = PendingInput::default();
3066                }
3067                currently_pending.focus = self.window.focus;
3068                currently_pending
3069                    .keystrokes
3070                    .push(key_down_event.keystroke.clone());
3071                for binding in bindings {
3072                    currently_pending.bindings.push(binding);
3073                }
3074
3075                currently_pending.timer = Some(self.spawn(|mut cx| async move {
3076                    cx.background_executor.timer(Duration::from_secs(1)).await;
3077                    cx.update(move |cx| {
3078                        cx.clear_pending_keystrokes();
3079                        let Some(currently_pending) = cx.window.pending_input.take() else {
3080                            return;
3081                        };
3082                        cx.replay_pending_input(currently_pending)
3083                    })
3084                    .log_err();
3085                }));
3086
3087                self.window.pending_input = Some(currently_pending);
3088
3089                self.propagate_event = false;
3090                return;
3091            } else if let Some(currently_pending) = self.window.pending_input.take() {
3092                if bindings
3093                    .iter()
3094                    .all(|binding| !currently_pending.used_by_binding(binding))
3095                {
3096                    self.replay_pending_input(currently_pending)
3097                }
3098            }
3099
3100            if !bindings.is_empty() {
3101                self.clear_pending_keystrokes();
3102            }
3103
3104            self.propagate_event = true;
3105            for binding in bindings {
3106                self.dispatch_action_on_node(node_id, binding.action.as_ref());
3107                if !self.propagate_event {
3108                    self.dispatch_keystroke_observers(event, Some(binding.action));
3109                    return;
3110                }
3111            }
3112        }
3113
3114        self.dispatch_key_down_up_event(event, &dispatch_path);
3115        if !self.propagate_event {
3116            return;
3117        }
3118
3119        self.dispatch_modifiers_changed_event(event, &dispatch_path);
3120        if !self.propagate_event {
3121            return;
3122        }
3123
3124        self.dispatch_keystroke_observers(event, None);
3125    }
3126
3127    fn dispatch_key_down_up_event(
3128        &mut self,
3129        event: &dyn Any,
3130        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3131    ) {
3132        // Capture phase
3133        for node_id in dispatch_path {
3134            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3135
3136            for key_listener in node.key_listeners.clone() {
3137                key_listener(event, DispatchPhase::Capture, self);
3138                if !self.propagate_event {
3139                    return;
3140                }
3141            }
3142        }
3143
3144        // Bubble phase
3145        for node_id in dispatch_path.iter().rev() {
3146            // Handle low level key events
3147            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3148            for key_listener in node.key_listeners.clone() {
3149                key_listener(event, DispatchPhase::Bubble, self);
3150                if !self.propagate_event {
3151                    return;
3152                }
3153            }
3154        }
3155    }
3156
3157    fn dispatch_modifiers_changed_event(
3158        &mut self,
3159        event: &dyn Any,
3160        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3161    ) {
3162        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3163            return;
3164        };
3165        for node_id in dispatch_path.iter().rev() {
3166            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3167            for listener in node.modifiers_changed_listeners.clone() {
3168                listener(event, self);
3169                if !self.propagate_event {
3170                    return;
3171                }
3172            }
3173        }
3174    }
3175
3176    /// Determine whether a potential multi-stroke key binding is in progress on this window.
3177    pub fn has_pending_keystrokes(&self) -> bool {
3178        self.window
3179            .rendered_frame
3180            .dispatch_tree
3181            .has_pending_keystrokes()
3182    }
3183
3184    fn replay_pending_input(&mut self, currently_pending: PendingInput) {
3185        let node_id = self
3186            .window
3187            .focus
3188            .and_then(|focus_id| {
3189                self.window
3190                    .rendered_frame
3191                    .dispatch_tree
3192                    .focusable_node_id(focus_id)
3193            })
3194            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3195
3196        if self.window.focus != currently_pending.focus {
3197            return;
3198        }
3199
3200        let input = currently_pending.input();
3201
3202        self.propagate_event = true;
3203        for binding in currently_pending.bindings {
3204            self.dispatch_action_on_node(node_id, binding.action.as_ref());
3205            if !self.propagate_event {
3206                return;
3207            }
3208        }
3209
3210        let dispatch_path = self
3211            .window
3212            .rendered_frame
3213            .dispatch_tree
3214            .dispatch_path(node_id);
3215
3216        for keystroke in currently_pending.keystrokes {
3217            let event = KeyDownEvent {
3218                keystroke,
3219                is_held: false,
3220            };
3221
3222            self.dispatch_key_down_up_event(&event, &dispatch_path);
3223            if !self.propagate_event {
3224                return;
3225            }
3226        }
3227
3228        if !input.is_empty() {
3229            if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3230                input_handler.dispatch_input(&input, self);
3231                self.window.platform_window.set_input_handler(input_handler)
3232            }
3233        }
3234    }
3235
3236    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3237        let dispatch_path = self
3238            .window
3239            .rendered_frame
3240            .dispatch_tree
3241            .dispatch_path(node_id);
3242
3243        // Capture phase for global actions.
3244        self.propagate_event = true;
3245        if let Some(mut global_listeners) = self
3246            .global_action_listeners
3247            .remove(&action.as_any().type_id())
3248        {
3249            for listener in &global_listeners {
3250                listener(action.as_any(), DispatchPhase::Capture, self);
3251                if !self.propagate_event {
3252                    break;
3253                }
3254            }
3255
3256            global_listeners.extend(
3257                self.global_action_listeners
3258                    .remove(&action.as_any().type_id())
3259                    .unwrap_or_default(),
3260            );
3261
3262            self.global_action_listeners
3263                .insert(action.as_any().type_id(), global_listeners);
3264        }
3265
3266        if !self.propagate_event {
3267            return;
3268        }
3269
3270        // Capture phase for window actions.
3271        for node_id in &dispatch_path {
3272            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3273            for DispatchActionListener {
3274                action_type,
3275                listener,
3276            } in node.action_listeners.clone()
3277            {
3278                let any_action = action.as_any();
3279                if action_type == any_action.type_id() {
3280                    listener(any_action, DispatchPhase::Capture, self);
3281
3282                    if !self.propagate_event {
3283                        return;
3284                    }
3285                }
3286            }
3287        }
3288
3289        // Bubble phase for window actions.
3290        for node_id in dispatch_path.iter().rev() {
3291            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3292            for DispatchActionListener {
3293                action_type,
3294                listener,
3295            } in node.action_listeners.clone()
3296            {
3297                let any_action = action.as_any();
3298                if action_type == any_action.type_id() {
3299                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3300                    listener(any_action, DispatchPhase::Bubble, self);
3301
3302                    if !self.propagate_event {
3303                        return;
3304                    }
3305                }
3306            }
3307        }
3308
3309        // Bubble phase for global actions.
3310        if let Some(mut global_listeners) = self
3311            .global_action_listeners
3312            .remove(&action.as_any().type_id())
3313        {
3314            for listener in global_listeners.iter().rev() {
3315                self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3316
3317                listener(action.as_any(), DispatchPhase::Bubble, self);
3318                if !self.propagate_event {
3319                    break;
3320                }
3321            }
3322
3323            global_listeners.extend(
3324                self.global_action_listeners
3325                    .remove(&action.as_any().type_id())
3326                    .unwrap_or_default(),
3327            );
3328
3329            self.global_action_listeners
3330                .insert(action.as_any().type_id(), global_listeners);
3331        }
3332    }
3333
3334    /// Register the given handler to be invoked whenever the global of the given type
3335    /// is updated.
3336    pub fn observe_global<G: Global>(
3337        &mut self,
3338        f: impl Fn(&mut WindowContext<'_>) + 'static,
3339    ) -> Subscription {
3340        let window_handle = self.window.handle;
3341        let (subscription, activate) = self.global_observers.insert(
3342            TypeId::of::<G>(),
3343            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3344        );
3345        self.app.defer(move |_| activate());
3346        subscription
3347    }
3348
3349    /// Focus the current window and bring it to the foreground at the platform level.
3350    pub fn activate_window(&self) {
3351        self.window.platform_window.activate();
3352    }
3353
3354    /// Minimize the current window at the platform level.
3355    pub fn minimize_window(&self) {
3356        self.window.platform_window.minimize();
3357    }
3358
3359    /// Toggle full screen status on the current window at the platform level.
3360    pub fn toggle_fullscreen(&self) {
3361        self.window.platform_window.toggle_fullscreen();
3362    }
3363
3364    /// Present a platform dialog.
3365    /// The provided message will be presented, along with buttons for each answer.
3366    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3367    pub fn prompt(
3368        &mut self,
3369        level: PromptLevel,
3370        message: &str,
3371        detail: Option<&str>,
3372        answers: &[&str],
3373    ) -> oneshot::Receiver<usize> {
3374        let prompt_builder = self.app.prompt_builder.take();
3375        let Some(prompt_builder) = prompt_builder else {
3376            unreachable!("Re-entrant window prompting is not supported by GPUI");
3377        };
3378
3379        let receiver = match &prompt_builder {
3380            PromptBuilder::Default => self
3381                .window
3382                .platform_window
3383                .prompt(level, message, detail, answers)
3384                .unwrap_or_else(|| {
3385                    self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3386                }),
3387            PromptBuilder::Custom(_) => {
3388                self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3389            }
3390        };
3391
3392        self.app.prompt_builder = Some(prompt_builder);
3393
3394        receiver
3395    }
3396
3397    fn build_custom_prompt(
3398        &mut self,
3399        prompt_builder: &PromptBuilder,
3400        level: PromptLevel,
3401        message: &str,
3402        detail: Option<&str>,
3403        answers: &[&str],
3404    ) -> oneshot::Receiver<usize> {
3405        let (sender, receiver) = oneshot::channel();
3406        let handle = PromptHandle::new(sender);
3407        let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3408        self.window.prompt = Some(handle);
3409        receiver
3410    }
3411
3412    /// Returns all available actions for the focused element.
3413    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3414        let node_id = self
3415            .window
3416            .focus
3417            .and_then(|focus_id| {
3418                self.window
3419                    .rendered_frame
3420                    .dispatch_tree
3421                    .focusable_node_id(focus_id)
3422            })
3423            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3424
3425        let mut actions = self
3426            .window
3427            .rendered_frame
3428            .dispatch_tree
3429            .available_actions(node_id);
3430        for action_type in self.global_action_listeners.keys() {
3431            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3432                let action = self.actions.build_action_type(action_type).ok();
3433                if let Some(action) = action {
3434                    actions.insert(ix, action);
3435                }
3436            }
3437        }
3438        actions
3439    }
3440
3441    /// Returns key bindings that invoke the given action on the currently focused element.
3442    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3443        self.window
3444            .rendered_frame
3445            .dispatch_tree
3446            .bindings_for_action(
3447                action,
3448                &self.window.rendered_frame.dispatch_tree.context_stack,
3449            )
3450    }
3451
3452    /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3453    pub fn bindings_for_action_in(
3454        &self,
3455        action: &dyn Action,
3456        focus_handle: &FocusHandle,
3457    ) -> Vec<KeyBinding> {
3458        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3459
3460        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3461            return vec![];
3462        };
3463        let context_stack: Vec<_> = dispatch_tree
3464            .dispatch_path(node_id)
3465            .into_iter()
3466            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3467            .collect();
3468        dispatch_tree.bindings_for_action(action, &context_stack)
3469    }
3470
3471    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3472    pub fn listener_for<V: Render, E>(
3473        &self,
3474        view: &View<V>,
3475        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3476    ) -> impl Fn(&E, &mut WindowContext) + 'static {
3477        let view = view.downgrade();
3478        move |e: &E, cx: &mut WindowContext| {
3479            view.update(cx, |view, cx| f(view, e, cx)).ok();
3480        }
3481    }
3482
3483    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3484    pub fn handler_for<V: Render>(
3485        &self,
3486        view: &View<V>,
3487        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3488    ) -> impl Fn(&mut WindowContext) {
3489        let view = view.downgrade();
3490        move |cx: &mut WindowContext| {
3491            view.update(cx, |view, cx| f(view, cx)).ok();
3492        }
3493    }
3494
3495    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3496    /// If the callback returns false, the window won't be closed.
3497    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3498        let mut this = self.to_async();
3499        self.window
3500            .platform_window
3501            .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3502    }
3503
3504    /// Register an action listener on the window for the next frame. The type of action
3505    /// is determined by the first parameter of the given listener. When the next frame is rendered
3506    /// the listener will be cleared.
3507    ///
3508    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3509    /// a specific need to register a global listener.
3510    pub fn on_action(
3511        &mut self,
3512        action_type: TypeId,
3513        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3514    ) {
3515        self.window
3516            .next_frame
3517            .dispatch_tree
3518            .on_action(action_type, Rc::new(listener));
3519    }
3520}
3521
3522#[cfg(target_os = "windows")]
3523impl WindowContext<'_> {
3524    /// Returns the raw HWND handle for the window.
3525    pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3526        self.window.platform_window.get_raw_handle()
3527    }
3528}
3529
3530impl Context for WindowContext<'_> {
3531    type Result<T> = T;
3532
3533    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3534    where
3535        T: 'static,
3536    {
3537        let slot = self.app.entities.reserve();
3538        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3539        self.entities.insert(slot, model)
3540    }
3541
3542    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3543        self.app.reserve_model()
3544    }
3545
3546    fn insert_model<T: 'static>(
3547        &mut self,
3548        reservation: crate::Reservation<T>,
3549        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3550    ) -> Self::Result<Model<T>> {
3551        self.app.insert_model(reservation, build_model)
3552    }
3553
3554    fn update_model<T: 'static, R>(
3555        &mut self,
3556        model: &Model<T>,
3557        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3558    ) -> R {
3559        let mut entity = self.entities.lease(model);
3560        let result = update(
3561            &mut *entity,
3562            &mut ModelContext::new(&mut *self.app, model.downgrade()),
3563        );
3564        self.entities.end_lease(entity);
3565        result
3566    }
3567
3568    fn read_model<T, R>(
3569        &self,
3570        handle: &Model<T>,
3571        read: impl FnOnce(&T, &AppContext) -> R,
3572    ) -> Self::Result<R>
3573    where
3574        T: 'static,
3575    {
3576        let entity = self.entities.read(handle);
3577        read(entity, &*self.app)
3578    }
3579
3580    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3581    where
3582        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3583    {
3584        if window == self.window.handle {
3585            let root_view = self.window.root_view.clone().unwrap();
3586            Ok(update(root_view, self))
3587        } else {
3588            window.update(self.app, update)
3589        }
3590    }
3591
3592    fn read_window<T, R>(
3593        &self,
3594        window: &WindowHandle<T>,
3595        read: impl FnOnce(View<T>, &AppContext) -> R,
3596    ) -> Result<R>
3597    where
3598        T: 'static,
3599    {
3600        if window.any_handle == self.window.handle {
3601            let root_view = self
3602                .window
3603                .root_view
3604                .clone()
3605                .unwrap()
3606                .downcast::<T>()
3607                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3608            Ok(read(root_view, self))
3609        } else {
3610            self.app.read_window(window, read)
3611        }
3612    }
3613}
3614
3615impl VisualContext for WindowContext<'_> {
3616    fn new_view<V>(
3617        &mut self,
3618        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3619    ) -> Self::Result<View<V>>
3620    where
3621        V: 'static + Render,
3622    {
3623        let slot = self.app.entities.reserve();
3624        let view = View {
3625            model: slot.clone(),
3626        };
3627        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3628        let entity = build_view_state(&mut cx);
3629        cx.entities.insert(slot, entity);
3630
3631        // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3632        fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3633            cx.new_view_observers.clone().retain(&tid, |observer| {
3634                let any_view = view.clone();
3635                (observer)(any_view, cx);
3636                true
3637            });
3638        }
3639        notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3640
3641        view
3642    }
3643
3644    /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3645    fn update_view<T: 'static, R>(
3646        &mut self,
3647        view: &View<T>,
3648        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3649    ) -> Self::Result<R> {
3650        let mut lease = self.app.entities.lease(&view.model);
3651        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3652        let result = update(&mut *lease, &mut cx);
3653        cx.app.entities.end_lease(lease);
3654        result
3655    }
3656
3657    fn replace_root_view<V>(
3658        &mut self,
3659        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3660    ) -> Self::Result<View<V>>
3661    where
3662        V: 'static + Render,
3663    {
3664        let view = self.new_view(build_view);
3665        self.window.root_view = Some(view.clone().into());
3666        self.refresh();
3667        view
3668    }
3669
3670    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3671        self.update_view(view, |view, cx| {
3672            view.focus_handle(cx).clone().focus(cx);
3673        })
3674    }
3675
3676    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3677    where
3678        V: ManagedView,
3679    {
3680        self.update_view(view, |_, cx| cx.emit(DismissEvent))
3681    }
3682}
3683
3684impl<'a> std::ops::Deref for WindowContext<'a> {
3685    type Target = AppContext;
3686
3687    fn deref(&self) -> &Self::Target {
3688        self.app
3689    }
3690}
3691
3692impl<'a> std::ops::DerefMut for WindowContext<'a> {
3693    fn deref_mut(&mut self) -> &mut Self::Target {
3694        self.app
3695    }
3696}
3697
3698impl<'a> Borrow<AppContext> for WindowContext<'a> {
3699    fn borrow(&self) -> &AppContext {
3700        self.app
3701    }
3702}
3703
3704impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3705    fn borrow_mut(&mut self) -> &mut AppContext {
3706        self.app
3707    }
3708}
3709
3710/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3711pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3712    #[doc(hidden)]
3713    fn app_mut(&mut self) -> &mut AppContext {
3714        self.borrow_mut()
3715    }
3716
3717    #[doc(hidden)]
3718    fn app(&self) -> &AppContext {
3719        self.borrow()
3720    }
3721
3722    #[doc(hidden)]
3723    fn window(&self) -> &Window {
3724        self.borrow()
3725    }
3726
3727    #[doc(hidden)]
3728    fn window_mut(&mut self) -> &mut Window {
3729        self.borrow_mut()
3730    }
3731}
3732
3733impl Borrow<Window> for WindowContext<'_> {
3734    fn borrow(&self) -> &Window {
3735        self.window
3736    }
3737}
3738
3739impl BorrowMut<Window> for WindowContext<'_> {
3740    fn borrow_mut(&mut self) -> &mut Window {
3741        self.window
3742    }
3743}
3744
3745impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
3746
3747/// Provides access to application state that is specialized for a particular [`View`].
3748/// Allows you to interact with focus, emit events, etc.
3749/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
3750/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
3751pub struct ViewContext<'a, V> {
3752    window_cx: WindowContext<'a>,
3753    view: &'a View<V>,
3754}
3755
3756impl<V> Borrow<AppContext> for ViewContext<'_, V> {
3757    fn borrow(&self) -> &AppContext {
3758        &*self.window_cx.app
3759    }
3760}
3761
3762impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
3763    fn borrow_mut(&mut self) -> &mut AppContext {
3764        &mut *self.window_cx.app
3765    }
3766}
3767
3768impl<V> Borrow<Window> for ViewContext<'_, V> {
3769    fn borrow(&self) -> &Window {
3770        &*self.window_cx.window
3771    }
3772}
3773
3774impl<V> BorrowMut<Window> for ViewContext<'_, V> {
3775    fn borrow_mut(&mut self) -> &mut Window {
3776        &mut *self.window_cx.window
3777    }
3778}
3779
3780impl<'a, V: 'static> ViewContext<'a, V> {
3781    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
3782        Self {
3783            window_cx: WindowContext::new(app, window),
3784            view,
3785        }
3786    }
3787
3788    /// Get the entity_id of this view.
3789    pub fn entity_id(&self) -> EntityId {
3790        self.view.entity_id()
3791    }
3792
3793    /// Get the view pointer underlying this context.
3794    pub fn view(&self) -> &View<V> {
3795        self.view
3796    }
3797
3798    /// Get the model underlying this view.
3799    pub fn model(&self) -> &Model<V> {
3800        &self.view.model
3801    }
3802
3803    /// Access the underlying window context.
3804    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
3805        &mut self.window_cx
3806    }
3807
3808    /// Sets a given callback to be run on the next frame.
3809    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
3810    where
3811        V: 'static,
3812    {
3813        let view = self.view().clone();
3814        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
3815    }
3816
3817    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
3818    /// that are currently on the stack to be returned to the app.
3819    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
3820        let view = self.view().downgrade();
3821        self.window_cx.defer(move |cx| {
3822            view.update(cx, f).ok();
3823        });
3824    }
3825
3826    /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
3827    pub fn observe<V2, E>(
3828        &mut self,
3829        entity: &E,
3830        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
3831    ) -> Subscription
3832    where
3833        V2: 'static,
3834        V: 'static,
3835        E: Entity<V2>,
3836    {
3837        let view = self.view().downgrade();
3838        let entity_id = entity.entity_id();
3839        let entity = entity.downgrade();
3840        let window_handle = self.window.handle;
3841        self.app.new_observer(
3842            entity_id,
3843            Box::new(move |cx| {
3844                window_handle
3845                    .update(cx, |_, cx| {
3846                        if let Some(handle) = E::upgrade_from(&entity) {
3847                            view.update(cx, |this, cx| on_notify(this, handle, cx))
3848                                .is_ok()
3849                        } else {
3850                            false
3851                        }
3852                    })
3853                    .unwrap_or(false)
3854            }),
3855        )
3856    }
3857
3858    /// Subscribe to events emitted by another model or view.
3859    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3860    /// 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.
3861    pub fn subscribe<V2, E, Evt>(
3862        &mut self,
3863        entity: &E,
3864        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
3865    ) -> Subscription
3866    where
3867        V2: EventEmitter<Evt>,
3868        E: Entity<V2>,
3869        Evt: 'static,
3870    {
3871        let view = self.view().downgrade();
3872        let entity_id = entity.entity_id();
3873        let handle = entity.downgrade();
3874        let window_handle = self.window.handle;
3875        self.app.new_subscription(
3876            entity_id,
3877            (
3878                TypeId::of::<Evt>(),
3879                Box::new(move |event, cx| {
3880                    window_handle
3881                        .update(cx, |_, cx| {
3882                            if let Some(handle) = E::upgrade_from(&handle) {
3883                                let event = event.downcast_ref().expect("invalid event type");
3884                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
3885                                    .is_ok()
3886                            } else {
3887                                false
3888                            }
3889                        })
3890                        .unwrap_or(false)
3891                }),
3892            ),
3893        )
3894    }
3895
3896    /// Register a callback to be invoked when the view is released.
3897    ///
3898    /// The callback receives a handle to the view's window. This handle may be
3899    /// invalid, if the window was closed before the view was released.
3900    pub fn on_release(
3901        &mut self,
3902        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
3903    ) -> Subscription {
3904        let window_handle = self.window.handle;
3905        let (subscription, activate) = self.app.release_listeners.insert(
3906            self.view.model.entity_id,
3907            Box::new(move |this, cx| {
3908                let this = this.downcast_mut().expect("invalid entity type");
3909                on_release(this, window_handle, cx)
3910            }),
3911        );
3912        activate();
3913        subscription
3914    }
3915
3916    /// Register a callback to be invoked when the given Model or View is released.
3917    pub fn observe_release<V2, E>(
3918        &mut self,
3919        entity: &E,
3920        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
3921    ) -> Subscription
3922    where
3923        V: 'static,
3924        V2: 'static,
3925        E: Entity<V2>,
3926    {
3927        let view = self.view().downgrade();
3928        let entity_id = entity.entity_id();
3929        let window_handle = self.window.handle;
3930        let (subscription, activate) = self.app.release_listeners.insert(
3931            entity_id,
3932            Box::new(move |entity, cx| {
3933                let entity = entity.downcast_mut().expect("invalid entity type");
3934                let _ = window_handle.update(cx, |_, cx| {
3935                    view.update(cx, |this, cx| on_release(this, entity, cx))
3936                });
3937            }),
3938        );
3939        activate();
3940        subscription
3941    }
3942
3943    /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
3944    /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
3945    pub fn notify(&mut self) {
3946        self.window_cx.notify(self.view.entity_id());
3947    }
3948
3949    /// Register a callback to be invoked when the window is resized.
3950    pub fn observe_window_bounds(
3951        &mut self,
3952        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3953    ) -> Subscription {
3954        let view = self.view.downgrade();
3955        let (subscription, activate) = self.window.bounds_observers.insert(
3956            (),
3957            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
3958        );
3959        activate();
3960        subscription
3961    }
3962
3963    /// Register a callback to be invoked when the window is activated or deactivated.
3964    pub fn observe_window_activation(
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.activation_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    /// Registers a callback to be invoked when the window appearance changes.
3978    pub fn observe_window_appearance(
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.appearance_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    /// Register a listener to be called when the given focus handle receives focus.
3992    /// Returns a subscription and persists until the subscription is dropped.
3993    pub fn on_focus(
3994        &mut self,
3995        handle: &FocusHandle,
3996        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
3997    ) -> Subscription {
3998        let view = self.view.downgrade();
3999        let focus_id = handle.id;
4000        let (subscription, activate) =
4001            self.window.new_focus_listener(Box::new(move |event, cx| {
4002                view.update(cx, |view, cx| {
4003                    if event.previous_focus_path.last() != Some(&focus_id)
4004                        && event.current_focus_path.last() == Some(&focus_id)
4005                    {
4006                        listener(view, cx)
4007                    }
4008                })
4009                .is_ok()
4010            }));
4011        self.app.defer(|_| activate());
4012        subscription
4013    }
4014
4015    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4016    /// Returns a subscription and persists until the subscription is dropped.
4017    pub fn on_focus_in(
4018        &mut self,
4019        handle: &FocusHandle,
4020        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4021    ) -> Subscription {
4022        let view = self.view.downgrade();
4023        let focus_id = handle.id;
4024        let (subscription, activate) =
4025            self.window.new_focus_listener(Box::new(move |event, cx| {
4026                view.update(cx, |view, cx| {
4027                    if !event.previous_focus_path.contains(&focus_id)
4028                        && event.current_focus_path.contains(&focus_id)
4029                    {
4030                        listener(view, cx)
4031                    }
4032                })
4033                .is_ok()
4034            }));
4035        self.app.defer(move |_| activate());
4036        subscription
4037    }
4038
4039    /// Register a listener to be called when the given focus handle loses focus.
4040    /// Returns a subscription and persists until the subscription is dropped.
4041    pub fn on_blur(
4042        &mut self,
4043        handle: &FocusHandle,
4044        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4045    ) -> Subscription {
4046        let view = self.view.downgrade();
4047        let focus_id = handle.id;
4048        let (subscription, activate) =
4049            self.window.new_focus_listener(Box::new(move |event, cx| {
4050                view.update(cx, |view, cx| {
4051                    if event.previous_focus_path.last() == Some(&focus_id)
4052                        && event.current_focus_path.last() != Some(&focus_id)
4053                    {
4054                        listener(view, cx)
4055                    }
4056                })
4057                .is_ok()
4058            }));
4059        self.app.defer(move |_| activate());
4060        subscription
4061    }
4062
4063    /// Register a listener to be called when nothing in the window has focus.
4064    /// This typically happens when the node that was focused is removed from the tree,
4065    /// and this callback lets you chose a default place to restore the users focus.
4066    /// Returns a subscription and persists until the subscription is dropped.
4067    pub fn on_focus_lost(
4068        &mut self,
4069        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4070    ) -> Subscription {
4071        let view = self.view.downgrade();
4072        let (subscription, activate) = self.window.focus_lost_listeners.insert(
4073            (),
4074            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4075        );
4076        activate();
4077        subscription
4078    }
4079
4080    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4081    /// Returns a subscription and persists until the subscription is dropped.
4082    pub fn on_focus_out(
4083        &mut self,
4084        handle: &FocusHandle,
4085        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4086    ) -> Subscription {
4087        let view = self.view.downgrade();
4088        let focus_id = handle.id;
4089        let (subscription, activate) =
4090            self.window.new_focus_listener(Box::new(move |event, cx| {
4091                view.update(cx, |view, cx| {
4092                    if event.previous_focus_path.contains(&focus_id)
4093                        && !event.current_focus_path.contains(&focus_id)
4094                    {
4095                        listener(view, cx)
4096                    }
4097                })
4098                .is_ok()
4099            }));
4100        self.app.defer(move |_| activate());
4101        subscription
4102    }
4103
4104    /// Schedule a future to be run asynchronously.
4105    /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4106    /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4107    /// The returned future will be polled on the main thread.
4108    pub fn spawn<Fut, R>(
4109        &mut self,
4110        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4111    ) -> Task<R>
4112    where
4113        R: 'static,
4114        Fut: Future<Output = R> + 'static,
4115    {
4116        let view = self.view().downgrade();
4117        self.window_cx.spawn(|cx| f(view, cx))
4118    }
4119
4120    /// Register a callback to be invoked when the given global state changes.
4121    pub fn observe_global<G: Global>(
4122        &mut self,
4123        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4124    ) -> Subscription {
4125        let window_handle = self.window.handle;
4126        let view = self.view().downgrade();
4127        let (subscription, activate) = self.global_observers.insert(
4128            TypeId::of::<G>(),
4129            Box::new(move |cx| {
4130                window_handle
4131                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4132                    .unwrap_or(false)
4133            }),
4134        );
4135        self.app.defer(move |_| activate());
4136        subscription
4137    }
4138
4139    /// Register a callback to be invoked when the given Action type is dispatched to the window.
4140    pub fn on_action(
4141        &mut self,
4142        action_type: TypeId,
4143        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4144    ) {
4145        let handle = self.view().clone();
4146        self.window_cx
4147            .on_action(action_type, move |action, phase, cx| {
4148                handle.update(cx, |view, cx| {
4149                    listener(view, action, phase, cx);
4150                })
4151            });
4152    }
4153
4154    /// Emit an event to be handled any other views that have subscribed via [ViewContext::subscribe].
4155    pub fn emit<Evt>(&mut self, event: Evt)
4156    where
4157        Evt: 'static,
4158        V: EventEmitter<Evt>,
4159    {
4160        let emitter = self.view.model.entity_id;
4161        self.app.push_effect(Effect::Emit {
4162            emitter,
4163            event_type: TypeId::of::<Evt>(),
4164            event: Box::new(event),
4165        });
4166    }
4167
4168    /// Move focus to the current view, assuming it implements [`FocusableView`].
4169    pub fn focus_self(&mut self)
4170    where
4171        V: FocusableView,
4172    {
4173        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4174    }
4175
4176    /// Convenience method for accessing view state in an event callback.
4177    ///
4178    /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4179    /// but it's often useful to be able to access view state in these
4180    /// callbacks. This method provides a convenient way to do so.
4181    pub fn listener<E>(
4182        &self,
4183        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4184    ) -> impl Fn(&E, &mut WindowContext) + 'static {
4185        let view = self.view().downgrade();
4186        move |e: &E, cx: &mut WindowContext| {
4187            view.update(cx, |view, cx| f(view, e, cx)).ok();
4188        }
4189    }
4190}
4191
4192impl<V> Context for ViewContext<'_, V> {
4193    type Result<U> = U;
4194
4195    fn new_model<T: 'static>(
4196        &mut self,
4197        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4198    ) -> Model<T> {
4199        self.window_cx.new_model(build_model)
4200    }
4201
4202    fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4203        self.window_cx.reserve_model()
4204    }
4205
4206    fn insert_model<T: 'static>(
4207        &mut self,
4208        reservation: crate::Reservation<T>,
4209        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4210    ) -> Self::Result<Model<T>> {
4211        self.window_cx.insert_model(reservation, build_model)
4212    }
4213
4214    fn update_model<T: 'static, R>(
4215        &mut self,
4216        model: &Model<T>,
4217        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4218    ) -> R {
4219        self.window_cx.update_model(model, update)
4220    }
4221
4222    fn read_model<T, R>(
4223        &self,
4224        handle: &Model<T>,
4225        read: impl FnOnce(&T, &AppContext) -> R,
4226    ) -> Self::Result<R>
4227    where
4228        T: 'static,
4229    {
4230        self.window_cx.read_model(handle, read)
4231    }
4232
4233    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4234    where
4235        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4236    {
4237        self.window_cx.update_window(window, update)
4238    }
4239
4240    fn read_window<T, R>(
4241        &self,
4242        window: &WindowHandle<T>,
4243        read: impl FnOnce(View<T>, &AppContext) -> R,
4244    ) -> Result<R>
4245    where
4246        T: 'static,
4247    {
4248        self.window_cx.read_window(window, read)
4249    }
4250}
4251
4252impl<V: 'static> VisualContext for ViewContext<'_, V> {
4253    fn new_view<W: Render + 'static>(
4254        &mut self,
4255        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4256    ) -> Self::Result<View<W>> {
4257        self.window_cx.new_view(build_view_state)
4258    }
4259
4260    fn update_view<V2: 'static, R>(
4261        &mut self,
4262        view: &View<V2>,
4263        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4264    ) -> Self::Result<R> {
4265        self.window_cx.update_view(view, update)
4266    }
4267
4268    fn replace_root_view<W>(
4269        &mut self,
4270        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4271    ) -> Self::Result<View<W>>
4272    where
4273        W: 'static + Render,
4274    {
4275        self.window_cx.replace_root_view(build_view)
4276    }
4277
4278    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4279        self.window_cx.focus_view(view)
4280    }
4281
4282    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4283        self.window_cx.dismiss_view(view)
4284    }
4285}
4286
4287impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4288    type Target = WindowContext<'a>;
4289
4290    fn deref(&self) -> &Self::Target {
4291        &self.window_cx
4292    }
4293}
4294
4295impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4296    fn deref_mut(&mut self) -> &mut Self::Target {
4297        &mut self.window_cx
4298    }
4299}
4300
4301// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4302slotmap::new_key_type! {
4303    /// A unique identifier for a window.
4304    pub struct WindowId;
4305}
4306
4307impl WindowId {
4308    /// Converts this window ID to a `u64`.
4309    pub fn as_u64(&self) -> u64 {
4310        self.0.as_ffi()
4311    }
4312}
4313
4314/// A handle to a window with a specific root view type.
4315/// Note that this does not keep the window alive on its own.
4316#[derive(Deref, DerefMut)]
4317pub struct WindowHandle<V> {
4318    #[deref]
4319    #[deref_mut]
4320    pub(crate) any_handle: AnyWindowHandle,
4321    state_type: PhantomData<V>,
4322}
4323
4324impl<V: 'static + Render> WindowHandle<V> {
4325    /// Creates a new handle from a window ID.
4326    /// This does not check if the root type of the window is `V`.
4327    pub fn new(id: WindowId) -> Self {
4328        WindowHandle {
4329            any_handle: AnyWindowHandle {
4330                id,
4331                state_type: TypeId::of::<V>(),
4332            },
4333            state_type: PhantomData,
4334        }
4335    }
4336
4337    /// Get the root view out of this window.
4338    ///
4339    /// This will fail if the window is closed or if the root view's type does not match `V`.
4340    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4341    where
4342        C: Context,
4343    {
4344        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4345            root_view
4346                .downcast::<V>()
4347                .map_err(|_| anyhow!("the type of the window's root view has changed"))
4348        }))
4349    }
4350
4351    /// Updates the root view of this window.
4352    ///
4353    /// This will fail if the window has been closed or if the root view's type does not match
4354    pub fn update<C, R>(
4355        &self,
4356        cx: &mut C,
4357        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4358    ) -> Result<R>
4359    where
4360        C: Context,
4361    {
4362        cx.update_window(self.any_handle, |root_view, cx| {
4363            let view = root_view
4364                .downcast::<V>()
4365                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4366            Ok(cx.update_view(&view, update))
4367        })?
4368    }
4369
4370    /// Read the root view out of this window.
4371    ///
4372    /// This will fail if the window is closed or if the root view's type does not match `V`.
4373    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4374        let x = cx
4375            .windows
4376            .get(self.id)
4377            .and_then(|window| {
4378                window
4379                    .as_ref()
4380                    .and_then(|window| window.root_view.clone())
4381                    .map(|root_view| root_view.downcast::<V>())
4382            })
4383            .ok_or_else(|| anyhow!("window not found"))?
4384            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4385
4386        Ok(x.read(cx))
4387    }
4388
4389    /// Read the root view out of this window, with a callback
4390    ///
4391    /// This will fail if the window is closed or if the root view's type does not match `V`.
4392    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4393    where
4394        C: Context,
4395    {
4396        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4397    }
4398
4399    /// Read the root view pointer off of this window.
4400    ///
4401    /// This will fail if the window is closed or if the root view's type does not match `V`.
4402    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4403    where
4404        C: Context,
4405    {
4406        cx.read_window(self, |root_view, _cx| root_view.clone())
4407    }
4408
4409    /// Check if this window is 'active'.
4410    ///
4411    /// Will return `None` if the window is closed or currently
4412    /// borrowed.
4413    pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4414        cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4415            .ok()
4416    }
4417}
4418
4419impl<V> Copy for WindowHandle<V> {}
4420
4421impl<V> Clone for WindowHandle<V> {
4422    fn clone(&self) -> Self {
4423        *self
4424    }
4425}
4426
4427impl<V> PartialEq for WindowHandle<V> {
4428    fn eq(&self, other: &Self) -> bool {
4429        self.any_handle == other.any_handle
4430    }
4431}
4432
4433impl<V> Eq for WindowHandle<V> {}
4434
4435impl<V> Hash for WindowHandle<V> {
4436    fn hash<H: Hasher>(&self, state: &mut H) {
4437        self.any_handle.hash(state);
4438    }
4439}
4440
4441impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4442    fn from(val: WindowHandle<V>) -> Self {
4443        val.any_handle
4444    }
4445}
4446
4447unsafe impl<V> Send for WindowHandle<V> {}
4448unsafe impl<V> Sync for WindowHandle<V> {}
4449
4450/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4451#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4452pub struct AnyWindowHandle {
4453    pub(crate) id: WindowId,
4454    state_type: TypeId,
4455}
4456
4457impl AnyWindowHandle {
4458    /// Get the ID of this window.
4459    pub fn window_id(&self) -> WindowId {
4460        self.id
4461    }
4462
4463    /// Attempt to convert this handle to a window handle with a specific root view type.
4464    /// If the types do not match, this will return `None`.
4465    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4466        if TypeId::of::<T>() == self.state_type {
4467            Some(WindowHandle {
4468                any_handle: *self,
4469                state_type: PhantomData,
4470            })
4471        } else {
4472            None
4473        }
4474    }
4475
4476    /// Updates the state of the root view of this window.
4477    ///
4478    /// This will fail if the window has been closed.
4479    pub fn update<C, R>(
4480        self,
4481        cx: &mut C,
4482        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4483    ) -> Result<R>
4484    where
4485        C: Context,
4486    {
4487        cx.update_window(self, update)
4488    }
4489
4490    /// Read the state of the root view of this window.
4491    ///
4492    /// This will fail if the window has been closed.
4493    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4494    where
4495        C: Context,
4496        T: 'static,
4497    {
4498        let view = self
4499            .downcast::<T>()
4500            .context("the type of the window's root view has changed")?;
4501
4502        cx.read_window(&view, read)
4503    }
4504}
4505
4506/// An identifier for an [`Element`](crate::Element).
4507///
4508/// Can be constructed with a string, a number, or both, as well
4509/// as other internal representations.
4510#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4511pub enum ElementId {
4512    /// The ID of a View element
4513    View(EntityId),
4514    /// An integer ID.
4515    Integer(usize),
4516    /// A string based ID.
4517    Name(SharedString),
4518    /// A UUID.
4519    Uuid(Uuid),
4520    /// An ID that's equated with a focus handle.
4521    FocusHandle(FocusId),
4522    /// A combination of a name and an integer.
4523    NamedInteger(SharedString, usize),
4524}
4525
4526impl Display for ElementId {
4527    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4528        match self {
4529            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4530            ElementId::Integer(ix) => write!(f, "{}", ix)?,
4531            ElementId::Name(name) => write!(f, "{}", name)?,
4532            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4533            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4534            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4535        }
4536
4537        Ok(())
4538    }
4539}
4540
4541impl TryInto<SharedString> for ElementId {
4542    type Error = anyhow::Error;
4543
4544    fn try_into(self) -> anyhow::Result<SharedString> {
4545        if let ElementId::Name(name) = self {
4546            Ok(name)
4547        } else {
4548            Err(anyhow!("element id is not string"))
4549        }
4550    }
4551}
4552
4553impl From<usize> for ElementId {
4554    fn from(id: usize) -> Self {
4555        ElementId::Integer(id)
4556    }
4557}
4558
4559impl From<i32> for ElementId {
4560    fn from(id: i32) -> Self {
4561        Self::Integer(id as usize)
4562    }
4563}
4564
4565impl From<SharedString> for ElementId {
4566    fn from(name: SharedString) -> Self {
4567        ElementId::Name(name)
4568    }
4569}
4570
4571impl From<&'static str> for ElementId {
4572    fn from(name: &'static str) -> Self {
4573        ElementId::Name(name.into())
4574    }
4575}
4576
4577impl<'a> From<&'a FocusHandle> for ElementId {
4578    fn from(handle: &'a FocusHandle) -> Self {
4579        ElementId::FocusHandle(handle.id)
4580    }
4581}
4582
4583impl From<(&'static str, EntityId)> for ElementId {
4584    fn from((name, id): (&'static str, EntityId)) -> Self {
4585        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4586    }
4587}
4588
4589impl From<(&'static str, usize)> for ElementId {
4590    fn from((name, id): (&'static str, usize)) -> Self {
4591        ElementId::NamedInteger(name.into(), id)
4592    }
4593}
4594
4595impl From<(&'static str, u64)> for ElementId {
4596    fn from((name, id): (&'static str, u64)) -> Self {
4597        ElementId::NamedInteger(name.into(), id as usize)
4598    }
4599}
4600
4601impl From<Uuid> for ElementId {
4602    fn from(value: Uuid) -> Self {
4603        Self::Uuid(value)
4604    }
4605}
4606
4607impl From<(&'static str, u32)> for ElementId {
4608    fn from((name, id): (&'static str, u32)) -> Self {
4609        ElementId::NamedInteger(name.into(), id as usize)
4610    }
4611}
4612
4613/// A rectangle to be rendered in the window at the given position and size.
4614/// Passed as an argument [`WindowContext::paint_quad`].
4615#[derive(Clone)]
4616pub struct PaintQuad {
4617    /// The bounds of the quad within the window.
4618    pub bounds: Bounds<Pixels>,
4619    /// The radii of the quad's corners.
4620    pub corner_radii: Corners<Pixels>,
4621    /// The background color of the quad.
4622    pub background: Hsla,
4623    /// The widths of the quad's borders.
4624    pub border_widths: Edges<Pixels>,
4625    /// The color of the quad's borders.
4626    pub border_color: Hsla,
4627}
4628
4629impl PaintQuad {
4630    /// Sets the corner radii of the quad.
4631    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4632        PaintQuad {
4633            corner_radii: corner_radii.into(),
4634            ..self
4635        }
4636    }
4637
4638    /// Sets the border widths of the quad.
4639    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4640        PaintQuad {
4641            border_widths: border_widths.into(),
4642            ..self
4643        }
4644    }
4645
4646    /// Sets the border color of the quad.
4647    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4648        PaintQuad {
4649            border_color: border_color.into(),
4650            ..self
4651        }
4652    }
4653
4654    /// Sets the background color of the quad.
4655    pub fn background(self, background: impl Into<Hsla>) -> Self {
4656        PaintQuad {
4657            background: background.into(),
4658            ..self
4659        }
4660    }
4661}
4662
4663/// Creates a quad with the given parameters.
4664pub fn quad(
4665    bounds: Bounds<Pixels>,
4666    corner_radii: impl Into<Corners<Pixels>>,
4667    background: impl Into<Hsla>,
4668    border_widths: impl Into<Edges<Pixels>>,
4669    border_color: impl Into<Hsla>,
4670) -> PaintQuad {
4671    PaintQuad {
4672        bounds,
4673        corner_radii: corner_radii.into(),
4674        background: background.into(),
4675        border_widths: border_widths.into(),
4676        border_color: border_color.into(),
4677    }
4678}
4679
4680/// Creates a filled quad with the given bounds and background color.
4681pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4682    PaintQuad {
4683        bounds: bounds.into(),
4684        corner_radii: (0.).into(),
4685        background: background.into(),
4686        border_widths: (0.).into(),
4687        border_color: transparent_black(),
4688    }
4689}
4690
4691/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4692pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4693    PaintQuad {
4694        bounds: bounds.into(),
4695        corner_radii: (0.).into(),
4696        background: transparent_black(),
4697        border_widths: (1.).into(),
4698        border_color: border_color.into(),
4699    }
4700}