window.rs

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