window.rs

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