window.rs

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