window.rs

   1use crate::{
   2    arena::{Arena, ArenaRef},
   3    key_dispatch::DispatchActionListener,
   4    px, size, transparent_black, Action, AnyDrag, AnyView, AppContext, AsyncWindowContext,
   5    AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle, DevicePixels, DispatchNodeId,
   6    DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten,
   7    FontId, GlobalElementId, GlyphId, Hsla, ImageData, InputEvent, IsZero, KeyBinding, KeyContext,
   8    KeyDownEvent, KeystrokeEvent, LayoutId, Model, ModelContext, Modifiers, MonochromeSprite,
   9    MouseButton, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay,
  10    PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render,
  11    RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, Scene, SceneBuilder,
  12    Shadow, SharedString, Size, Style, SubscriberSet, Subscription, Surface, TaffyLayoutEngine,
  13    Task, Underline, UnderlineStyle, View, VisualContext, WeakView, WindowBounds, WindowOptions,
  14    SUBPIXEL_VARIANTS,
  15};
  16use anyhow::{anyhow, Context as _, Result};
  17use collections::FxHashMap;
  18use derive_more::{Deref, DerefMut};
  19use futures::{
  20    channel::{mpsc, oneshot},
  21    StreamExt,
  22};
  23use media::core_video::CVImageBuffer;
  24use parking_lot::RwLock;
  25use slotmap::SlotMap;
  26use smallvec::SmallVec;
  27use std::{
  28    any::{Any, TypeId},
  29    borrow::{Borrow, BorrowMut, Cow},
  30    cell::RefCell,
  31    fmt::Debug,
  32    future::Future,
  33    hash::{Hash, Hasher},
  34    marker::PhantomData,
  35    mem,
  36    rc::Rc,
  37    sync::{
  38        atomic::{AtomicUsize, Ordering::SeqCst},
  39        Arc,
  40    },
  41};
  42use util::ResultExt;
  43
  44const ACTIVE_DRAG_Z_INDEX: u8 = 1;
  45
  46/// A global stacking order, which is created by stacking successive z-index values.
  47/// Each z-index will always be interpreted in the context of its parent z-index.
  48#[derive(Deref, DerefMut, Clone, Debug, Ord, PartialOrd, PartialEq, Eq)]
  49pub struct StackingOrder {
  50    #[deref]
  51    #[deref_mut]
  52    z_indices: SmallVec<[u8; 64]>,
  53}
  54
  55impl Default for StackingOrder {
  56    fn default() -> Self {
  57        StackingOrder {
  58            z_indices: SmallVec::new(),
  59        }
  60    }
  61}
  62
  63/// Represents the two different phases when dispatching events.
  64#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  65pub enum DispatchPhase {
  66    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  67    /// invoked front to back and keyboard event listeners are invoked from the focused element
  68    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  69    /// registering event listeners.
  70    #[default]
  71    Bubble,
  72    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  73    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  74    /// is used for special purposes such as clearing the "pressed" state for click events. If
  75    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  76    /// outside of the immediate region may rely on detecting non-local events during this phase.
  77    Capture,
  78}
  79
  80impl DispatchPhase {
  81    pub fn bubble(self) -> bool {
  82        self == DispatchPhase::Bubble
  83    }
  84
  85    pub fn capture(self) -> bool {
  86        self == DispatchPhase::Capture
  87    }
  88}
  89
  90type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  91type AnyMouseListener = ArenaRef<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
  92type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
  93
  94struct FocusEvent {
  95    previous_focus_path: SmallVec<[FocusId; 8]>,
  96    current_focus_path: SmallVec<[FocusId; 8]>,
  97}
  98
  99slotmap::new_key_type! { pub struct FocusId; }
 100
 101thread_local! {
 102    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(4 * 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    /// Moves the focus to the element associated with this handle.
 173    pub fn focus(&self, cx: &mut WindowContext) {
 174        cx.focus(self)
 175    }
 176
 177    /// Obtains whether the element associated with this handle is currently focused.
 178    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 179        self.id.is_focused(cx)
 180    }
 181
 182    /// Obtains whether the element associated with this handle contains the focused
 183    /// element or is itself focused.
 184    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 185        self.id.contains_focused(cx)
 186    }
 187
 188    /// Obtains whether the element associated with this handle is contained within the
 189    /// focused element or is itself focused.
 190    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 191        self.id.within_focused(cx)
 192    }
 193
 194    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 195    pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 196        self.id.contains(other.id, cx)
 197    }
 198}
 199
 200impl Clone for FocusHandle {
 201    fn clone(&self) -> Self {
 202        Self::for_id(self.id, &self.handles).unwrap()
 203    }
 204}
 205
 206impl PartialEq for FocusHandle {
 207    fn eq(&self, other: &Self) -> bool {
 208        self.id == other.id
 209    }
 210}
 211
 212impl Eq for FocusHandle {}
 213
 214impl Drop for FocusHandle {
 215    fn drop(&mut self) {
 216        self.handles
 217            .read()
 218            .get(self.id)
 219            .unwrap()
 220            .fetch_sub(1, SeqCst);
 221    }
 222}
 223
 224/// FocusableView allows users of your view to easily
 225/// focus it (using cx.focus_view(view))
 226pub trait FocusableView: 'static + Render {
 227    fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
 228}
 229
 230/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
 231/// where the lifecycle of the view is handled by another view.
 232pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
 233
 234impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
 235
 236pub struct DismissEvent;
 237
 238// Holds the state for a specific window.
 239pub struct Window {
 240    pub(crate) handle: AnyWindowHandle,
 241    pub(crate) removed: bool,
 242    pub(crate) platform_window: Box<dyn PlatformWindow>,
 243    display_id: DisplayId,
 244    sprite_atlas: Arc<dyn PlatformAtlas>,
 245    rem_size: Pixels,
 246    viewport_size: Size<Pixels>,
 247    layout_engine: Option<TaffyLayoutEngine>,
 248    pub(crate) root_view: Option<AnyView>,
 249    pub(crate) element_id_stack: GlobalElementId,
 250    pub(crate) rendered_frame: Frame,
 251    pub(crate) next_frame: Frame,
 252    frame_arena: Arena,
 253    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 254    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 255    blur_listeners: SubscriberSet<(), AnyObserver>,
 256    default_prevented: bool,
 257    mouse_position: Point<Pixels>,
 258    modifiers: Modifiers,
 259    requested_cursor_style: Option<CursorStyle>,
 260    scale_factor: f32,
 261    bounds: WindowBounds,
 262    bounds_observers: SubscriberSet<(), AnyObserver>,
 263    active: bool,
 264    pub(crate) dirty: bool,
 265    pub(crate) drawing: bool,
 266    activation_observers: SubscriberSet<(), AnyObserver>,
 267    pub(crate) focus: Option<FocusId>,
 268
 269    #[cfg(any(test, feature = "test-support"))]
 270    pub(crate) focus_invalidated: bool,
 271}
 272
 273pub(crate) struct ElementStateBox {
 274    inner: Box<dyn Any>,
 275    #[cfg(debug_assertions)]
 276    type_name: &'static str,
 277}
 278
 279pub(crate) struct Frame {
 280    focus: Option<FocusId>,
 281    pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
 282    mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, AnyMouseListener)>>,
 283    pub(crate) dispatch_tree: DispatchTree,
 284    pub(crate) scene_builder: SceneBuilder,
 285    pub(crate) depth_map: Vec<(StackingOrder, Bounds<Pixels>)>,
 286    pub(crate) z_index_stack: StackingOrder,
 287    content_mask_stack: Vec<ContentMask<Pixels>>,
 288    element_offset_stack: Vec<Point<Pixels>>,
 289}
 290
 291impl Frame {
 292    fn new(dispatch_tree: DispatchTree) -> Self {
 293        Frame {
 294            focus: None,
 295            element_states: FxHashMap::default(),
 296            mouse_listeners: FxHashMap::default(),
 297            dispatch_tree,
 298            scene_builder: SceneBuilder::default(),
 299            z_index_stack: StackingOrder::default(),
 300            depth_map: Default::default(),
 301            content_mask_stack: Vec::new(),
 302            element_offset_stack: Vec::new(),
 303        }
 304    }
 305
 306    fn clear(&mut self) {
 307        self.element_states.clear();
 308        self.mouse_listeners.values_mut().for_each(Vec::clear);
 309        self.dispatch_tree.clear();
 310        self.depth_map.clear();
 311    }
 312
 313    fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 314        self.focus
 315            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 316            .unwrap_or_default()
 317    }
 318}
 319
 320impl Window {
 321    pub(crate) fn new(
 322        handle: AnyWindowHandle,
 323        options: WindowOptions,
 324        cx: &mut AppContext,
 325    ) -> Self {
 326        let platform_window = cx.platform.open_window(
 327            handle,
 328            options,
 329            Box::new({
 330                let mut cx = cx.to_async();
 331                move || handle.update(&mut cx, |_, cx| cx.draw())
 332            }),
 333        );
 334        let display_id = platform_window.display().id();
 335        let sprite_atlas = platform_window.sprite_atlas();
 336        let mouse_position = platform_window.mouse_position();
 337        let modifiers = platform_window.modifiers();
 338        let content_size = platform_window.content_size();
 339        let scale_factor = platform_window.scale_factor();
 340        let bounds = platform_window.bounds();
 341
 342        platform_window.on_resize(Box::new({
 343            let mut cx = cx.to_async();
 344            move |_, _| {
 345                handle
 346                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 347                    .log_err();
 348            }
 349        }));
 350        platform_window.on_moved(Box::new({
 351            let mut cx = cx.to_async();
 352            move || {
 353                handle
 354                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 355                    .log_err();
 356            }
 357        }));
 358        platform_window.on_active_status_change(Box::new({
 359            let mut cx = cx.to_async();
 360            move |active| {
 361                handle
 362                    .update(&mut cx, |_, cx| {
 363                        cx.window.active = active;
 364                        cx.window
 365                            .activation_observers
 366                            .clone()
 367                            .retain(&(), |callback| callback(cx));
 368                    })
 369                    .log_err();
 370            }
 371        }));
 372
 373        platform_window.on_input({
 374            let mut cx = cx.to_async();
 375            Box::new(move |event| {
 376                handle
 377                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 378                    .log_err()
 379                    .unwrap_or(false)
 380            })
 381        });
 382
 383        Window {
 384            handle,
 385            removed: false,
 386            platform_window,
 387            display_id,
 388            sprite_atlas,
 389            rem_size: px(16.),
 390            viewport_size: content_size,
 391            layout_engine: Some(TaffyLayoutEngine::new()),
 392            root_view: None,
 393            element_id_stack: GlobalElementId::default(),
 394            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 395            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
 396            frame_arena: Arena::new(1 * 1024 * 1024),
 397            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 398            focus_listeners: SubscriberSet::new(),
 399            blur_listeners: SubscriberSet::new(),
 400            default_prevented: true,
 401            mouse_position,
 402            modifiers,
 403            requested_cursor_style: None,
 404            scale_factor,
 405            bounds,
 406            bounds_observers: SubscriberSet::new(),
 407            active: false,
 408            dirty: false,
 409            drawing: false,
 410            activation_observers: SubscriberSet::new(),
 411            focus: None,
 412
 413            #[cfg(any(test, feature = "test-support"))]
 414            focus_invalidated: false,
 415        }
 416    }
 417}
 418
 419/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 420/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 421/// to leave room to support more complex shapes in the future.
 422#[derive(Clone, Debug, Default, PartialEq, Eq)]
 423#[repr(C)]
 424pub struct ContentMask<P: Clone + Default + Debug> {
 425    pub bounds: Bounds<P>,
 426}
 427
 428impl ContentMask<Pixels> {
 429    /// Scale the content mask's pixel units by the given scaling factor.
 430    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 431        ContentMask {
 432            bounds: self.bounds.scale(factor),
 433        }
 434    }
 435
 436    /// Intersect the content mask with the given content mask.
 437    pub fn intersect(&self, other: &Self) -> Self {
 438        let bounds = self.bounds.intersect(&other.bounds);
 439        ContentMask { bounds }
 440    }
 441}
 442
 443/// Provides access to application state in the context of a single window. Derefs
 444/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
 445/// an `AppContext` and call any `AppContext` methods.
 446pub struct WindowContext<'a> {
 447    pub(crate) app: &'a mut AppContext,
 448    pub(crate) window: &'a mut Window,
 449}
 450
 451impl<'a> WindowContext<'a> {
 452    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 453        Self { app, window }
 454    }
 455
 456    /// Obtain a handle to the window that belongs to this context.
 457    pub fn window_handle(&self) -> AnyWindowHandle {
 458        self.window.handle
 459    }
 460
 461    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 462    pub fn notify(&mut self) {
 463        if !self.window.drawing {
 464            self.window.dirty = true;
 465        }
 466    }
 467
 468    /// Close this window.
 469    pub fn remove_window(&mut self) {
 470        self.window.removed = true;
 471    }
 472
 473    /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
 474    /// for elements rendered within this window.
 475    pub fn focus_handle(&mut self) -> FocusHandle {
 476        FocusHandle::new(&self.window.focus_handles)
 477    }
 478
 479    /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
 480    pub fn focused(&self) -> Option<FocusHandle> {
 481        self.window
 482            .focus
 483            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 484    }
 485
 486    /// Move focus to the element associated with the given `FocusHandle`.
 487    pub fn focus(&mut self, handle: &FocusHandle) {
 488        if self.window.focus == Some(handle.id) {
 489            return;
 490        }
 491
 492        self.window.focus = Some(handle.id);
 493        self.window
 494            .rendered_frame
 495            .dispatch_tree
 496            .clear_pending_keystrokes();
 497
 498        #[cfg(any(test, feature = "test-support"))]
 499        {
 500            self.window.focus_invalidated = true;
 501        }
 502
 503        self.notify();
 504    }
 505
 506    /// Remove focus from all elements within this context's window.
 507    pub fn blur(&mut self) {
 508        self.window.focus = None;
 509        self.notify();
 510    }
 511
 512    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 513        let focus_handle = self.focused();
 514
 515        self.defer(move |cx| {
 516            let node_id = focus_handle
 517                .and_then(|handle| {
 518                    cx.window
 519                        .rendered_frame
 520                        .dispatch_tree
 521                        .focusable_node_id(handle.id)
 522                })
 523                .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
 524
 525            cx.propagate_event = true;
 526            cx.dispatch_action_on_node(node_id, action);
 527        })
 528    }
 529
 530    pub(crate) fn dispatch_keystroke_observers(
 531        &mut self,
 532        event: &dyn Any,
 533        action: Option<Box<dyn Action>>,
 534    ) {
 535        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
 536            return;
 537        };
 538
 539        self.keystroke_observers
 540            .clone()
 541            .retain(&(), move |callback| {
 542                (callback)(
 543                    &KeystrokeEvent {
 544                        keystroke: key_down_event.keystroke.clone(),
 545                        action: action.as_ref().map(|action| action.boxed_clone()),
 546                    },
 547                    self,
 548                );
 549                true
 550            });
 551    }
 552
 553    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 554    /// that are currently on the stack to be returned to the app.
 555    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 556        let handle = self.window.handle;
 557        self.app.defer(move |cx| {
 558            handle.update(cx, |_, cx| f(cx)).ok();
 559        });
 560    }
 561
 562    pub fn subscribe<Emitter, E, Evt>(
 563        &mut self,
 564        entity: &E,
 565        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
 566    ) -> Subscription
 567    where
 568        Emitter: EventEmitter<Evt>,
 569        E: Entity<Emitter>,
 570        Evt: 'static,
 571    {
 572        let entity_id = entity.entity_id();
 573        let entity = entity.downgrade();
 574        let window_handle = self.window.handle;
 575        let (subscription, activate) = self.app.event_listeners.insert(
 576            entity_id,
 577            (
 578                TypeId::of::<Evt>(),
 579                Box::new(move |event, cx| {
 580                    window_handle
 581                        .update(cx, |_, cx| {
 582                            if let Some(handle) = E::upgrade_from(&entity) {
 583                                let event = event.downcast_ref().expect("invalid event type");
 584                                on_event(handle, event, cx);
 585                                true
 586                            } else {
 587                                false
 588                            }
 589                        })
 590                        .unwrap_or(false)
 591                }),
 592            ),
 593        );
 594        self.app.defer(move |_| activate());
 595        subscription
 596    }
 597
 598    /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
 599    /// await points in async code.
 600    pub fn to_async(&self) -> AsyncWindowContext {
 601        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 602    }
 603
 604    /// Schedule the given closure to be run directly after the current frame is rendered.
 605    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
 606        let handle = self.window.handle;
 607        let display_id = self.window.display_id;
 608
 609        if !self.frame_consumers.contains_key(&display_id) {
 610            let (tx, mut rx) = mpsc::unbounded::<()>();
 611            self.platform.set_display_link_output_callback(
 612                display_id,
 613                Box::new(move |_current_time, _output_time| _ = tx.unbounded_send(())),
 614            );
 615
 616            let consumer_task = self.app.spawn(|cx| async move {
 617                while rx.next().await.is_some() {
 618                    cx.update(|cx| {
 619                        for callback in cx
 620                            .next_frame_callbacks
 621                            .get_mut(&display_id)
 622                            .unwrap()
 623                            .drain(..)
 624                            .collect::<SmallVec<[_; 32]>>()
 625                        {
 626                            callback(cx);
 627                        }
 628                    })
 629                    .ok();
 630
 631                    // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
 632
 633                    cx.update(|cx| {
 634                        if cx.next_frame_callbacks.is_empty() {
 635                            cx.platform.stop_display_link(display_id);
 636                        }
 637                    })
 638                    .ok();
 639                }
 640            });
 641            self.frame_consumers.insert(display_id, consumer_task);
 642        }
 643
 644        if self.next_frame_callbacks.is_empty() {
 645            self.platform.start_display_link(display_id);
 646        }
 647
 648        self.next_frame_callbacks
 649            .entry(display_id)
 650            .or_default()
 651            .push(Box::new(move |cx: &mut AppContext| {
 652                cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
 653            }));
 654    }
 655
 656    /// Spawn the future returned by the given closure on the application thread pool.
 657    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 658    /// use within your future.
 659    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 660    where
 661        R: 'static,
 662        Fut: Future<Output = R> + 'static,
 663    {
 664        self.app
 665            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 666    }
 667
 668    /// Update the global of the given type. The given closure is given simultaneous mutable
 669    /// access both to the global and the context.
 670    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 671    where
 672        G: 'static,
 673    {
 674        let mut global = self.app.lease_global::<G>();
 675        let result = f(&mut global, self);
 676        self.app.end_global_lease(global);
 677        result
 678    }
 679
 680    #[must_use]
 681    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 682    /// layout is being requested, along with the layout ids of any children. This method is called during
 683    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 684    pub fn request_layout(
 685        &mut self,
 686        style: &Style,
 687        children: impl IntoIterator<Item = LayoutId>,
 688    ) -> LayoutId {
 689        self.app.layout_id_buffer.clear();
 690        self.app.layout_id_buffer.extend(children.into_iter());
 691        let rem_size = self.rem_size();
 692
 693        self.window.layout_engine.as_mut().unwrap().request_layout(
 694            style,
 695            rem_size,
 696            &self.app.layout_id_buffer,
 697        )
 698    }
 699
 700    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 701    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 702    /// determine the element's size. One place this is used internally is when measuring text.
 703    ///
 704    /// The given closure is invoked at layout time with the known dimensions and available space and
 705    /// returns a `Size`.
 706    pub fn request_measured_layout<
 707        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
 708            + 'static,
 709    >(
 710        &mut self,
 711        style: Style,
 712        measure: F,
 713    ) -> LayoutId {
 714        let rem_size = self.rem_size();
 715        self.window
 716            .layout_engine
 717            .as_mut()
 718            .unwrap()
 719            .request_measured_layout(style, rem_size, measure)
 720    }
 721
 722    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
 723        let mut layout_engine = self.window.layout_engine.take().unwrap();
 724        layout_engine.compute_layout(layout_id, available_space, self);
 725        self.window.layout_engine = Some(layout_engine);
 726    }
 727
 728    /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
 729    /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
 730    /// in order to pass your element its `Bounds` automatically.
 731    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
 732        let mut bounds = self
 733            .window
 734            .layout_engine
 735            .as_mut()
 736            .unwrap()
 737            .layout_bounds(layout_id)
 738            .map(Into::into);
 739        bounds.origin += self.element_offset();
 740        bounds
 741    }
 742
 743    fn window_bounds_changed(&mut self) {
 744        self.window.scale_factor = self.window.platform_window.scale_factor();
 745        self.window.viewport_size = self.window.platform_window.content_size();
 746        self.window.bounds = self.window.platform_window.bounds();
 747        self.window.display_id = self.window.platform_window.display().id();
 748        self.notify();
 749
 750        self.window
 751            .bounds_observers
 752            .clone()
 753            .retain(&(), |callback| callback(self));
 754    }
 755
 756    pub fn window_bounds(&self) -> WindowBounds {
 757        self.window.bounds
 758    }
 759
 760    pub fn viewport_size(&self) -> Size<Pixels> {
 761        self.window.viewport_size
 762    }
 763
 764    pub fn is_window_active(&self) -> bool {
 765        self.window.active
 766    }
 767
 768    pub fn zoom_window(&self) {
 769        self.window.platform_window.zoom();
 770    }
 771
 772    pub fn set_window_title(&mut self, title: &str) {
 773        self.window.platform_window.set_title(title);
 774    }
 775
 776    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 777        self.platform
 778            .displays()
 779            .into_iter()
 780            .find(|display| display.id() == self.window.display_id)
 781    }
 782
 783    pub fn show_character_palette(&self) {
 784        self.window.platform_window.show_character_palette();
 785    }
 786
 787    /// The scale factor of the display associated with the window. For example, it could
 788    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 789    /// be rendered as two pixels on screen.
 790    pub fn scale_factor(&self) -> f32 {
 791        self.window.scale_factor
 792    }
 793
 794    /// The size of an em for the base font of the application. Adjusting this value allows the
 795    /// UI to scale, just like zooming a web page.
 796    pub fn rem_size(&self) -> Pixels {
 797        self.window.rem_size
 798    }
 799
 800    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 801    /// UI to scale, just like zooming a web page.
 802    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 803        self.window.rem_size = rem_size.into();
 804    }
 805
 806    /// The line height associated with the current text style.
 807    pub fn line_height(&self) -> Pixels {
 808        let rem_size = self.rem_size();
 809        let text_style = self.text_style();
 810        text_style
 811            .line_height
 812            .to_pixels(text_style.font_size.into(), rem_size)
 813    }
 814
 815    /// Call to prevent the default action of an event. Currently only used to prevent
 816    /// parent elements from becoming focused on mouse down.
 817    pub fn prevent_default(&mut self) {
 818        self.window.default_prevented = true;
 819    }
 820
 821    /// Obtain whether default has been prevented for the event currently being dispatched.
 822    pub fn default_prevented(&self) -> bool {
 823        self.window.default_prevented
 824    }
 825
 826    /// Register a mouse event listener on the window for the next frame. The type of event
 827    /// is determined by the first parameter of the given listener. When the next frame is rendered
 828    /// the listener will be cleared.
 829    pub fn on_mouse_event<Event: 'static>(
 830        &mut self,
 831        mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
 832    ) {
 833        let order = self.window.next_frame.z_index_stack.clone();
 834        let handler = self
 835            .window
 836            .frame_arena
 837            .alloc(|| {
 838                move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
 839                    handler(event.downcast_ref().unwrap(), phase, cx)
 840                }
 841            })
 842            .map(|handler| handler as _);
 843        self.window
 844            .next_frame
 845            .mouse_listeners
 846            .entry(TypeId::of::<Event>())
 847            .or_default()
 848            .push((order, handler))
 849    }
 850
 851    /// Register a key event listener on the window for the next frame. The type of event
 852    /// is determined by the first parameter of the given listener. When the next frame is rendered
 853    /// the listener will be cleared.
 854    ///
 855    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 856    /// a specific need to register a global listener.
 857    pub fn on_key_event<Event: 'static>(
 858        &mut self,
 859        listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 860    ) {
 861        let listener = self
 862            .window
 863            .frame_arena
 864            .alloc(|| {
 865                move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
 866                    if let Some(event) = event.downcast_ref::<Event>() {
 867                        listener(event, phase, cx)
 868                    }
 869                }
 870            })
 871            .map(|handler| handler as _);
 872        self.window.next_frame.dispatch_tree.on_key_event(listener);
 873    }
 874
 875    /// Register an action listener on the window for the next frame. The type of action
 876    /// is determined by the first parameter of the given listener. When the next frame is rendered
 877    /// the listener will be cleared.
 878    ///
 879    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
 880    /// a specific need to register a global listener.
 881    pub fn on_action(
 882        &mut self,
 883        action_type: TypeId,
 884        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
 885    ) {
 886        let listener = self
 887            .window
 888            .frame_arena
 889            .alloc(|| listener)
 890            .map(|handler| handler as _);
 891        self.window
 892            .next_frame
 893            .dispatch_tree
 894            .on_action(action_type, listener);
 895    }
 896
 897    pub fn is_action_available(&self, action: &dyn Action) -> bool {
 898        let target = self
 899            .focused()
 900            .and_then(|focused_handle| {
 901                self.window
 902                    .rendered_frame
 903                    .dispatch_tree
 904                    .focusable_node_id(focused_handle.id)
 905            })
 906            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
 907        self.window
 908            .rendered_frame
 909            .dispatch_tree
 910            .is_action_available(action, target)
 911    }
 912
 913    /// The position of the mouse relative to the window.
 914    pub fn mouse_position(&self) -> Point<Pixels> {
 915        self.window.mouse_position
 916    }
 917
 918    /// The current state of the keyboard's modifiers
 919    pub fn modifiers(&self) -> Modifiers {
 920        self.window.modifiers
 921    }
 922
 923    pub fn set_cursor_style(&mut self, style: CursorStyle) {
 924        self.window.requested_cursor_style = Some(style)
 925    }
 926
 927    /// Called during painting to invoke the given closure in a new stacking context. The given
 928    /// z-index is interpreted relative to the previous call to `stack`.
 929    pub fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
 930        self.window.next_frame.z_index_stack.push(z_index);
 931        let result = f(self);
 932        self.window.next_frame.z_index_stack.pop();
 933        result
 934    }
 935
 936    /// Called during painting to track which z-index is on top at each pixel position
 937    pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
 938        let stacking_order = self.window.next_frame.z_index_stack.clone();
 939        let depth_map = &mut self.window.next_frame.depth_map;
 940        match depth_map.binary_search_by(|(level, _)| stacking_order.cmp(&level)) {
 941            Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, bounds)),
 942        }
 943    }
 944
 945    /// Returns true if the top-most opaque layer painted over this point was part of the
 946    /// same layer as the given stacking order.
 947    pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
 948        for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
 949            if bounds.contains(point) {
 950                return level.starts_with(stack) || stack.starts_with(level);
 951            }
 952        }
 953
 954        false
 955    }
 956
 957    pub fn was_top_layer_under_active_drag(
 958        &self,
 959        point: &Point<Pixels>,
 960        level: &StackingOrder,
 961    ) -> bool {
 962        for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
 963            if stack.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
 964                continue;
 965            }
 966            if bounds.contains(point) {
 967                return level.starts_with(stack) || stack.starts_with(level);
 968            }
 969        }
 970
 971        false
 972    }
 973
 974    /// Called during painting to get the current stacking order.
 975    pub fn stacking_order(&self) -> &StackingOrder {
 976        &self.window.next_frame.z_index_stack
 977    }
 978
 979    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
 980    pub fn paint_shadows(
 981        &mut self,
 982        bounds: Bounds<Pixels>,
 983        corner_radii: Corners<Pixels>,
 984        shadows: &[BoxShadow],
 985    ) {
 986        let scale_factor = self.scale_factor();
 987        let content_mask = self.content_mask();
 988        let window = &mut *self.window;
 989        for shadow in shadows {
 990            let mut shadow_bounds = bounds;
 991            shadow_bounds.origin += shadow.offset;
 992            shadow_bounds.dilate(shadow.spread_radius);
 993            window.next_frame.scene_builder.insert(
 994                &window.next_frame.z_index_stack,
 995                Shadow {
 996                    order: 0,
 997                    bounds: shadow_bounds.scale(scale_factor),
 998                    content_mask: content_mask.scale(scale_factor),
 999                    corner_radii: corner_radii.scale(scale_factor),
1000                    color: shadow.color,
1001                    blur_radius: shadow.blur_radius.scale(scale_factor),
1002                },
1003            );
1004        }
1005    }
1006
1007    /// Paint one or more quads into the scene for the next frame at the current stacking context.
1008    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
1009    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
1010    pub fn paint_quad(&mut self, quad: PaintQuad) {
1011        let scale_factor = self.scale_factor();
1012        let content_mask = self.content_mask();
1013
1014        let window = &mut *self.window;
1015        window.next_frame.scene_builder.insert(
1016            &window.next_frame.z_index_stack,
1017            Quad {
1018                order: 0,
1019                bounds: quad.bounds.scale(scale_factor),
1020                content_mask: content_mask.scale(scale_factor),
1021                background: quad.background,
1022                border_color: quad.border_color,
1023                corner_radii: quad.corner_radii.scale(scale_factor),
1024                border_widths: quad.border_widths.scale(scale_factor),
1025            },
1026        );
1027    }
1028
1029    /// Paint the given `Path` into the scene for the next frame at the current z-index.
1030    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
1031        let scale_factor = self.scale_factor();
1032        let content_mask = self.content_mask();
1033        path.content_mask = content_mask;
1034        path.color = color.into();
1035        let window = &mut *self.window;
1036        window
1037            .next_frame
1038            .scene_builder
1039            .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1040    }
1041
1042    /// Paint an underline into the scene for the next frame at the current z-index.
1043    pub fn paint_underline(
1044        &mut self,
1045        origin: Point<Pixels>,
1046        width: Pixels,
1047        style: &UnderlineStyle,
1048    ) {
1049        let scale_factor = self.scale_factor();
1050        let height = if style.wavy {
1051            style.thickness * 3.
1052        } else {
1053            style.thickness
1054        };
1055        let bounds = Bounds {
1056            origin,
1057            size: size(width, height),
1058        };
1059        let content_mask = self.content_mask();
1060        let window = &mut *self.window;
1061        window.next_frame.scene_builder.insert(
1062            &window.next_frame.z_index_stack,
1063            Underline {
1064                order: 0,
1065                bounds: bounds.scale(scale_factor),
1066                content_mask: content_mask.scale(scale_factor),
1067                thickness: style.thickness.scale(scale_factor),
1068                color: style.color.unwrap_or_default(),
1069                wavy: style.wavy,
1070            },
1071        );
1072    }
1073
1074    /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1075    /// The y component of the origin is the baseline of the glyph.
1076    pub fn paint_glyph(
1077        &mut self,
1078        origin: Point<Pixels>,
1079        font_id: FontId,
1080        glyph_id: GlyphId,
1081        font_size: Pixels,
1082        color: Hsla,
1083    ) -> Result<()> {
1084        let scale_factor = self.scale_factor();
1085        let glyph_origin = origin.scale(scale_factor);
1086        let subpixel_variant = Point {
1087            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1088            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1089        };
1090        let params = RenderGlyphParams {
1091            font_id,
1092            glyph_id,
1093            font_size,
1094            subpixel_variant,
1095            scale_factor,
1096            is_emoji: false,
1097        };
1098
1099        let raster_bounds = self.text_system().raster_bounds(&params)?;
1100        if !raster_bounds.is_zero() {
1101            let tile =
1102                self.window
1103                    .sprite_atlas
1104                    .get_or_insert_with(&params.clone().into(), &mut || {
1105                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1106                        Ok((size, Cow::Owned(bytes)))
1107                    })?;
1108            let bounds = Bounds {
1109                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1110                size: tile.bounds.size.map(Into::into),
1111            };
1112            let content_mask = self.content_mask().scale(scale_factor);
1113            let window = &mut *self.window;
1114            window.next_frame.scene_builder.insert(
1115                &window.next_frame.z_index_stack,
1116                MonochromeSprite {
1117                    order: 0,
1118                    bounds,
1119                    content_mask,
1120                    color,
1121                    tile,
1122                },
1123            );
1124        }
1125        Ok(())
1126    }
1127
1128    /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1129    /// The y component of the origin is the baseline of the glyph.
1130    pub fn paint_emoji(
1131        &mut self,
1132        origin: Point<Pixels>,
1133        font_id: FontId,
1134        glyph_id: GlyphId,
1135        font_size: Pixels,
1136    ) -> Result<()> {
1137        let scale_factor = self.scale_factor();
1138        let glyph_origin = origin.scale(scale_factor);
1139        let params = RenderGlyphParams {
1140            font_id,
1141            glyph_id,
1142            font_size,
1143            // We don't render emojis with subpixel variants.
1144            subpixel_variant: Default::default(),
1145            scale_factor,
1146            is_emoji: true,
1147        };
1148
1149        let raster_bounds = self.text_system().raster_bounds(&params)?;
1150        if !raster_bounds.is_zero() {
1151            let tile =
1152                self.window
1153                    .sprite_atlas
1154                    .get_or_insert_with(&params.clone().into(), &mut || {
1155                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1156                        Ok((size, Cow::Owned(bytes)))
1157                    })?;
1158            let bounds = Bounds {
1159                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1160                size: tile.bounds.size.map(Into::into),
1161            };
1162            let content_mask = self.content_mask().scale(scale_factor);
1163            let window = &mut *self.window;
1164
1165            window.next_frame.scene_builder.insert(
1166                &window.next_frame.z_index_stack,
1167                PolychromeSprite {
1168                    order: 0,
1169                    bounds,
1170                    corner_radii: Default::default(),
1171                    content_mask,
1172                    tile,
1173                    grayscale: false,
1174                },
1175            );
1176        }
1177        Ok(())
1178    }
1179
1180    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1181    pub fn paint_svg(
1182        &mut self,
1183        bounds: Bounds<Pixels>,
1184        path: SharedString,
1185        color: Hsla,
1186    ) -> Result<()> {
1187        let scale_factor = self.scale_factor();
1188        let bounds = bounds.scale(scale_factor);
1189        // Render the SVG at twice the size to get a higher quality result.
1190        let params = RenderSvgParams {
1191            path,
1192            size: bounds
1193                .size
1194                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1195        };
1196
1197        let tile =
1198            self.window
1199                .sprite_atlas
1200                .get_or_insert_with(&params.clone().into(), &mut || {
1201                    let bytes = self.svg_renderer.render(&params)?;
1202                    Ok((params.size, Cow::Owned(bytes)))
1203                })?;
1204        let content_mask = self.content_mask().scale(scale_factor);
1205
1206        let window = &mut *self.window;
1207        window.next_frame.scene_builder.insert(
1208            &window.next_frame.z_index_stack,
1209            MonochromeSprite {
1210                order: 0,
1211                bounds,
1212                content_mask,
1213                color,
1214                tile,
1215            },
1216        );
1217
1218        Ok(())
1219    }
1220
1221    /// Paint an image into the scene for the next frame at the current z-index.
1222    pub fn paint_image(
1223        &mut self,
1224        bounds: Bounds<Pixels>,
1225        corner_radii: Corners<Pixels>,
1226        data: Arc<ImageData>,
1227        grayscale: bool,
1228    ) -> Result<()> {
1229        let scale_factor = self.scale_factor();
1230        let bounds = bounds.scale(scale_factor);
1231        let params = RenderImageParams { image_id: data.id };
1232
1233        let tile = self
1234            .window
1235            .sprite_atlas
1236            .get_or_insert_with(&params.clone().into(), &mut || {
1237                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1238            })?;
1239        let content_mask = self.content_mask().scale(scale_factor);
1240        let corner_radii = corner_radii.scale(scale_factor);
1241
1242        let window = &mut *self.window;
1243        window.next_frame.scene_builder.insert(
1244            &window.next_frame.z_index_stack,
1245            PolychromeSprite {
1246                order: 0,
1247                bounds,
1248                content_mask,
1249                corner_radii,
1250                tile,
1251                grayscale,
1252            },
1253        );
1254        Ok(())
1255    }
1256
1257    /// Paint a surface into the scene for the next frame at the current z-index.
1258    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1259        let scale_factor = self.scale_factor();
1260        let bounds = bounds.scale(scale_factor);
1261        let content_mask = self.content_mask().scale(scale_factor);
1262        let window = &mut *self.window;
1263        window.next_frame.scene_builder.insert(
1264            &window.next_frame.z_index_stack,
1265            Surface {
1266                order: 0,
1267                bounds,
1268                content_mask,
1269                image_buffer,
1270            },
1271        );
1272    }
1273
1274    /// Draw pixels to the display for this window based on the contents of its scene.
1275    pub(crate) fn draw(&mut self) -> Scene {
1276        self.window.dirty = false;
1277        self.window.drawing = true;
1278
1279        #[cfg(any(test, feature = "test-support"))]
1280        {
1281            self.window.focus_invalidated = false;
1282        }
1283
1284        self.text_system().start_frame();
1285        self.window.platform_window.clear_input_handler();
1286        self.window.layout_engine.as_mut().unwrap().clear();
1287        self.window.next_frame.clear();
1288        self.window.frame_arena.clear();
1289        let root_view = self.window.root_view.take().unwrap();
1290
1291        self.with_z_index(0, |cx| {
1292            cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1293                for (action_type, action_listeners) in &cx.app.global_action_listeners {
1294                    for action_listener in action_listeners.iter().cloned() {
1295                        let listener = cx
1296                            .window
1297                            .frame_arena
1298                            .alloc(|| {
1299                                move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1300                                    action_listener(action, phase, cx)
1301                                }
1302                            })
1303                            .map(|listener| listener as _);
1304                        cx.window
1305                            .next_frame
1306                            .dispatch_tree
1307                            .on_action(*action_type, listener)
1308                    }
1309                }
1310
1311                let available_space = cx.window.viewport_size.map(Into::into);
1312                root_view.draw(Point::default(), available_space, cx);
1313            })
1314        });
1315
1316        if let Some(active_drag) = self.app.active_drag.take() {
1317            self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1318                let offset = cx.mouse_position() - active_drag.cursor_offset;
1319                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1320                active_drag.view.draw(offset, available_space, cx);
1321            });
1322            self.active_drag = Some(active_drag);
1323        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1324            self.with_z_index(1, |cx| {
1325                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1326                active_tooltip
1327                    .view
1328                    .draw(active_tooltip.cursor_offset, available_space, cx);
1329            });
1330        }
1331
1332        self.window
1333            .next_frame
1334            .dispatch_tree
1335            .preserve_pending_keystrokes(
1336                &mut self.window.rendered_frame.dispatch_tree,
1337                self.window.focus,
1338            );
1339        self.window.next_frame.focus = self.window.focus;
1340        self.window.root_view = Some(root_view);
1341
1342        let previous_focus_path = self.window.rendered_frame.focus_path();
1343        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1344        let current_focus_path = self.window.rendered_frame.focus_path();
1345
1346        if previous_focus_path != current_focus_path {
1347            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1348                self.window
1349                    .blur_listeners
1350                    .clone()
1351                    .retain(&(), |listener| listener(self));
1352            }
1353
1354            let event = FocusEvent {
1355                previous_focus_path,
1356                current_focus_path,
1357            };
1358            self.window
1359                .focus_listeners
1360                .clone()
1361                .retain(&(), |listener| listener(&event, self));
1362        }
1363
1364        let scene = self.window.rendered_frame.scene_builder.build();
1365
1366        // Set the cursor only if we're the active window.
1367        let cursor_style = self
1368            .window
1369            .requested_cursor_style
1370            .take()
1371            .unwrap_or(CursorStyle::Arrow);
1372        if self.is_window_active() {
1373            self.platform.set_cursor_style(cursor_style);
1374        }
1375
1376        self.window.drawing = false;
1377        ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
1378
1379        scene
1380    }
1381
1382    /// Dispatch a mouse or keyboard event on the window.
1383    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1384        // Handlers may set this to false by calling `stop_propagation`.
1385        self.app.propagate_event = true;
1386        // Handlers may set this to true by calling `prevent_default`.
1387        self.window.default_prevented = false;
1388
1389        let event = match event {
1390            // Track the mouse position with our own state, since accessing the platform
1391            // API for the mouse position can only occur on the main thread.
1392            InputEvent::MouseMove(mouse_move) => {
1393                self.window.mouse_position = mouse_move.position;
1394                self.window.modifiers = mouse_move.modifiers;
1395                InputEvent::MouseMove(mouse_move)
1396            }
1397            InputEvent::MouseDown(mouse_down) => {
1398                self.window.mouse_position = mouse_down.position;
1399                self.window.modifiers = mouse_down.modifiers;
1400                InputEvent::MouseDown(mouse_down)
1401            }
1402            InputEvent::MouseUp(mouse_up) => {
1403                self.window.mouse_position = mouse_up.position;
1404                self.window.modifiers = mouse_up.modifiers;
1405                InputEvent::MouseUp(mouse_up)
1406            }
1407            InputEvent::MouseExited(mouse_exited) => {
1408                // todo!("Should we record that the mouse is outside of the window somehow? Or are these global pixels?")
1409                self.window.modifiers = mouse_exited.modifiers;
1410
1411                InputEvent::MouseExited(mouse_exited)
1412            }
1413            InputEvent::ModifiersChanged(modifiers_changed) => {
1414                self.window.modifiers = modifiers_changed.modifiers;
1415                InputEvent::ModifiersChanged(modifiers_changed)
1416            }
1417            InputEvent::ScrollWheel(scroll_wheel) => {
1418                self.window.mouse_position = scroll_wheel.position;
1419                self.window.modifiers = scroll_wheel.modifiers;
1420                InputEvent::ScrollWheel(scroll_wheel)
1421            }
1422            // Translate dragging and dropping of external files from the operating system
1423            // to internal drag and drop events.
1424            InputEvent::FileDrop(file_drop) => match file_drop {
1425                FileDropEvent::Entered { position, files } => {
1426                    self.window.mouse_position = position;
1427                    if self.active_drag.is_none() {
1428                        self.active_drag = Some(AnyDrag {
1429                            value: Box::new(files.clone()),
1430                            view: self.build_view(|_| files).into(),
1431                            cursor_offset: position,
1432                        });
1433                    }
1434                    InputEvent::MouseMove(MouseMoveEvent {
1435                        position,
1436                        pressed_button: Some(MouseButton::Left),
1437                        modifiers: Modifiers::default(),
1438                    })
1439                }
1440                FileDropEvent::Pending { position } => {
1441                    self.window.mouse_position = position;
1442                    InputEvent::MouseMove(MouseMoveEvent {
1443                        position,
1444                        pressed_button: Some(MouseButton::Left),
1445                        modifiers: Modifiers::default(),
1446                    })
1447                }
1448                FileDropEvent::Submit { position } => {
1449                    self.activate(true);
1450                    self.window.mouse_position = position;
1451                    InputEvent::MouseUp(MouseUpEvent {
1452                        button: MouseButton::Left,
1453                        position,
1454                        modifiers: Modifiers::default(),
1455                        click_count: 1,
1456                    })
1457                }
1458                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1459                    button: MouseButton::Left,
1460                    position: Point::default(),
1461                    modifiers: Modifiers::default(),
1462                    click_count: 1,
1463                }),
1464            },
1465            InputEvent::KeyDown(_) | InputEvent::KeyUp(_) => event,
1466        };
1467
1468        if let Some(any_mouse_event) = event.mouse_event() {
1469            self.dispatch_mouse_event(any_mouse_event);
1470        } else if let Some(any_key_event) = event.keyboard_event() {
1471            self.dispatch_key_event(any_key_event);
1472        }
1473
1474        !self.app.propagate_event
1475    }
1476
1477    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1478        if let Some(mut handlers) = self
1479            .window
1480            .rendered_frame
1481            .mouse_listeners
1482            .remove(&event.type_id())
1483        {
1484            // Because handlers may add other handlers, we sort every time.
1485            handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1486
1487            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1488            // special purposes, such as detecting events outside of a given Bounds.
1489            for (_, handler) in &mut handlers {
1490                handler(event, DispatchPhase::Capture, self);
1491                if !self.app.propagate_event {
1492                    break;
1493                }
1494            }
1495
1496            // Bubble phase, where most normal handlers do their work.
1497            if self.app.propagate_event {
1498                for (_, handler) in handlers.iter_mut().rev() {
1499                    handler(event, DispatchPhase::Bubble, self);
1500                    if !self.app.propagate_event {
1501                        break;
1502                    }
1503                }
1504            }
1505
1506            if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1507                self.active_drag = None;
1508            }
1509
1510            self.window
1511                .rendered_frame
1512                .mouse_listeners
1513                .insert(event.type_id(), handlers);
1514        }
1515    }
1516
1517    fn dispatch_key_event(&mut self, event: &dyn Any) {
1518        let node_id = self
1519            .window
1520            .focus
1521            .and_then(|focus_id| {
1522                self.window
1523                    .rendered_frame
1524                    .dispatch_tree
1525                    .focusable_node_id(focus_id)
1526            })
1527            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1528
1529        let dispatch_path = self
1530            .window
1531            .rendered_frame
1532            .dispatch_tree
1533            .dispatch_path(node_id);
1534
1535        let mut actions: Vec<Box<dyn Action>> = Vec::new();
1536
1537        // Capture phase
1538        let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1539        self.propagate_event = true;
1540
1541        for node_id in &dispatch_path {
1542            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1543
1544            if let Some(context) = node.context.clone() {
1545                context_stack.push(context);
1546            }
1547
1548            for key_listener in node.key_listeners.clone() {
1549                key_listener(event, DispatchPhase::Capture, self);
1550                if !self.propagate_event {
1551                    return;
1552                }
1553            }
1554        }
1555
1556        // Bubble phase
1557        for node_id in dispatch_path.iter().rev() {
1558            // Handle low level key events
1559            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1560            for key_listener in node.key_listeners.clone() {
1561                key_listener(event, DispatchPhase::Bubble, self);
1562                if !self.propagate_event {
1563                    return;
1564                }
1565            }
1566
1567            // Match keystrokes
1568            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1569            if node.context.is_some() {
1570                if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1571                    let mut new_actions = self
1572                        .window
1573                        .rendered_frame
1574                        .dispatch_tree
1575                        .dispatch_key(&key_down_event.keystroke, &context_stack);
1576                    actions.append(&mut new_actions);
1577                }
1578
1579                context_stack.pop();
1580            }
1581        }
1582
1583        for action in actions {
1584            self.dispatch_action_on_node(node_id, action.boxed_clone());
1585            if !self.propagate_event {
1586                self.dispatch_keystroke_observers(event, Some(action));
1587                return;
1588            }
1589        }
1590        self.dispatch_keystroke_observers(event, None);
1591    }
1592
1593    pub fn has_pending_keystrokes(&self) -> bool {
1594        self.window
1595            .rendered_frame
1596            .dispatch_tree
1597            .has_pending_keystrokes()
1598    }
1599
1600    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1601        let dispatch_path = self
1602            .window
1603            .rendered_frame
1604            .dispatch_tree
1605            .dispatch_path(node_id);
1606
1607        // Capture phase
1608        for node_id in &dispatch_path {
1609            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1610            for DispatchActionListener {
1611                action_type,
1612                listener,
1613            } in node.action_listeners.clone()
1614            {
1615                let any_action = action.as_any();
1616                if action_type == any_action.type_id() {
1617                    listener(any_action, DispatchPhase::Capture, self);
1618                    if !self.propagate_event {
1619                        return;
1620                    }
1621                }
1622            }
1623        }
1624        // Bubble phase
1625        for node_id in dispatch_path.iter().rev() {
1626            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1627            for DispatchActionListener {
1628                action_type,
1629                listener,
1630            } in node.action_listeners.clone()
1631            {
1632                let any_action = action.as_any();
1633                if action_type == any_action.type_id() {
1634                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1635                    listener(any_action, DispatchPhase::Bubble, self);
1636                    if !self.propagate_event {
1637                        return;
1638                    }
1639                }
1640            }
1641        }
1642    }
1643
1644    /// Register the given handler to be invoked whenever the global of the given type
1645    /// is updated.
1646    pub fn observe_global<G: 'static>(
1647        &mut self,
1648        f: impl Fn(&mut WindowContext<'_>) + 'static,
1649    ) -> Subscription {
1650        let window_handle = self.window.handle;
1651        let (subscription, activate) = self.global_observers.insert(
1652            TypeId::of::<G>(),
1653            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1654        );
1655        self.app.defer(move |_| activate());
1656        subscription
1657    }
1658
1659    pub fn activate_window(&self) {
1660        self.window.platform_window.activate();
1661    }
1662
1663    pub fn minimize_window(&self) {
1664        self.window.platform_window.minimize();
1665    }
1666
1667    pub fn toggle_full_screen(&self) {
1668        self.window.platform_window.toggle_full_screen();
1669    }
1670
1671    pub fn prompt(
1672        &self,
1673        level: PromptLevel,
1674        msg: &str,
1675        answers: &[&str],
1676    ) -> oneshot::Receiver<usize> {
1677        self.window.platform_window.prompt(level, msg, answers)
1678    }
1679
1680    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1681        let node_id = self
1682            .window
1683            .focus
1684            .and_then(|focus_id| {
1685                self.window
1686                    .rendered_frame
1687                    .dispatch_tree
1688                    .focusable_node_id(focus_id)
1689            })
1690            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1691
1692        self.window
1693            .rendered_frame
1694            .dispatch_tree
1695            .available_actions(node_id)
1696    }
1697
1698    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1699        self.window
1700            .rendered_frame
1701            .dispatch_tree
1702            .bindings_for_action(
1703                action,
1704                &self.window.rendered_frame.dispatch_tree.context_stack,
1705            )
1706    }
1707
1708    pub fn bindings_for_action_in(
1709        &self,
1710        action: &dyn Action,
1711        focus_handle: &FocusHandle,
1712    ) -> Vec<KeyBinding> {
1713        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1714
1715        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1716            return vec![];
1717        };
1718        let context_stack = dispatch_tree
1719            .dispatch_path(node_id)
1720            .into_iter()
1721            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1722            .collect();
1723        dispatch_tree.bindings_for_action(action, &context_stack)
1724    }
1725
1726    pub fn listener_for<V: Render, E>(
1727        &self,
1728        view: &View<V>,
1729        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1730    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1731        let view = view.downgrade();
1732        move |e: &E, cx: &mut WindowContext| {
1733            view.update(cx, |view, cx| f(view, e, cx)).ok();
1734        }
1735    }
1736
1737    pub fn handler_for<V: Render>(
1738        &self,
1739        view: &View<V>,
1740        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1741    ) -> impl Fn(&mut WindowContext) {
1742        let view = view.downgrade();
1743        move |cx: &mut WindowContext| {
1744            view.update(cx, |view, cx| f(view, cx)).ok();
1745        }
1746    }
1747
1748    //========== ELEMENT RELATED FUNCTIONS ===========
1749    pub fn with_key_dispatch<R>(
1750        &mut self,
1751        context: Option<KeyContext>,
1752        focus_handle: Option<FocusHandle>,
1753        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1754    ) -> R {
1755        let window = &mut self.window;
1756        window.next_frame.dispatch_tree.push_node(context.clone());
1757        if let Some(focus_handle) = focus_handle.as_ref() {
1758            window
1759                .next_frame
1760                .dispatch_tree
1761                .make_focusable(focus_handle.id);
1762        }
1763        let result = f(focus_handle, self);
1764
1765        self.window.next_frame.dispatch_tree.pop_node();
1766
1767        result
1768    }
1769
1770    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1771    /// platform to receive textual input with proper integration with concerns such
1772    /// as IME interactions.
1773    pub fn handle_input(
1774        &mut self,
1775        focus_handle: &FocusHandle,
1776        input_handler: impl PlatformInputHandler,
1777    ) {
1778        if focus_handle.is_focused(self) {
1779            self.window
1780                .platform_window
1781                .set_input_handler(Box::new(input_handler));
1782        }
1783    }
1784
1785    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1786        let mut this = self.to_async();
1787        self.window
1788            .platform_window
1789            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1790    }
1791}
1792
1793impl Context for WindowContext<'_> {
1794    type Result<T> = T;
1795
1796    fn build_model<T>(
1797        &mut self,
1798        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1799    ) -> Model<T>
1800    where
1801        T: 'static,
1802    {
1803        let slot = self.app.entities.reserve();
1804        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1805        self.entities.insert(slot, model)
1806    }
1807
1808    fn update_model<T: 'static, R>(
1809        &mut self,
1810        model: &Model<T>,
1811        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1812    ) -> R {
1813        let mut entity = self.entities.lease(model);
1814        let result = update(
1815            &mut *entity,
1816            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1817        );
1818        self.entities.end_lease(entity);
1819        result
1820    }
1821
1822    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1823    where
1824        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1825    {
1826        if window == self.window.handle {
1827            let root_view = self.window.root_view.clone().unwrap();
1828            Ok(update(root_view, self))
1829        } else {
1830            window.update(self.app, update)
1831        }
1832    }
1833
1834    fn read_model<T, R>(
1835        &self,
1836        handle: &Model<T>,
1837        read: impl FnOnce(&T, &AppContext) -> R,
1838    ) -> Self::Result<R>
1839    where
1840        T: 'static,
1841    {
1842        let entity = self.entities.read(handle);
1843        read(&*entity, &*self.app)
1844    }
1845
1846    fn read_window<T, R>(
1847        &self,
1848        window: &WindowHandle<T>,
1849        read: impl FnOnce(View<T>, &AppContext) -> R,
1850    ) -> Result<R>
1851    where
1852        T: 'static,
1853    {
1854        if window.any_handle == self.window.handle {
1855            let root_view = self
1856                .window
1857                .root_view
1858                .clone()
1859                .unwrap()
1860                .downcast::<T>()
1861                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1862            Ok(read(root_view, self))
1863        } else {
1864            self.app.read_window(window, read)
1865        }
1866    }
1867}
1868
1869impl VisualContext for WindowContext<'_> {
1870    fn build_view<V>(
1871        &mut self,
1872        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1873    ) -> Self::Result<View<V>>
1874    where
1875        V: 'static + Render,
1876    {
1877        let slot = self.app.entities.reserve();
1878        let view = View {
1879            model: slot.clone(),
1880        };
1881        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1882        let entity = build_view_state(&mut cx);
1883        cx.entities.insert(slot, entity);
1884
1885        cx.new_view_observers
1886            .clone()
1887            .retain(&TypeId::of::<V>(), |observer| {
1888                let any_view = AnyView::from(view.clone());
1889                (observer)(any_view, self);
1890                true
1891            });
1892
1893        view
1894    }
1895
1896    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1897    fn update_view<T: 'static, R>(
1898        &mut self,
1899        view: &View<T>,
1900        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1901    ) -> Self::Result<R> {
1902        let mut lease = self.app.entities.lease(&view.model);
1903        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1904        let result = update(&mut *lease, &mut cx);
1905        cx.app.entities.end_lease(lease);
1906        result
1907    }
1908
1909    fn replace_root_view<V>(
1910        &mut self,
1911        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1912    ) -> Self::Result<View<V>>
1913    where
1914        V: 'static + Render,
1915    {
1916        let slot = self.app.entities.reserve();
1917        let view = View {
1918            model: slot.clone(),
1919        };
1920        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1921        let entity = build_view(&mut cx);
1922        self.entities.insert(slot, entity);
1923        self.window.root_view = Some(view.clone().into());
1924        view
1925    }
1926
1927    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1928        self.update_view(view, |view, cx| {
1929            view.focus_handle(cx).clone().focus(cx);
1930        })
1931    }
1932
1933    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1934    where
1935        V: ManagedView,
1936    {
1937        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1938    }
1939}
1940
1941impl<'a> std::ops::Deref for WindowContext<'a> {
1942    type Target = AppContext;
1943
1944    fn deref(&self) -> &Self::Target {
1945        &self.app
1946    }
1947}
1948
1949impl<'a> std::ops::DerefMut for WindowContext<'a> {
1950    fn deref_mut(&mut self) -> &mut Self::Target {
1951        &mut self.app
1952    }
1953}
1954
1955impl<'a> Borrow<AppContext> for WindowContext<'a> {
1956    fn borrow(&self) -> &AppContext {
1957        &self.app
1958    }
1959}
1960
1961impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1962    fn borrow_mut(&mut self) -> &mut AppContext {
1963        &mut self.app
1964    }
1965}
1966
1967pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1968    fn app_mut(&mut self) -> &mut AppContext {
1969        self.borrow_mut()
1970    }
1971
1972    fn app(&self) -> &AppContext {
1973        self.borrow()
1974    }
1975
1976    fn window(&self) -> &Window {
1977        self.borrow()
1978    }
1979
1980    fn window_mut(&mut self) -> &mut Window {
1981        self.borrow_mut()
1982    }
1983
1984    /// Pushes the given element id onto the global stack and invokes the given closure
1985    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1986    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1987    /// used to associate state with identified elements across separate frames.
1988    fn with_element_id<R>(
1989        &mut self,
1990        id: Option<impl Into<ElementId>>,
1991        f: impl FnOnce(&mut Self) -> R,
1992    ) -> R {
1993        if let Some(id) = id.map(Into::into) {
1994            let window = self.window_mut();
1995            window.element_id_stack.push(id.into());
1996            let result = f(self);
1997            let window: &mut Window = self.borrow_mut();
1998            window.element_id_stack.pop();
1999            result
2000        } else {
2001            f(self)
2002        }
2003    }
2004
2005    /// Invoke the given function with the given content mask after intersecting it
2006    /// with the current mask.
2007    fn with_content_mask<R>(
2008        &mut self,
2009        mask: Option<ContentMask<Pixels>>,
2010        f: impl FnOnce(&mut Self) -> R,
2011    ) -> R {
2012        if let Some(mask) = mask {
2013            let mask = mask.intersect(&self.content_mask());
2014            self.window_mut().next_frame.content_mask_stack.push(mask);
2015            let result = f(self);
2016            self.window_mut().next_frame.content_mask_stack.pop();
2017            result
2018        } else {
2019            f(self)
2020        }
2021    }
2022
2023    /// Invoke the given function with the content mask reset to that
2024    /// of the window.
2025    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2026        let mask = ContentMask {
2027            bounds: Bounds {
2028                origin: Point::default(),
2029                size: self.window().viewport_size,
2030            },
2031        };
2032        self.window_mut().next_frame.content_mask_stack.push(mask);
2033        let result = f(self);
2034        self.window_mut().next_frame.content_mask_stack.pop();
2035        result
2036    }
2037
2038    /// Update the global element offset relative to the current offset. This is used to implement
2039    /// scrolling.
2040    fn with_element_offset<R>(
2041        &mut self,
2042        offset: Point<Pixels>,
2043        f: impl FnOnce(&mut Self) -> R,
2044    ) -> R {
2045        if offset.is_zero() {
2046            return f(self);
2047        };
2048
2049        let abs_offset = self.element_offset() + offset;
2050        self.with_absolute_element_offset(abs_offset, f)
2051    }
2052
2053    /// Update the global element offset based on the given offset. This is used to implement
2054    /// drag handles and other manual painting of elements.
2055    fn with_absolute_element_offset<R>(
2056        &mut self,
2057        offset: Point<Pixels>,
2058        f: impl FnOnce(&mut Self) -> R,
2059    ) -> R {
2060        self.window_mut()
2061            .next_frame
2062            .element_offset_stack
2063            .push(offset);
2064        let result = f(self);
2065        self.window_mut().next_frame.element_offset_stack.pop();
2066        result
2067    }
2068
2069    /// Obtain the current element offset.
2070    fn element_offset(&self) -> Point<Pixels> {
2071        self.window()
2072            .next_frame
2073            .element_offset_stack
2074            .last()
2075            .copied()
2076            .unwrap_or_default()
2077    }
2078
2079    /// Update or initialize state for an element with the given id that lives across multiple
2080    /// frames. If an element with this id existed in the rendered frame, its state will be passed
2081    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2082    /// when drawing the next frame.
2083    fn with_element_state<S, R>(
2084        &mut self,
2085        id: ElementId,
2086        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2087    ) -> R
2088    where
2089        S: 'static,
2090    {
2091        self.with_element_id(Some(id), |cx| {
2092            let global_id = cx.window().element_id_stack.clone();
2093
2094            if let Some(any) = cx
2095                .window_mut()
2096                .next_frame
2097                .element_states
2098                .remove(&global_id)
2099                .or_else(|| {
2100                    cx.window_mut()
2101                        .rendered_frame
2102                        .element_states
2103                        .remove(&global_id)
2104                })
2105            {
2106                let ElementStateBox {
2107                    inner,
2108
2109                    #[cfg(debug_assertions)]
2110                    type_name
2111                } = any;
2112                // Using the extra inner option to avoid needing to reallocate a new box.
2113                let mut state_box = inner
2114                    .downcast::<Option<S>>()
2115                    .map_err(|_| {
2116                        #[cfg(debug_assertions)]
2117                        {
2118                            anyhow!(
2119                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2120                                std::any::type_name::<S>(),
2121                                type_name
2122                            )
2123                        }
2124
2125                        #[cfg(not(debug_assertions))]
2126                        {
2127                            anyhow!(
2128                                "invalid element state type for id, requested_type {:?}",
2129                                std::any::type_name::<S>(),
2130                            )
2131                        }
2132                    })
2133                    .unwrap();
2134
2135                // Actual: Option<AnyElement> <- View
2136                // Requested: () <- AnyElemet
2137                let state = state_box
2138                    .take()
2139                    .expect("element state is already on the stack");
2140                let (result, state) = f(Some(state), cx);
2141                state_box.replace(state);
2142                cx.window_mut()
2143                    .next_frame
2144                    .element_states
2145                    .insert(global_id, ElementStateBox {
2146                        inner: state_box,
2147
2148                        #[cfg(debug_assertions)]
2149                        type_name
2150                    });
2151                result
2152            } else {
2153                let (result, state) = f(None, cx);
2154                cx.window_mut()
2155                    .next_frame
2156                    .element_states
2157                    .insert(global_id,
2158                        ElementStateBox {
2159                            inner: Box::new(Some(state)),
2160
2161                            #[cfg(debug_assertions)]
2162                            type_name: std::any::type_name::<S>()
2163                        }
2164
2165                    );
2166                result
2167            }
2168        })
2169    }
2170
2171    /// Obtain the current content mask.
2172    fn content_mask(&self) -> ContentMask<Pixels> {
2173        self.window()
2174            .next_frame
2175            .content_mask_stack
2176            .last()
2177            .cloned()
2178            .unwrap_or_else(|| ContentMask {
2179                bounds: Bounds {
2180                    origin: Point::default(),
2181                    size: self.window().viewport_size,
2182                },
2183            })
2184    }
2185
2186    /// The size of an em for the base font of the application. Adjusting this value allows the
2187    /// UI to scale, just like zooming a web page.
2188    fn rem_size(&self) -> Pixels {
2189        self.window().rem_size
2190    }
2191}
2192
2193impl Borrow<Window> for WindowContext<'_> {
2194    fn borrow(&self) -> &Window {
2195        &self.window
2196    }
2197}
2198
2199impl BorrowMut<Window> for WindowContext<'_> {
2200    fn borrow_mut(&mut self) -> &mut Window {
2201        &mut self.window
2202    }
2203}
2204
2205impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2206
2207pub struct ViewContext<'a, V> {
2208    window_cx: WindowContext<'a>,
2209    view: &'a View<V>,
2210}
2211
2212impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2213    fn borrow(&self) -> &AppContext {
2214        &*self.window_cx.app
2215    }
2216}
2217
2218impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2219    fn borrow_mut(&mut self) -> &mut AppContext {
2220        &mut *self.window_cx.app
2221    }
2222}
2223
2224impl<V> Borrow<Window> for ViewContext<'_, V> {
2225    fn borrow(&self) -> &Window {
2226        &*self.window_cx.window
2227    }
2228}
2229
2230impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2231    fn borrow_mut(&mut self) -> &mut Window {
2232        &mut *self.window_cx.window
2233    }
2234}
2235
2236impl<'a, V: 'static> ViewContext<'a, V> {
2237    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2238        Self {
2239            window_cx: WindowContext::new(app, window),
2240            view,
2241        }
2242    }
2243
2244    pub fn entity_id(&self) -> EntityId {
2245        self.view.entity_id()
2246    }
2247
2248    pub fn view(&self) -> &View<V> {
2249        self.view
2250    }
2251
2252    pub fn model(&self) -> &Model<V> {
2253        &self.view.model
2254    }
2255
2256    /// Access the underlying window context.
2257    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2258        &mut self.window_cx
2259    }
2260
2261    pub fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2262        self.window.next_frame.z_index_stack.push(z_index);
2263        let result = f(self);
2264        self.window.next_frame.z_index_stack.pop();
2265        result
2266    }
2267
2268    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2269    where
2270        V: 'static,
2271    {
2272        let view = self.view().clone();
2273        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2274    }
2275
2276    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2277    /// that are currently on the stack to be returned to the app.
2278    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2279        let view = self.view().downgrade();
2280        self.window_cx.defer(move |cx| {
2281            view.update(cx, f).ok();
2282        });
2283    }
2284
2285    pub fn observe<V2, E>(
2286        &mut self,
2287        entity: &E,
2288        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2289    ) -> Subscription
2290    where
2291        V2: 'static,
2292        V: 'static,
2293        E: Entity<V2>,
2294    {
2295        let view = self.view().downgrade();
2296        let entity_id = entity.entity_id();
2297        let entity = entity.downgrade();
2298        let window_handle = self.window.handle;
2299        let (subscription, activate) = self.app.observers.insert(
2300            entity_id,
2301            Box::new(move |cx| {
2302                window_handle
2303                    .update(cx, |_, cx| {
2304                        if let Some(handle) = E::upgrade_from(&entity) {
2305                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2306                                .is_ok()
2307                        } else {
2308                            false
2309                        }
2310                    })
2311                    .unwrap_or(false)
2312            }),
2313        );
2314        self.app.defer(move |_| activate());
2315        subscription
2316    }
2317
2318    pub fn subscribe<V2, E, Evt>(
2319        &mut self,
2320        entity: &E,
2321        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2322    ) -> Subscription
2323    where
2324        V2: EventEmitter<Evt>,
2325        E: Entity<V2>,
2326        Evt: 'static,
2327    {
2328        let view = self.view().downgrade();
2329        let entity_id = entity.entity_id();
2330        let handle = entity.downgrade();
2331        let window_handle = self.window.handle;
2332        let (subscription, activate) = self.app.event_listeners.insert(
2333            entity_id,
2334            (
2335                TypeId::of::<Evt>(),
2336                Box::new(move |event, cx| {
2337                    window_handle
2338                        .update(cx, |_, cx| {
2339                            if let Some(handle) = E::upgrade_from(&handle) {
2340                                let event = event.downcast_ref().expect("invalid event type");
2341                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2342                                    .is_ok()
2343                            } else {
2344                                false
2345                            }
2346                        })
2347                        .unwrap_or(false)
2348                }),
2349            ),
2350        );
2351        self.app.defer(move |_| activate());
2352        subscription
2353    }
2354
2355    pub fn on_release(
2356        &mut self,
2357        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2358    ) -> Subscription {
2359        let window_handle = self.window.handle;
2360        let (subscription, activate) = self.app.release_listeners.insert(
2361            self.view.model.entity_id,
2362            Box::new(move |this, cx| {
2363                let this = this.downcast_mut().expect("invalid entity type");
2364                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2365            }),
2366        );
2367        activate();
2368        subscription
2369    }
2370
2371    pub fn observe_release<V2, E>(
2372        &mut self,
2373        entity: &E,
2374        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2375    ) -> Subscription
2376    where
2377        V: 'static,
2378        V2: 'static,
2379        E: Entity<V2>,
2380    {
2381        let view = self.view().downgrade();
2382        let entity_id = entity.entity_id();
2383        let window_handle = self.window.handle;
2384        let (subscription, activate) = self.app.release_listeners.insert(
2385            entity_id,
2386            Box::new(move |entity, cx| {
2387                let entity = entity.downcast_mut().expect("invalid entity type");
2388                let _ = window_handle.update(cx, |_, cx| {
2389                    view.update(cx, |this, cx| on_release(this, entity, cx))
2390                });
2391            }),
2392        );
2393        activate();
2394        subscription
2395    }
2396
2397    pub fn notify(&mut self) {
2398        if !self.window.drawing {
2399            self.window_cx.notify();
2400            self.window_cx.app.push_effect(Effect::Notify {
2401                emitter: self.view.model.entity_id,
2402            });
2403        }
2404    }
2405
2406    pub fn observe_window_bounds(
2407        &mut self,
2408        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2409    ) -> Subscription {
2410        let view = self.view.downgrade();
2411        let (subscription, activate) = self.window.bounds_observers.insert(
2412            (),
2413            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2414        );
2415        activate();
2416        subscription
2417    }
2418
2419    pub fn observe_window_activation(
2420        &mut self,
2421        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2422    ) -> Subscription {
2423        let view = self.view.downgrade();
2424        let (subscription, activate) = self.window.activation_observers.insert(
2425            (),
2426            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2427        );
2428        activate();
2429        subscription
2430    }
2431
2432    /// Register a listener to be called when the given focus handle receives focus.
2433    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2434    /// is dropped.
2435    pub fn on_focus(
2436        &mut self,
2437        handle: &FocusHandle,
2438        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2439    ) -> Subscription {
2440        let view = self.view.downgrade();
2441        let focus_id = handle.id;
2442        let (subscription, activate) = self.window.focus_listeners.insert(
2443            (),
2444            Box::new(move |event, cx| {
2445                view.update(cx, |view, cx| {
2446                    if event.previous_focus_path.last() != Some(&focus_id)
2447                        && event.current_focus_path.last() == Some(&focus_id)
2448                    {
2449                        listener(view, cx)
2450                    }
2451                })
2452                .is_ok()
2453            }),
2454        );
2455        self.app.defer(move |_| activate());
2456        subscription
2457    }
2458
2459    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2460    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2461    /// is dropped.
2462    pub fn on_focus_in(
2463        &mut self,
2464        handle: &FocusHandle,
2465        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2466    ) -> Subscription {
2467        let view = self.view.downgrade();
2468        let focus_id = handle.id;
2469        let (subscription, activate) = self.window.focus_listeners.insert(
2470            (),
2471            Box::new(move |event, cx| {
2472                view.update(cx, |view, cx| {
2473                    if !event.previous_focus_path.contains(&focus_id)
2474                        && event.current_focus_path.contains(&focus_id)
2475                    {
2476                        listener(view, cx)
2477                    }
2478                })
2479                .is_ok()
2480            }),
2481        );
2482        self.app.defer(move |_| activate());
2483        subscription
2484    }
2485
2486    /// Register a listener to be called when the given focus handle loses focus.
2487    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2488    /// is dropped.
2489    pub fn on_blur(
2490        &mut self,
2491        handle: &FocusHandle,
2492        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2493    ) -> Subscription {
2494        let view = self.view.downgrade();
2495        let focus_id = handle.id;
2496        let (subscription, activate) = self.window.focus_listeners.insert(
2497            (),
2498            Box::new(move |event, cx| {
2499                view.update(cx, |view, cx| {
2500                    if event.previous_focus_path.last() == Some(&focus_id)
2501                        && event.current_focus_path.last() != Some(&focus_id)
2502                    {
2503                        listener(view, cx)
2504                    }
2505                })
2506                .is_ok()
2507            }),
2508        );
2509        self.app.defer(move |_| activate());
2510        subscription
2511    }
2512
2513    /// Register a listener to be called when the window loses focus.
2514    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2515    /// is dropped.
2516    pub fn on_blur_window(
2517        &mut self,
2518        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2519    ) -> Subscription {
2520        let view = self.view.downgrade();
2521        let (subscription, activate) = self.window.blur_listeners.insert(
2522            (),
2523            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2524        );
2525        activate();
2526        subscription
2527    }
2528
2529    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2530    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2531    /// is dropped.
2532    pub fn on_focus_out(
2533        &mut self,
2534        handle: &FocusHandle,
2535        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2536    ) -> Subscription {
2537        let view = self.view.downgrade();
2538        let focus_id = handle.id;
2539        let (subscription, activate) = self.window.focus_listeners.insert(
2540            (),
2541            Box::new(move |event, cx| {
2542                view.update(cx, |view, cx| {
2543                    if event.previous_focus_path.contains(&focus_id)
2544                        && !event.current_focus_path.contains(&focus_id)
2545                    {
2546                        listener(view, cx)
2547                    }
2548                })
2549                .is_ok()
2550            }),
2551        );
2552        self.app.defer(move |_| activate());
2553        subscription
2554    }
2555
2556    pub fn spawn<Fut, R>(
2557        &mut self,
2558        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2559    ) -> Task<R>
2560    where
2561        R: 'static,
2562        Fut: Future<Output = R> + 'static,
2563    {
2564        let view = self.view().downgrade();
2565        self.window_cx.spawn(|cx| f(view, cx))
2566    }
2567
2568    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2569    where
2570        G: 'static,
2571    {
2572        let mut global = self.app.lease_global::<G>();
2573        let result = f(&mut global, self);
2574        self.app.end_global_lease(global);
2575        result
2576    }
2577
2578    pub fn observe_global<G: 'static>(
2579        &mut self,
2580        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2581    ) -> Subscription {
2582        let window_handle = self.window.handle;
2583        let view = self.view().downgrade();
2584        let (subscription, activate) = self.global_observers.insert(
2585            TypeId::of::<G>(),
2586            Box::new(move |cx| {
2587                window_handle
2588                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2589                    .unwrap_or(false)
2590            }),
2591        );
2592        self.app.defer(move |_| activate());
2593        subscription
2594    }
2595
2596    pub fn on_mouse_event<Event: 'static>(
2597        &mut self,
2598        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2599    ) {
2600        let handle = self.view().clone();
2601        self.window_cx.on_mouse_event(move |event, phase, cx| {
2602            handle.update(cx, |view, cx| {
2603                handler(view, event, phase, cx);
2604            })
2605        });
2606    }
2607
2608    pub fn on_key_event<Event: 'static>(
2609        &mut self,
2610        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2611    ) {
2612        let handle = self.view().clone();
2613        self.window_cx.on_key_event(move |event, phase, cx| {
2614            handle.update(cx, |view, cx| {
2615                handler(view, event, phase, cx);
2616            })
2617        });
2618    }
2619
2620    pub fn on_action(
2621        &mut self,
2622        action_type: TypeId,
2623        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2624    ) {
2625        let handle = self.view().clone();
2626        self.window_cx
2627            .on_action(action_type, move |action, phase, cx| {
2628                handle.update(cx, |view, cx| {
2629                    listener(view, action, phase, cx);
2630                })
2631            });
2632    }
2633
2634    pub fn emit<Evt>(&mut self, event: Evt)
2635    where
2636        Evt: 'static,
2637        V: EventEmitter<Evt>,
2638    {
2639        let emitter = self.view.model.entity_id;
2640        self.app.push_effect(Effect::Emit {
2641            emitter,
2642            event_type: TypeId::of::<Evt>(),
2643            event: Box::new(event),
2644        });
2645    }
2646
2647    pub fn focus_self(&mut self)
2648    where
2649        V: FocusableView,
2650    {
2651        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2652    }
2653
2654    pub fn dismiss_self(&mut self)
2655    where
2656        V: ManagedView,
2657    {
2658        self.defer(|_, cx| cx.emit(DismissEvent))
2659    }
2660
2661    pub fn listener<E>(
2662        &self,
2663        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2664    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2665        let view = self.view().downgrade();
2666        move |e: &E, cx: &mut WindowContext| {
2667            view.update(cx, |view, cx| f(view, e, cx)).ok();
2668        }
2669    }
2670}
2671
2672impl<V> Context for ViewContext<'_, V> {
2673    type Result<U> = U;
2674
2675    fn build_model<T: 'static>(
2676        &mut self,
2677        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2678    ) -> Model<T> {
2679        self.window_cx.build_model(build_model)
2680    }
2681
2682    fn update_model<T: 'static, R>(
2683        &mut self,
2684        model: &Model<T>,
2685        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2686    ) -> R {
2687        self.window_cx.update_model(model, update)
2688    }
2689
2690    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2691    where
2692        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2693    {
2694        self.window_cx.update_window(window, update)
2695    }
2696
2697    fn read_model<T, R>(
2698        &self,
2699        handle: &Model<T>,
2700        read: impl FnOnce(&T, &AppContext) -> R,
2701    ) -> Self::Result<R>
2702    where
2703        T: 'static,
2704    {
2705        self.window_cx.read_model(handle, read)
2706    }
2707
2708    fn read_window<T, R>(
2709        &self,
2710        window: &WindowHandle<T>,
2711        read: impl FnOnce(View<T>, &AppContext) -> R,
2712    ) -> Result<R>
2713    where
2714        T: 'static,
2715    {
2716        self.window_cx.read_window(window, read)
2717    }
2718}
2719
2720impl<V: 'static> VisualContext for ViewContext<'_, V> {
2721    fn build_view<W: Render + 'static>(
2722        &mut self,
2723        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2724    ) -> Self::Result<View<W>> {
2725        self.window_cx.build_view(build_view_state)
2726    }
2727
2728    fn update_view<V2: 'static, R>(
2729        &mut self,
2730        view: &View<V2>,
2731        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2732    ) -> Self::Result<R> {
2733        self.window_cx.update_view(view, update)
2734    }
2735
2736    fn replace_root_view<W>(
2737        &mut self,
2738        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2739    ) -> Self::Result<View<W>>
2740    where
2741        W: 'static + Render,
2742    {
2743        self.window_cx.replace_root_view(build_view)
2744    }
2745
2746    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2747        self.window_cx.focus_view(view)
2748    }
2749
2750    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2751        self.window_cx.dismiss_view(view)
2752    }
2753}
2754
2755impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2756    type Target = WindowContext<'a>;
2757
2758    fn deref(&self) -> &Self::Target {
2759        &self.window_cx
2760    }
2761}
2762
2763impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2764    fn deref_mut(&mut self) -> &mut Self::Target {
2765        &mut self.window_cx
2766    }
2767}
2768
2769// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2770slotmap::new_key_type! { pub struct WindowId; }
2771
2772impl WindowId {
2773    pub fn as_u64(&self) -> u64 {
2774        self.0.as_ffi()
2775    }
2776}
2777
2778#[derive(Deref, DerefMut)]
2779pub struct WindowHandle<V> {
2780    #[deref]
2781    #[deref_mut]
2782    pub(crate) any_handle: AnyWindowHandle,
2783    state_type: PhantomData<V>,
2784}
2785
2786impl<V: 'static + Render> WindowHandle<V> {
2787    pub fn new(id: WindowId) -> Self {
2788        WindowHandle {
2789            any_handle: AnyWindowHandle {
2790                id,
2791                state_type: TypeId::of::<V>(),
2792            },
2793            state_type: PhantomData,
2794        }
2795    }
2796
2797    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2798    where
2799        C: Context,
2800    {
2801        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2802            root_view
2803                .downcast::<V>()
2804                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2805        }))
2806    }
2807
2808    pub fn update<C, R>(
2809        &self,
2810        cx: &mut C,
2811        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2812    ) -> Result<R>
2813    where
2814        C: Context,
2815    {
2816        cx.update_window(self.any_handle, |root_view, cx| {
2817            let view = root_view
2818                .downcast::<V>()
2819                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2820            Ok(cx.update_view(&view, update))
2821        })?
2822    }
2823
2824    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2825        let x = cx
2826            .windows
2827            .get(self.id)
2828            .and_then(|window| {
2829                window
2830                    .as_ref()
2831                    .and_then(|window| window.root_view.clone())
2832                    .map(|root_view| root_view.downcast::<V>())
2833            })
2834            .ok_or_else(|| anyhow!("window not found"))?
2835            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2836
2837        Ok(x.read(cx))
2838    }
2839
2840    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2841    where
2842        C: Context,
2843    {
2844        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2845    }
2846
2847    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2848    where
2849        C: Context,
2850    {
2851        cx.read_window(self, |root_view, _cx| root_view.clone())
2852    }
2853
2854    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2855        cx.windows
2856            .get(self.id)
2857            .and_then(|window| window.as_ref().map(|window| window.active))
2858    }
2859}
2860
2861impl<V> Copy for WindowHandle<V> {}
2862
2863impl<V> Clone for WindowHandle<V> {
2864    fn clone(&self) -> Self {
2865        WindowHandle {
2866            any_handle: self.any_handle,
2867            state_type: PhantomData,
2868        }
2869    }
2870}
2871
2872impl<V> PartialEq for WindowHandle<V> {
2873    fn eq(&self, other: &Self) -> bool {
2874        self.any_handle == other.any_handle
2875    }
2876}
2877
2878impl<V> Eq for WindowHandle<V> {}
2879
2880impl<V> Hash for WindowHandle<V> {
2881    fn hash<H: Hasher>(&self, state: &mut H) {
2882        self.any_handle.hash(state);
2883    }
2884}
2885
2886impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2887    fn into(self) -> AnyWindowHandle {
2888        self.any_handle
2889    }
2890}
2891
2892#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2893pub struct AnyWindowHandle {
2894    pub(crate) id: WindowId,
2895    state_type: TypeId,
2896}
2897
2898impl AnyWindowHandle {
2899    pub fn window_id(&self) -> WindowId {
2900        self.id
2901    }
2902
2903    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2904        if TypeId::of::<T>() == self.state_type {
2905            Some(WindowHandle {
2906                any_handle: *self,
2907                state_type: PhantomData,
2908            })
2909        } else {
2910            None
2911        }
2912    }
2913
2914    pub fn update<C, R>(
2915        self,
2916        cx: &mut C,
2917        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2918    ) -> Result<R>
2919    where
2920        C: Context,
2921    {
2922        cx.update_window(self, update)
2923    }
2924
2925    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2926    where
2927        C: Context,
2928        T: 'static,
2929    {
2930        let view = self
2931            .downcast::<T>()
2932            .context("the type of the window's root view has changed")?;
2933
2934        cx.read_window(&view, read)
2935    }
2936}
2937
2938// #[cfg(any(test, feature = "test-support"))]
2939// impl From<SmallVec<[u32; 16]>> for StackingOrder {
2940//     fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2941//         StackingOrder(small_vec)
2942//     }
2943// }
2944
2945#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2946pub enum ElementId {
2947    View(EntityId),
2948    Integer(usize),
2949    Name(SharedString),
2950    FocusHandle(FocusId),
2951    NamedInteger(SharedString, usize),
2952}
2953
2954impl ElementId {
2955    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2956        ElementId::View(entity_id)
2957    }
2958}
2959
2960impl TryInto<SharedString> for ElementId {
2961    type Error = anyhow::Error;
2962
2963    fn try_into(self) -> anyhow::Result<SharedString> {
2964        if let ElementId::Name(name) = self {
2965            Ok(name)
2966        } else {
2967            Err(anyhow!("element id is not string"))
2968        }
2969    }
2970}
2971
2972impl From<usize> for ElementId {
2973    fn from(id: usize) -> Self {
2974        ElementId::Integer(id)
2975    }
2976}
2977
2978impl From<i32> for ElementId {
2979    fn from(id: i32) -> Self {
2980        Self::Integer(id as usize)
2981    }
2982}
2983
2984impl From<SharedString> for ElementId {
2985    fn from(name: SharedString) -> Self {
2986        ElementId::Name(name)
2987    }
2988}
2989
2990impl From<&'static str> for ElementId {
2991    fn from(name: &'static str) -> Self {
2992        ElementId::Name(name.into())
2993    }
2994}
2995
2996impl<'a> From<&'a FocusHandle> for ElementId {
2997    fn from(handle: &'a FocusHandle) -> Self {
2998        ElementId::FocusHandle(handle.id)
2999    }
3000}
3001
3002impl From<(&'static str, EntityId)> for ElementId {
3003    fn from((name, id): (&'static str, EntityId)) -> Self {
3004        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3005    }
3006}
3007
3008impl From<(&'static str, usize)> for ElementId {
3009    fn from((name, id): (&'static str, usize)) -> Self {
3010        ElementId::NamedInteger(name.into(), id)
3011    }
3012}
3013
3014impl From<(&'static str, u64)> for ElementId {
3015    fn from((name, id): (&'static str, u64)) -> Self {
3016        ElementId::NamedInteger(name.into(), id as usize)
3017    }
3018}
3019
3020/// A rectangle, to be rendered on the screen by GPUI at the given position and size.
3021pub struct PaintQuad {
3022    bounds: Bounds<Pixels>,
3023    corner_radii: Corners<Pixels>,
3024    background: Hsla,
3025    border_widths: Edges<Pixels>,
3026    border_color: Hsla,
3027}
3028
3029impl PaintQuad {
3030    /// Set the corner radii of the quad.
3031    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3032        PaintQuad {
3033            corner_radii: corner_radii.into(),
3034            ..self
3035        }
3036    }
3037
3038    /// Set the border widths of the quad.
3039    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3040        PaintQuad {
3041            border_widths: border_widths.into(),
3042            ..self
3043        }
3044    }
3045
3046    /// Set the border color of the quad.
3047    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3048        PaintQuad {
3049            border_color: border_color.into(),
3050            ..self
3051        }
3052    }
3053
3054    /// Set the background color of the quad.
3055    pub fn background(self, background: impl Into<Hsla>) -> Self {
3056        PaintQuad {
3057            background: background.into(),
3058            ..self
3059        }
3060    }
3061}
3062
3063/// Create a quad with the given parameters.
3064pub fn quad(
3065    bounds: Bounds<Pixels>,
3066    corner_radii: impl Into<Corners<Pixels>>,
3067    background: impl Into<Hsla>,
3068    border_widths: impl Into<Edges<Pixels>>,
3069    border_color: impl Into<Hsla>,
3070) -> PaintQuad {
3071    PaintQuad {
3072        bounds,
3073        corner_radii: corner_radii.into(),
3074        background: background.into(),
3075        border_widths: border_widths.into(),
3076        border_color: border_color.into(),
3077    }
3078}
3079
3080/// Create a filled quad with the given bounds and background color.
3081pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3082    PaintQuad {
3083        bounds: bounds.into(),
3084        corner_radii: (0.).into(),
3085        background: background.into(),
3086        border_widths: (0.).into(),
3087        border_color: transparent_black(),
3088    }
3089}
3090
3091/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3092pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3093    PaintQuad {
3094        bounds: bounds.into(),
3095        corner_radii: (0.).into(),
3096        background: transparent_black(),
3097        border_widths: (1.).into(),
3098        border_color: border_color.into(),
3099    }
3100}