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