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 set_window_edited(&mut self, edited: bool) {
 777        self.window.platform_window.set_edited(edited);
 778    }
 779
 780    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 781        self.platform
 782            .displays()
 783            .into_iter()
 784            .find(|display| display.id() == self.window.display_id)
 785    }
 786
 787    pub fn show_character_palette(&self) {
 788        self.window.platform_window.show_character_palette();
 789    }
 790
 791    /// The scale factor of the display associated with the window. For example, it could
 792    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 793    /// be rendered as two pixels on screen.
 794    pub fn scale_factor(&self) -> f32 {
 795        self.window.scale_factor
 796    }
 797
 798    /// The size of an em for the base font of the application. Adjusting this value allows the
 799    /// UI to scale, just like zooming a web page.
 800    pub fn rem_size(&self) -> Pixels {
 801        self.window.rem_size
 802    }
 803
 804    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 805    /// UI to scale, just like zooming a web page.
 806    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 807        self.window.rem_size = rem_size.into();
 808    }
 809
 810    /// The line height associated with the current text style.
 811    pub fn line_height(&self) -> Pixels {
 812        let rem_size = self.rem_size();
 813        let text_style = self.text_style();
 814        text_style
 815            .line_height
 816            .to_pixels(text_style.font_size.into(), rem_size)
 817    }
 818
 819    /// Call to prevent the default action of an event. Currently only used to prevent
 820    /// parent elements from becoming focused on mouse down.
 821    pub fn prevent_default(&mut self) {
 822        self.window.default_prevented = true;
 823    }
 824
 825    /// Obtain whether default has been prevented for the event currently being dispatched.
 826    pub fn default_prevented(&self) -> bool {
 827        self.window.default_prevented
 828    }
 829
 830    /// Register a mouse event listener on the window for the next frame. The type of event
 831    /// is determined by the first parameter of the given listener. When the next frame is rendered
 832    /// the listener will be cleared.
 833    pub fn on_mouse_event<Event: 'static>(
 834        &mut self,
 835        mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
 836    ) {
 837        let order = self.window.next_frame.z_index_stack.clone();
 838        let handler = self
 839            .window
 840            .frame_arena
 841            .alloc(|| {
 842                move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
 843                    handler(event.downcast_ref().unwrap(), phase, cx)
 844                }
 845            })
 846            .map(|handler| handler as _);
 847        self.window
 848            .next_frame
 849            .mouse_listeners
 850            .entry(TypeId::of::<Event>())
 851            .or_default()
 852            .push((order, handler))
 853    }
 854
 855    /// Register a key event listener on the window for the next frame. The type of event
 856    /// is determined by the first parameter of the given listener. When the next frame is rendered
 857    /// the listener will be cleared.
 858    ///
 859    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 860    /// a specific need to register a global listener.
 861    pub fn on_key_event<Event: 'static>(
 862        &mut self,
 863        listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 864    ) {
 865        let listener = self
 866            .window
 867            .frame_arena
 868            .alloc(|| {
 869                move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
 870                    if let Some(event) = event.downcast_ref::<Event>() {
 871                        listener(event, phase, cx)
 872                    }
 873                }
 874            })
 875            .map(|handler| handler as _);
 876        self.window.next_frame.dispatch_tree.on_key_event(listener);
 877    }
 878
 879    /// Register an action listener on the window for the next frame. The type of action
 880    /// is determined by the first parameter of the given listener. When the next frame is rendered
 881    /// the listener will be cleared.
 882    ///
 883    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
 884    /// a specific need to register a global listener.
 885    pub fn on_action(
 886        &mut self,
 887        action_type: TypeId,
 888        listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
 889    ) {
 890        let listener = self
 891            .window
 892            .frame_arena
 893            .alloc(|| listener)
 894            .map(|handler| handler as _);
 895        self.window
 896            .next_frame
 897            .dispatch_tree
 898            .on_action(action_type, listener);
 899    }
 900
 901    pub fn is_action_available(&self, action: &dyn Action) -> bool {
 902        let target = self
 903            .focused()
 904            .and_then(|focused_handle| {
 905                self.window
 906                    .rendered_frame
 907                    .dispatch_tree
 908                    .focusable_node_id(focused_handle.id)
 909            })
 910            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
 911        self.window
 912            .rendered_frame
 913            .dispatch_tree
 914            .is_action_available(action, target)
 915    }
 916
 917    /// The position of the mouse relative to the window.
 918    pub fn mouse_position(&self) -> Point<Pixels> {
 919        self.window.mouse_position
 920    }
 921
 922    /// The current state of the keyboard's modifiers
 923    pub fn modifiers(&self) -> Modifiers {
 924        self.window.modifiers
 925    }
 926
 927    pub fn set_cursor_style(&mut self, style: CursorStyle) {
 928        self.window.requested_cursor_style = Some(style)
 929    }
 930
 931    /// Called during painting to invoke the given closure in a new stacking context. The given
 932    /// z-index is interpreted relative to the previous call to `stack`.
 933    pub fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
 934        self.window.next_frame.z_index_stack.push(z_index);
 935        let result = f(self);
 936        self.window.next_frame.z_index_stack.pop();
 937        result
 938    }
 939
 940    /// Called during painting to track which z-index is on top at each pixel position
 941    pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
 942        let stacking_order = self.window.next_frame.z_index_stack.clone();
 943        let depth_map = &mut self.window.next_frame.depth_map;
 944        match depth_map.binary_search_by(|(level, _)| stacking_order.cmp(&level)) {
 945            Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, bounds)),
 946        }
 947    }
 948
 949    /// Returns true if there is no opaque layer containing the given point
 950    /// on top of the given level. Layers whose level is an extension of the
 951    /// level are not considered to be on top of the level.
 952    pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
 953        for (opaque_level, bounds) in self.window.rendered_frame.depth_map.iter() {
 954            if level >= opaque_level {
 955                break;
 956            }
 957
 958            if bounds.contains(point) && !opaque_level.starts_with(level) {
 959                return false;
 960            }
 961        }
 962        true
 963    }
 964
 965    pub fn was_top_layer_under_active_drag(
 966        &self,
 967        point: &Point<Pixels>,
 968        level: &StackingOrder,
 969    ) -> bool {
 970        for (opaque_level, bounds) in self.window.rendered_frame.depth_map.iter() {
 971            if level >= opaque_level {
 972                break;
 973            }
 974            if opaque_level.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
 975                continue;
 976            }
 977
 978            if bounds.contains(point) && !opaque_level.starts_with(level) {
 979                return false;
 980            }
 981        }
 982        true
 983    }
 984
 985    /// Called during painting to get the current stacking order.
 986    pub fn stacking_order(&self) -> &StackingOrder {
 987        &self.window.next_frame.z_index_stack
 988    }
 989
 990    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
 991    pub fn paint_shadows(
 992        &mut self,
 993        bounds: Bounds<Pixels>,
 994        corner_radii: Corners<Pixels>,
 995        shadows: &[BoxShadow],
 996    ) {
 997        let scale_factor = self.scale_factor();
 998        let content_mask = self.content_mask();
 999        let window = &mut *self.window;
1000        for shadow in shadows {
1001            let mut shadow_bounds = bounds;
1002            shadow_bounds.origin += shadow.offset;
1003            shadow_bounds.dilate(shadow.spread_radius);
1004            window.next_frame.scene_builder.insert(
1005                &window.next_frame.z_index_stack,
1006                Shadow {
1007                    order: 0,
1008                    bounds: shadow_bounds.scale(scale_factor),
1009                    content_mask: content_mask.scale(scale_factor),
1010                    corner_radii: corner_radii.scale(scale_factor),
1011                    color: shadow.color,
1012                    blur_radius: shadow.blur_radius.scale(scale_factor),
1013                },
1014            );
1015        }
1016    }
1017
1018    /// Paint one or more quads into the scene for the next frame at the current stacking context.
1019    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
1020    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
1021    pub fn paint_quad(&mut self, quad: PaintQuad) {
1022        let scale_factor = self.scale_factor();
1023        let content_mask = self.content_mask();
1024
1025        let window = &mut *self.window;
1026        window.next_frame.scene_builder.insert(
1027            &window.next_frame.z_index_stack,
1028            Quad {
1029                order: 0,
1030                bounds: quad.bounds.scale(scale_factor),
1031                content_mask: content_mask.scale(scale_factor),
1032                background: quad.background,
1033                border_color: quad.border_color,
1034                corner_radii: quad.corner_radii.scale(scale_factor),
1035                border_widths: quad.border_widths.scale(scale_factor),
1036            },
1037        );
1038    }
1039
1040    /// Paint the given `Path` into the scene for the next frame at the current z-index.
1041    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
1042        let scale_factor = self.scale_factor();
1043        let content_mask = self.content_mask();
1044        path.content_mask = content_mask;
1045        path.color = color.into();
1046        let window = &mut *self.window;
1047        window
1048            .next_frame
1049            .scene_builder
1050            .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1051    }
1052
1053    /// Paint an underline into the scene for the next frame at the current z-index.
1054    pub fn paint_underline(
1055        &mut self,
1056        origin: Point<Pixels>,
1057        width: Pixels,
1058        style: &UnderlineStyle,
1059    ) {
1060        let scale_factor = self.scale_factor();
1061        let height = if style.wavy {
1062            style.thickness * 3.
1063        } else {
1064            style.thickness
1065        };
1066        let bounds = Bounds {
1067            origin,
1068            size: size(width, height),
1069        };
1070        let content_mask = self.content_mask();
1071        let window = &mut *self.window;
1072        window.next_frame.scene_builder.insert(
1073            &window.next_frame.z_index_stack,
1074            Underline {
1075                order: 0,
1076                bounds: bounds.scale(scale_factor),
1077                content_mask: content_mask.scale(scale_factor),
1078                thickness: style.thickness.scale(scale_factor),
1079                color: style.color.unwrap_or_default(),
1080                wavy: style.wavy,
1081            },
1082        );
1083    }
1084
1085    /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1086    /// The y component of the origin is the baseline of the glyph.
1087    pub fn paint_glyph(
1088        &mut self,
1089        origin: Point<Pixels>,
1090        font_id: FontId,
1091        glyph_id: GlyphId,
1092        font_size: Pixels,
1093        color: Hsla,
1094    ) -> Result<()> {
1095        let scale_factor = self.scale_factor();
1096        let glyph_origin = origin.scale(scale_factor);
1097        let subpixel_variant = Point {
1098            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1099            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1100        };
1101        let params = RenderGlyphParams {
1102            font_id,
1103            glyph_id,
1104            font_size,
1105            subpixel_variant,
1106            scale_factor,
1107            is_emoji: false,
1108        };
1109
1110        let raster_bounds = self.text_system().raster_bounds(&params)?;
1111        if !raster_bounds.is_zero() {
1112            let tile =
1113                self.window
1114                    .sprite_atlas
1115                    .get_or_insert_with(&params.clone().into(), &mut || {
1116                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1117                        Ok((size, Cow::Owned(bytes)))
1118                    })?;
1119            let bounds = Bounds {
1120                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1121                size: tile.bounds.size.map(Into::into),
1122            };
1123            let content_mask = self.content_mask().scale(scale_factor);
1124            let window = &mut *self.window;
1125            window.next_frame.scene_builder.insert(
1126                &window.next_frame.z_index_stack,
1127                MonochromeSprite {
1128                    order: 0,
1129                    bounds,
1130                    content_mask,
1131                    color,
1132                    tile,
1133                },
1134            );
1135        }
1136        Ok(())
1137    }
1138
1139    /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1140    /// The y component of the origin is the baseline of the glyph.
1141    pub fn paint_emoji(
1142        &mut self,
1143        origin: Point<Pixels>,
1144        font_id: FontId,
1145        glyph_id: GlyphId,
1146        font_size: Pixels,
1147    ) -> Result<()> {
1148        let scale_factor = self.scale_factor();
1149        let glyph_origin = origin.scale(scale_factor);
1150        let params = RenderGlyphParams {
1151            font_id,
1152            glyph_id,
1153            font_size,
1154            // We don't render emojis with subpixel variants.
1155            subpixel_variant: Default::default(),
1156            scale_factor,
1157            is_emoji: true,
1158        };
1159
1160        let raster_bounds = self.text_system().raster_bounds(&params)?;
1161        if !raster_bounds.is_zero() {
1162            let tile =
1163                self.window
1164                    .sprite_atlas
1165                    .get_or_insert_with(&params.clone().into(), &mut || {
1166                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
1167                        Ok((size, Cow::Owned(bytes)))
1168                    })?;
1169            let bounds = Bounds {
1170                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1171                size: tile.bounds.size.map(Into::into),
1172            };
1173            let content_mask = self.content_mask().scale(scale_factor);
1174            let window = &mut *self.window;
1175
1176            window.next_frame.scene_builder.insert(
1177                &window.next_frame.z_index_stack,
1178                PolychromeSprite {
1179                    order: 0,
1180                    bounds,
1181                    corner_radii: Default::default(),
1182                    content_mask,
1183                    tile,
1184                    grayscale: false,
1185                },
1186            );
1187        }
1188        Ok(())
1189    }
1190
1191    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1192    pub fn paint_svg(
1193        &mut self,
1194        bounds: Bounds<Pixels>,
1195        path: SharedString,
1196        color: Hsla,
1197    ) -> Result<()> {
1198        let scale_factor = self.scale_factor();
1199        let bounds = bounds.scale(scale_factor);
1200        // Render the SVG at twice the size to get a higher quality result.
1201        let params = RenderSvgParams {
1202            path,
1203            size: bounds
1204                .size
1205                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1206        };
1207
1208        let tile =
1209            self.window
1210                .sprite_atlas
1211                .get_or_insert_with(&params.clone().into(), &mut || {
1212                    let bytes = self.svg_renderer.render(&params)?;
1213                    Ok((params.size, Cow::Owned(bytes)))
1214                })?;
1215        let content_mask = self.content_mask().scale(scale_factor);
1216
1217        let window = &mut *self.window;
1218        window.next_frame.scene_builder.insert(
1219            &window.next_frame.z_index_stack,
1220            MonochromeSprite {
1221                order: 0,
1222                bounds,
1223                content_mask,
1224                color,
1225                tile,
1226            },
1227        );
1228
1229        Ok(())
1230    }
1231
1232    /// Paint an image into the scene for the next frame at the current z-index.
1233    pub fn paint_image(
1234        &mut self,
1235        bounds: Bounds<Pixels>,
1236        corner_radii: Corners<Pixels>,
1237        data: Arc<ImageData>,
1238        grayscale: bool,
1239    ) -> Result<()> {
1240        let scale_factor = self.scale_factor();
1241        let bounds = bounds.scale(scale_factor);
1242        let params = RenderImageParams { image_id: data.id };
1243
1244        let tile = self
1245            .window
1246            .sprite_atlas
1247            .get_or_insert_with(&params.clone().into(), &mut || {
1248                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1249            })?;
1250        let content_mask = self.content_mask().scale(scale_factor);
1251        let corner_radii = corner_radii.scale(scale_factor);
1252
1253        let window = &mut *self.window;
1254        window.next_frame.scene_builder.insert(
1255            &window.next_frame.z_index_stack,
1256            PolychromeSprite {
1257                order: 0,
1258                bounds,
1259                content_mask,
1260                corner_radii,
1261                tile,
1262                grayscale,
1263            },
1264        );
1265        Ok(())
1266    }
1267
1268    /// Paint a surface into the scene for the next frame at the current z-index.
1269    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1270        let scale_factor = self.scale_factor();
1271        let bounds = bounds.scale(scale_factor);
1272        let content_mask = self.content_mask().scale(scale_factor);
1273        let window = &mut *self.window;
1274        window.next_frame.scene_builder.insert(
1275            &window.next_frame.z_index_stack,
1276            Surface {
1277                order: 0,
1278                bounds,
1279                content_mask,
1280                image_buffer,
1281            },
1282        );
1283    }
1284
1285    /// Draw pixels to the display for this window based on the contents of its scene.
1286    pub(crate) fn draw(&mut self) -> Scene {
1287        self.window.dirty = false;
1288        self.window.drawing = true;
1289
1290        #[cfg(any(test, feature = "test-support"))]
1291        {
1292            self.window.focus_invalidated = false;
1293        }
1294
1295        self.text_system().start_frame();
1296        self.window.platform_window.clear_input_handler();
1297        self.window.layout_engine.as_mut().unwrap().clear();
1298        self.window.next_frame.clear();
1299        self.window.frame_arena.clear();
1300        let root_view = self.window.root_view.take().unwrap();
1301
1302        self.with_z_index(0, |cx| {
1303            cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1304                for (action_type, action_listeners) in &cx.app.global_action_listeners {
1305                    for action_listener in action_listeners.iter().cloned() {
1306                        let listener = cx
1307                            .window
1308                            .frame_arena
1309                            .alloc(|| {
1310                                move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
1311                                    action_listener(action, phase, cx)
1312                                }
1313                            })
1314                            .map(|listener| listener as _);
1315                        cx.window
1316                            .next_frame
1317                            .dispatch_tree
1318                            .on_action(*action_type, listener)
1319                    }
1320                }
1321
1322                let available_space = cx.window.viewport_size.map(Into::into);
1323                root_view.draw(Point::default(), available_space, cx);
1324            })
1325        });
1326
1327        if let Some(active_drag) = self.app.active_drag.take() {
1328            self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1329                let offset = cx.mouse_position() - active_drag.cursor_offset;
1330                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1331                active_drag.view.draw(offset, available_space, cx);
1332            });
1333            self.active_drag = Some(active_drag);
1334        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1335            self.with_z_index(1, |cx| {
1336                let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1337                active_tooltip
1338                    .view
1339                    .draw(active_tooltip.cursor_offset, available_space, cx);
1340            });
1341        }
1342
1343        self.window
1344            .next_frame
1345            .dispatch_tree
1346            .preserve_pending_keystrokes(
1347                &mut self.window.rendered_frame.dispatch_tree,
1348                self.window.focus,
1349            );
1350        self.window.next_frame.focus = self.window.focus;
1351        self.window.root_view = Some(root_view);
1352
1353        let previous_focus_path = self.window.rendered_frame.focus_path();
1354        mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1355        let current_focus_path = self.window.rendered_frame.focus_path();
1356
1357        if previous_focus_path != current_focus_path {
1358            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1359                self.window
1360                    .blur_listeners
1361                    .clone()
1362                    .retain(&(), |listener| listener(self));
1363            }
1364
1365            let event = FocusEvent {
1366                previous_focus_path,
1367                current_focus_path,
1368            };
1369            self.window
1370                .focus_listeners
1371                .clone()
1372                .retain(&(), |listener| listener(&event, self));
1373        }
1374
1375        let scene = self.window.rendered_frame.scene_builder.build();
1376
1377        // Set the cursor only if we're the active window.
1378        let cursor_style = self
1379            .window
1380            .requested_cursor_style
1381            .take()
1382            .unwrap_or(CursorStyle::Arrow);
1383        if self.is_window_active() {
1384            self.platform.set_cursor_style(cursor_style);
1385        }
1386
1387        self.window.drawing = false;
1388        ELEMENT_ARENA.with_borrow_mut(|element_arena| element_arena.clear());
1389
1390        scene
1391    }
1392
1393    /// Dispatch a mouse or keyboard event on the window.
1394    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1395        // Handlers may set this to false by calling `stop_propagation`.
1396        self.app.propagate_event = true;
1397        // Handlers may set this to true by calling `prevent_default`.
1398        self.window.default_prevented = false;
1399
1400        let event = match event {
1401            // Track the mouse position with our own state, since accessing the platform
1402            // API for the mouse position can only occur on the main thread.
1403            InputEvent::MouseMove(mouse_move) => {
1404                self.window.mouse_position = mouse_move.position;
1405                self.window.modifiers = mouse_move.modifiers;
1406                InputEvent::MouseMove(mouse_move)
1407            }
1408            InputEvent::MouseDown(mouse_down) => {
1409                self.window.mouse_position = mouse_down.position;
1410                self.window.modifiers = mouse_down.modifiers;
1411                InputEvent::MouseDown(mouse_down)
1412            }
1413            InputEvent::MouseUp(mouse_up) => {
1414                self.window.mouse_position = mouse_up.position;
1415                self.window.modifiers = mouse_up.modifiers;
1416                InputEvent::MouseUp(mouse_up)
1417            }
1418            InputEvent::MouseExited(mouse_exited) => {
1419                // todo!("Should we record that the mouse is outside of the window somehow? Or are these global pixels?")
1420                self.window.modifiers = mouse_exited.modifiers;
1421
1422                InputEvent::MouseExited(mouse_exited)
1423            }
1424            InputEvent::ModifiersChanged(modifiers_changed) => {
1425                self.window.modifiers = modifiers_changed.modifiers;
1426                InputEvent::ModifiersChanged(modifiers_changed)
1427            }
1428            InputEvent::ScrollWheel(scroll_wheel) => {
1429                self.window.mouse_position = scroll_wheel.position;
1430                self.window.modifiers = scroll_wheel.modifiers;
1431                InputEvent::ScrollWheel(scroll_wheel)
1432            }
1433            // Translate dragging and dropping of external files from the operating system
1434            // to internal drag and drop events.
1435            InputEvent::FileDrop(file_drop) => match file_drop {
1436                FileDropEvent::Entered { position, files } => {
1437                    self.window.mouse_position = position;
1438                    if self.active_drag.is_none() {
1439                        self.active_drag = Some(AnyDrag {
1440                            value: Box::new(files.clone()),
1441                            view: self.build_view(|_| files).into(),
1442                            cursor_offset: position,
1443                        });
1444                    }
1445                    InputEvent::MouseMove(MouseMoveEvent {
1446                        position,
1447                        pressed_button: Some(MouseButton::Left),
1448                        modifiers: Modifiers::default(),
1449                    })
1450                }
1451                FileDropEvent::Pending { position } => {
1452                    self.window.mouse_position = position;
1453                    InputEvent::MouseMove(MouseMoveEvent {
1454                        position,
1455                        pressed_button: Some(MouseButton::Left),
1456                        modifiers: Modifiers::default(),
1457                    })
1458                }
1459                FileDropEvent::Submit { position } => {
1460                    self.activate(true);
1461                    self.window.mouse_position = position;
1462                    InputEvent::MouseUp(MouseUpEvent {
1463                        button: MouseButton::Left,
1464                        position,
1465                        modifiers: Modifiers::default(),
1466                        click_count: 1,
1467                    })
1468                }
1469                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1470                    button: MouseButton::Left,
1471                    position: Point::default(),
1472                    modifiers: Modifiers::default(),
1473                    click_count: 1,
1474                }),
1475            },
1476            InputEvent::KeyDown(_) | InputEvent::KeyUp(_) => event,
1477        };
1478
1479        if let Some(any_mouse_event) = event.mouse_event() {
1480            self.dispatch_mouse_event(any_mouse_event);
1481        } else if let Some(any_key_event) = event.keyboard_event() {
1482            self.dispatch_key_event(any_key_event);
1483        }
1484
1485        !self.app.propagate_event
1486    }
1487
1488    fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1489        if let Some(mut handlers) = self
1490            .window
1491            .rendered_frame
1492            .mouse_listeners
1493            .remove(&event.type_id())
1494        {
1495            // Because handlers may add other handlers, we sort every time.
1496            handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1497
1498            // Capture phase, events bubble from back to front. Handlers for this phase are used for
1499            // special purposes, such as detecting events outside of a given Bounds.
1500            for (_, handler) in &mut handlers {
1501                handler(event, DispatchPhase::Capture, self);
1502                if !self.app.propagate_event {
1503                    break;
1504                }
1505            }
1506
1507            // Bubble phase, where most normal handlers do their work.
1508            if self.app.propagate_event {
1509                for (_, handler) in handlers.iter_mut().rev() {
1510                    handler(event, DispatchPhase::Bubble, self);
1511                    if !self.app.propagate_event {
1512                        break;
1513                    }
1514                }
1515            }
1516
1517            if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1518                self.active_drag = None;
1519            }
1520
1521            self.window
1522                .rendered_frame
1523                .mouse_listeners
1524                .insert(event.type_id(), handlers);
1525        }
1526    }
1527
1528    fn dispatch_key_event(&mut self, event: &dyn Any) {
1529        let node_id = self
1530            .window
1531            .focus
1532            .and_then(|focus_id| {
1533                self.window
1534                    .rendered_frame
1535                    .dispatch_tree
1536                    .focusable_node_id(focus_id)
1537            })
1538            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1539
1540        let dispatch_path = self
1541            .window
1542            .rendered_frame
1543            .dispatch_tree
1544            .dispatch_path(node_id);
1545
1546        let mut actions: Vec<Box<dyn Action>> = Vec::new();
1547
1548        // Capture phase
1549        let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1550        self.propagate_event = true;
1551
1552        for node_id in &dispatch_path {
1553            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1554
1555            if let Some(context) = node.context.clone() {
1556                context_stack.push(context);
1557            }
1558
1559            for key_listener in node.key_listeners.clone() {
1560                key_listener(event, DispatchPhase::Capture, self);
1561                if !self.propagate_event {
1562                    return;
1563                }
1564            }
1565        }
1566
1567        // Bubble phase
1568        for node_id in dispatch_path.iter().rev() {
1569            // Handle low level key events
1570            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1571            for key_listener in node.key_listeners.clone() {
1572                key_listener(event, DispatchPhase::Bubble, self);
1573                if !self.propagate_event {
1574                    return;
1575                }
1576            }
1577
1578            // Match keystrokes
1579            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1580            if node.context.is_some() {
1581                if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1582                    let mut new_actions = self
1583                        .window
1584                        .rendered_frame
1585                        .dispatch_tree
1586                        .dispatch_key(&key_down_event.keystroke, &context_stack);
1587                    actions.append(&mut new_actions);
1588                }
1589
1590                context_stack.pop();
1591            }
1592        }
1593
1594        for action in actions {
1595            self.dispatch_action_on_node(node_id, action.boxed_clone());
1596            if !self.propagate_event {
1597                self.dispatch_keystroke_observers(event, Some(action));
1598                return;
1599            }
1600        }
1601        self.dispatch_keystroke_observers(event, None);
1602    }
1603
1604    pub fn has_pending_keystrokes(&self) -> bool {
1605        self.window
1606            .rendered_frame
1607            .dispatch_tree
1608            .has_pending_keystrokes()
1609    }
1610
1611    fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1612        let dispatch_path = self
1613            .window
1614            .rendered_frame
1615            .dispatch_tree
1616            .dispatch_path(node_id);
1617
1618        // Capture phase
1619        for node_id in &dispatch_path {
1620            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1621            for DispatchActionListener {
1622                action_type,
1623                listener,
1624            } in node.action_listeners.clone()
1625            {
1626                let any_action = action.as_any();
1627                if action_type == any_action.type_id() {
1628                    listener(any_action, DispatchPhase::Capture, self);
1629                    if !self.propagate_event {
1630                        return;
1631                    }
1632                }
1633            }
1634        }
1635        // Bubble phase
1636        for node_id in dispatch_path.iter().rev() {
1637            let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1638            for DispatchActionListener {
1639                action_type,
1640                listener,
1641            } in node.action_listeners.clone()
1642            {
1643                let any_action = action.as_any();
1644                if action_type == any_action.type_id() {
1645                    self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1646                    listener(any_action, DispatchPhase::Bubble, self);
1647                    if !self.propagate_event {
1648                        return;
1649                    }
1650                }
1651            }
1652        }
1653    }
1654
1655    /// Register the given handler to be invoked whenever the global of the given type
1656    /// is updated.
1657    pub fn observe_global<G: 'static>(
1658        &mut self,
1659        f: impl Fn(&mut WindowContext<'_>) + 'static,
1660    ) -> Subscription {
1661        let window_handle = self.window.handle;
1662        let (subscription, activate) = self.global_observers.insert(
1663            TypeId::of::<G>(),
1664            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1665        );
1666        self.app.defer(move |_| activate());
1667        subscription
1668    }
1669
1670    pub fn activate_window(&self) {
1671        self.window.platform_window.activate();
1672    }
1673
1674    pub fn minimize_window(&self) {
1675        self.window.platform_window.minimize();
1676    }
1677
1678    pub fn toggle_full_screen(&self) {
1679        self.window.platform_window.toggle_full_screen();
1680    }
1681
1682    pub fn prompt(
1683        &self,
1684        level: PromptLevel,
1685        msg: &str,
1686        answers: &[&str],
1687    ) -> oneshot::Receiver<usize> {
1688        self.window.platform_window.prompt(level, msg, answers)
1689    }
1690
1691    pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1692        let node_id = self
1693            .window
1694            .focus
1695            .and_then(|focus_id| {
1696                self.window
1697                    .rendered_frame
1698                    .dispatch_tree
1699                    .focusable_node_id(focus_id)
1700            })
1701            .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1702
1703        self.window
1704            .rendered_frame
1705            .dispatch_tree
1706            .available_actions(node_id)
1707    }
1708
1709    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1710        self.window
1711            .rendered_frame
1712            .dispatch_tree
1713            .bindings_for_action(
1714                action,
1715                &self.window.rendered_frame.dispatch_tree.context_stack,
1716            )
1717    }
1718
1719    pub fn bindings_for_action_in(
1720        &self,
1721        action: &dyn Action,
1722        focus_handle: &FocusHandle,
1723    ) -> Vec<KeyBinding> {
1724        let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1725
1726        let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1727            return vec![];
1728        };
1729        let context_stack = dispatch_tree
1730            .dispatch_path(node_id)
1731            .into_iter()
1732            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1733            .collect();
1734        dispatch_tree.bindings_for_action(action, &context_stack)
1735    }
1736
1737    pub fn listener_for<V: Render, E>(
1738        &self,
1739        view: &View<V>,
1740        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1741    ) -> impl Fn(&E, &mut WindowContext) + 'static {
1742        let view = view.downgrade();
1743        move |e: &E, cx: &mut WindowContext| {
1744            view.update(cx, |view, cx| f(view, e, cx)).ok();
1745        }
1746    }
1747
1748    pub fn handler_for<V: Render>(
1749        &self,
1750        view: &View<V>,
1751        f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1752    ) -> impl Fn(&mut WindowContext) {
1753        let view = view.downgrade();
1754        move |cx: &mut WindowContext| {
1755            view.update(cx, |view, cx| f(view, cx)).ok();
1756        }
1757    }
1758
1759    //========== ELEMENT RELATED FUNCTIONS ===========
1760    pub fn with_key_dispatch<R>(
1761        &mut self,
1762        context: Option<KeyContext>,
1763        focus_handle: Option<FocusHandle>,
1764        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1765    ) -> R {
1766        let window = &mut self.window;
1767        window.next_frame.dispatch_tree.push_node(context.clone());
1768        if let Some(focus_handle) = focus_handle.as_ref() {
1769            window
1770                .next_frame
1771                .dispatch_tree
1772                .make_focusable(focus_handle.id);
1773        }
1774        let result = f(focus_handle, self);
1775
1776        self.window.next_frame.dispatch_tree.pop_node();
1777
1778        result
1779    }
1780
1781    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1782    /// platform to receive textual input with proper integration with concerns such
1783    /// as IME interactions.
1784    pub fn handle_input(
1785        &mut self,
1786        focus_handle: &FocusHandle,
1787        input_handler: impl PlatformInputHandler,
1788    ) {
1789        if focus_handle.is_focused(self) {
1790            self.window
1791                .platform_window
1792                .set_input_handler(Box::new(input_handler));
1793        }
1794    }
1795
1796    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1797        let mut this = self.to_async();
1798        self.window
1799            .platform_window
1800            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1801    }
1802}
1803
1804impl Context for WindowContext<'_> {
1805    type Result<T> = T;
1806
1807    fn build_model<T>(
1808        &mut self,
1809        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1810    ) -> Model<T>
1811    where
1812        T: 'static,
1813    {
1814        let slot = self.app.entities.reserve();
1815        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1816        self.entities.insert(slot, model)
1817    }
1818
1819    fn update_model<T: 'static, R>(
1820        &mut self,
1821        model: &Model<T>,
1822        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1823    ) -> R {
1824        let mut entity = self.entities.lease(model);
1825        let result = update(
1826            &mut *entity,
1827            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1828        );
1829        self.entities.end_lease(entity);
1830        result
1831    }
1832
1833    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1834    where
1835        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1836    {
1837        if window == self.window.handle {
1838            let root_view = self.window.root_view.clone().unwrap();
1839            Ok(update(root_view, self))
1840        } else {
1841            window.update(self.app, update)
1842        }
1843    }
1844
1845    fn read_model<T, R>(
1846        &self,
1847        handle: &Model<T>,
1848        read: impl FnOnce(&T, &AppContext) -> R,
1849    ) -> Self::Result<R>
1850    where
1851        T: 'static,
1852    {
1853        let entity = self.entities.read(handle);
1854        read(&*entity, &*self.app)
1855    }
1856
1857    fn read_window<T, R>(
1858        &self,
1859        window: &WindowHandle<T>,
1860        read: impl FnOnce(View<T>, &AppContext) -> R,
1861    ) -> Result<R>
1862    where
1863        T: 'static,
1864    {
1865        if window.any_handle == self.window.handle {
1866            let root_view = self
1867                .window
1868                .root_view
1869                .clone()
1870                .unwrap()
1871                .downcast::<T>()
1872                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1873            Ok(read(root_view, self))
1874        } else {
1875            self.app.read_window(window, read)
1876        }
1877    }
1878}
1879
1880impl VisualContext for WindowContext<'_> {
1881    fn build_view<V>(
1882        &mut self,
1883        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1884    ) -> Self::Result<View<V>>
1885    where
1886        V: 'static + Render,
1887    {
1888        let slot = self.app.entities.reserve();
1889        let view = View {
1890            model: slot.clone(),
1891        };
1892        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1893        let entity = build_view_state(&mut cx);
1894        cx.entities.insert(slot, entity);
1895
1896        cx.new_view_observers
1897            .clone()
1898            .retain(&TypeId::of::<V>(), |observer| {
1899                let any_view = AnyView::from(view.clone());
1900                (observer)(any_view, self);
1901                true
1902            });
1903
1904        view
1905    }
1906
1907    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1908    fn update_view<T: 'static, R>(
1909        &mut self,
1910        view: &View<T>,
1911        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1912    ) -> Self::Result<R> {
1913        let mut lease = self.app.entities.lease(&view.model);
1914        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1915        let result = update(&mut *lease, &mut cx);
1916        cx.app.entities.end_lease(lease);
1917        result
1918    }
1919
1920    fn replace_root_view<V>(
1921        &mut self,
1922        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1923    ) -> Self::Result<View<V>>
1924    where
1925        V: 'static + Render,
1926    {
1927        let slot = self.app.entities.reserve();
1928        let view = View {
1929            model: slot.clone(),
1930        };
1931        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1932        let entity = build_view(&mut cx);
1933        self.entities.insert(slot, entity);
1934        self.window.root_view = Some(view.clone().into());
1935        view
1936    }
1937
1938    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1939        self.update_view(view, |view, cx| {
1940            view.focus_handle(cx).clone().focus(cx);
1941        })
1942    }
1943
1944    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1945    where
1946        V: ManagedView,
1947    {
1948        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1949    }
1950}
1951
1952impl<'a> std::ops::Deref for WindowContext<'a> {
1953    type Target = AppContext;
1954
1955    fn deref(&self) -> &Self::Target {
1956        &self.app
1957    }
1958}
1959
1960impl<'a> std::ops::DerefMut for WindowContext<'a> {
1961    fn deref_mut(&mut self) -> &mut Self::Target {
1962        &mut self.app
1963    }
1964}
1965
1966impl<'a> Borrow<AppContext> for WindowContext<'a> {
1967    fn borrow(&self) -> &AppContext {
1968        &self.app
1969    }
1970}
1971
1972impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1973    fn borrow_mut(&mut self) -> &mut AppContext {
1974        &mut self.app
1975    }
1976}
1977
1978pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1979    fn app_mut(&mut self) -> &mut AppContext {
1980        self.borrow_mut()
1981    }
1982
1983    fn app(&self) -> &AppContext {
1984        self.borrow()
1985    }
1986
1987    fn window(&self) -> &Window {
1988        self.borrow()
1989    }
1990
1991    fn window_mut(&mut self) -> &mut Window {
1992        self.borrow_mut()
1993    }
1994
1995    /// Pushes the given element id onto the global stack and invokes the given closure
1996    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1997    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1998    /// used to associate state with identified elements across separate frames.
1999    fn with_element_id<R>(
2000        &mut self,
2001        id: Option<impl Into<ElementId>>,
2002        f: impl FnOnce(&mut Self) -> R,
2003    ) -> R {
2004        if let Some(id) = id.map(Into::into) {
2005            let window = self.window_mut();
2006            window.element_id_stack.push(id.into());
2007            let result = f(self);
2008            let window: &mut Window = self.borrow_mut();
2009            window.element_id_stack.pop();
2010            result
2011        } else {
2012            f(self)
2013        }
2014    }
2015
2016    /// Invoke the given function with the given content mask after intersecting it
2017    /// with the current mask.
2018    fn with_content_mask<R>(
2019        &mut self,
2020        mask: Option<ContentMask<Pixels>>,
2021        f: impl FnOnce(&mut Self) -> R,
2022    ) -> R {
2023        if let Some(mask) = mask {
2024            let mask = mask.intersect(&self.content_mask());
2025            self.window_mut().next_frame.content_mask_stack.push(mask);
2026            let result = f(self);
2027            self.window_mut().next_frame.content_mask_stack.pop();
2028            result
2029        } else {
2030            f(self)
2031        }
2032    }
2033
2034    /// Invoke the given function with the content mask reset to that
2035    /// of the window.
2036    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2037        let mask = ContentMask {
2038            bounds: Bounds {
2039                origin: Point::default(),
2040                size: self.window().viewport_size,
2041            },
2042        };
2043        self.window_mut().next_frame.content_mask_stack.push(mask);
2044        let result = f(self);
2045        self.window_mut().next_frame.content_mask_stack.pop();
2046        result
2047    }
2048
2049    /// Update the global element offset relative to the current offset. This is used to implement
2050    /// scrolling.
2051    fn with_element_offset<R>(
2052        &mut self,
2053        offset: Point<Pixels>,
2054        f: impl FnOnce(&mut Self) -> R,
2055    ) -> R {
2056        if offset.is_zero() {
2057            return f(self);
2058        };
2059
2060        let abs_offset = self.element_offset() + offset;
2061        self.with_absolute_element_offset(abs_offset, f)
2062    }
2063
2064    /// Update the global element offset based on the given offset. This is used to implement
2065    /// drag handles and other manual painting of elements.
2066    fn with_absolute_element_offset<R>(
2067        &mut self,
2068        offset: Point<Pixels>,
2069        f: impl FnOnce(&mut Self) -> R,
2070    ) -> R {
2071        self.window_mut()
2072            .next_frame
2073            .element_offset_stack
2074            .push(offset);
2075        let result = f(self);
2076        self.window_mut().next_frame.element_offset_stack.pop();
2077        result
2078    }
2079
2080    /// Obtain the current element offset.
2081    fn element_offset(&self) -> Point<Pixels> {
2082        self.window()
2083            .next_frame
2084            .element_offset_stack
2085            .last()
2086            .copied()
2087            .unwrap_or_default()
2088    }
2089
2090    /// Update or initialize state for an element with the given id that lives across multiple
2091    /// frames. If an element with this id existed in the rendered frame, its state will be passed
2092    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2093    /// when drawing the next frame.
2094    fn with_element_state<S, R>(
2095        &mut self,
2096        id: ElementId,
2097        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2098    ) -> R
2099    where
2100        S: 'static,
2101    {
2102        self.with_element_id(Some(id), |cx| {
2103            let global_id = cx.window().element_id_stack.clone();
2104
2105            if let Some(any) = cx
2106                .window_mut()
2107                .next_frame
2108                .element_states
2109                .remove(&global_id)
2110                .or_else(|| {
2111                    cx.window_mut()
2112                        .rendered_frame
2113                        .element_states
2114                        .remove(&global_id)
2115                })
2116            {
2117                let ElementStateBox {
2118                    inner,
2119
2120                    #[cfg(debug_assertions)]
2121                    type_name
2122                } = any;
2123                // Using the extra inner option to avoid needing to reallocate a new box.
2124                let mut state_box = inner
2125                    .downcast::<Option<S>>()
2126                    .map_err(|_| {
2127                        #[cfg(debug_assertions)]
2128                        {
2129                            anyhow!(
2130                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2131                                std::any::type_name::<S>(),
2132                                type_name
2133                            )
2134                        }
2135
2136                        #[cfg(not(debug_assertions))]
2137                        {
2138                            anyhow!(
2139                                "invalid element state type for id, requested_type {:?}",
2140                                std::any::type_name::<S>(),
2141                            )
2142                        }
2143                    })
2144                    .unwrap();
2145
2146                // Actual: Option<AnyElement> <- View
2147                // Requested: () <- AnyElemet
2148                let state = state_box
2149                    .take()
2150                    .expect("element state is already on the stack");
2151                let (result, state) = f(Some(state), cx);
2152                state_box.replace(state);
2153                cx.window_mut()
2154                    .next_frame
2155                    .element_states
2156                    .insert(global_id, ElementStateBox {
2157                        inner: state_box,
2158
2159                        #[cfg(debug_assertions)]
2160                        type_name
2161                    });
2162                result
2163            } else {
2164                let (result, state) = f(None, cx);
2165                cx.window_mut()
2166                    .next_frame
2167                    .element_states
2168                    .insert(global_id,
2169                        ElementStateBox {
2170                            inner: Box::new(Some(state)),
2171
2172                            #[cfg(debug_assertions)]
2173                            type_name: std::any::type_name::<S>()
2174                        }
2175
2176                    );
2177                result
2178            }
2179        })
2180    }
2181
2182    /// Obtain the current content mask.
2183    fn content_mask(&self) -> ContentMask<Pixels> {
2184        self.window()
2185            .next_frame
2186            .content_mask_stack
2187            .last()
2188            .cloned()
2189            .unwrap_or_else(|| ContentMask {
2190                bounds: Bounds {
2191                    origin: Point::default(),
2192                    size: self.window().viewport_size,
2193                },
2194            })
2195    }
2196
2197    /// The size of an em for the base font of the application. Adjusting this value allows the
2198    /// UI to scale, just like zooming a web page.
2199    fn rem_size(&self) -> Pixels {
2200        self.window().rem_size
2201    }
2202}
2203
2204impl Borrow<Window> for WindowContext<'_> {
2205    fn borrow(&self) -> &Window {
2206        &self.window
2207    }
2208}
2209
2210impl BorrowMut<Window> for WindowContext<'_> {
2211    fn borrow_mut(&mut self) -> &mut Window {
2212        &mut self.window
2213    }
2214}
2215
2216impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2217
2218pub struct ViewContext<'a, V> {
2219    window_cx: WindowContext<'a>,
2220    view: &'a View<V>,
2221}
2222
2223impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2224    fn borrow(&self) -> &AppContext {
2225        &*self.window_cx.app
2226    }
2227}
2228
2229impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2230    fn borrow_mut(&mut self) -> &mut AppContext {
2231        &mut *self.window_cx.app
2232    }
2233}
2234
2235impl<V> Borrow<Window> for ViewContext<'_, V> {
2236    fn borrow(&self) -> &Window {
2237        &*self.window_cx.window
2238    }
2239}
2240
2241impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2242    fn borrow_mut(&mut self) -> &mut Window {
2243        &mut *self.window_cx.window
2244    }
2245}
2246
2247impl<'a, V: 'static> ViewContext<'a, V> {
2248    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2249        Self {
2250            window_cx: WindowContext::new(app, window),
2251            view,
2252        }
2253    }
2254
2255    pub fn entity_id(&self) -> EntityId {
2256        self.view.entity_id()
2257    }
2258
2259    pub fn view(&self) -> &View<V> {
2260        self.view
2261    }
2262
2263    pub fn model(&self) -> &Model<V> {
2264        &self.view.model
2265    }
2266
2267    /// Access the underlying window context.
2268    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2269        &mut self.window_cx
2270    }
2271
2272    pub fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2273        self.window.next_frame.z_index_stack.push(z_index);
2274        let result = f(self);
2275        self.window.next_frame.z_index_stack.pop();
2276        result
2277    }
2278
2279    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2280    where
2281        V: 'static,
2282    {
2283        let view = self.view().clone();
2284        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2285    }
2286
2287    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2288    /// that are currently on the stack to be returned to the app.
2289    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2290        let view = self.view().downgrade();
2291        self.window_cx.defer(move |cx| {
2292            view.update(cx, f).ok();
2293        });
2294    }
2295
2296    pub fn observe<V2, E>(
2297        &mut self,
2298        entity: &E,
2299        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2300    ) -> Subscription
2301    where
2302        V2: 'static,
2303        V: 'static,
2304        E: Entity<V2>,
2305    {
2306        let view = self.view().downgrade();
2307        let entity_id = entity.entity_id();
2308        let entity = entity.downgrade();
2309        let window_handle = self.window.handle;
2310        let (subscription, activate) = self.app.observers.insert(
2311            entity_id,
2312            Box::new(move |cx| {
2313                window_handle
2314                    .update(cx, |_, cx| {
2315                        if let Some(handle) = E::upgrade_from(&entity) {
2316                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2317                                .is_ok()
2318                        } else {
2319                            false
2320                        }
2321                    })
2322                    .unwrap_or(false)
2323            }),
2324        );
2325        self.app.defer(move |_| activate());
2326        subscription
2327    }
2328
2329    pub fn subscribe<V2, E, Evt>(
2330        &mut self,
2331        entity: &E,
2332        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2333    ) -> Subscription
2334    where
2335        V2: EventEmitter<Evt>,
2336        E: Entity<V2>,
2337        Evt: 'static,
2338    {
2339        let view = self.view().downgrade();
2340        let entity_id = entity.entity_id();
2341        let handle = entity.downgrade();
2342        let window_handle = self.window.handle;
2343        let (subscription, activate) = self.app.event_listeners.insert(
2344            entity_id,
2345            (
2346                TypeId::of::<Evt>(),
2347                Box::new(move |event, cx| {
2348                    window_handle
2349                        .update(cx, |_, cx| {
2350                            if let Some(handle) = E::upgrade_from(&handle) {
2351                                let event = event.downcast_ref().expect("invalid event type");
2352                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2353                                    .is_ok()
2354                            } else {
2355                                false
2356                            }
2357                        })
2358                        .unwrap_or(false)
2359                }),
2360            ),
2361        );
2362        self.app.defer(move |_| activate());
2363        subscription
2364    }
2365
2366    pub fn on_release(
2367        &mut self,
2368        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2369    ) -> Subscription {
2370        let window_handle = self.window.handle;
2371        let (subscription, activate) = self.app.release_listeners.insert(
2372            self.view.model.entity_id,
2373            Box::new(move |this, cx| {
2374                let this = this.downcast_mut().expect("invalid entity type");
2375                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2376            }),
2377        );
2378        activate();
2379        subscription
2380    }
2381
2382    pub fn observe_release<V2, E>(
2383        &mut self,
2384        entity: &E,
2385        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2386    ) -> Subscription
2387    where
2388        V: 'static,
2389        V2: 'static,
2390        E: Entity<V2>,
2391    {
2392        let view = self.view().downgrade();
2393        let entity_id = entity.entity_id();
2394        let window_handle = self.window.handle;
2395        let (subscription, activate) = self.app.release_listeners.insert(
2396            entity_id,
2397            Box::new(move |entity, cx| {
2398                let entity = entity.downcast_mut().expect("invalid entity type");
2399                let _ = window_handle.update(cx, |_, cx| {
2400                    view.update(cx, |this, cx| on_release(this, entity, cx))
2401                });
2402            }),
2403        );
2404        activate();
2405        subscription
2406    }
2407
2408    pub fn notify(&mut self) {
2409        if !self.window.drawing {
2410            self.window_cx.notify();
2411            self.window_cx.app.push_effect(Effect::Notify {
2412                emitter: self.view.model.entity_id,
2413            });
2414        }
2415    }
2416
2417    pub fn observe_window_bounds(
2418        &mut self,
2419        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2420    ) -> Subscription {
2421        let view = self.view.downgrade();
2422        let (subscription, activate) = self.window.bounds_observers.insert(
2423            (),
2424            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2425        );
2426        activate();
2427        subscription
2428    }
2429
2430    pub fn observe_window_activation(
2431        &mut self,
2432        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2433    ) -> Subscription {
2434        let view = self.view.downgrade();
2435        let (subscription, activate) = self.window.activation_observers.insert(
2436            (),
2437            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2438        );
2439        activate();
2440        subscription
2441    }
2442
2443    /// Register a listener to be called when the given focus handle receives focus.
2444    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2445    /// is dropped.
2446    pub fn on_focus(
2447        &mut self,
2448        handle: &FocusHandle,
2449        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2450    ) -> Subscription {
2451        let view = self.view.downgrade();
2452        let focus_id = handle.id;
2453        let (subscription, activate) = self.window.focus_listeners.insert(
2454            (),
2455            Box::new(move |event, cx| {
2456                view.update(cx, |view, cx| {
2457                    if event.previous_focus_path.last() != Some(&focus_id)
2458                        && event.current_focus_path.last() == Some(&focus_id)
2459                    {
2460                        listener(view, cx)
2461                    }
2462                })
2463                .is_ok()
2464            }),
2465        );
2466        self.app.defer(move |_| activate());
2467        subscription
2468    }
2469
2470    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2471    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2472    /// is dropped.
2473    pub fn on_focus_in(
2474        &mut self,
2475        handle: &FocusHandle,
2476        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2477    ) -> Subscription {
2478        let view = self.view.downgrade();
2479        let focus_id = handle.id;
2480        let (subscription, activate) = self.window.focus_listeners.insert(
2481            (),
2482            Box::new(move |event, cx| {
2483                view.update(cx, |view, cx| {
2484                    if !event.previous_focus_path.contains(&focus_id)
2485                        && event.current_focus_path.contains(&focus_id)
2486                    {
2487                        listener(view, cx)
2488                    }
2489                })
2490                .is_ok()
2491            }),
2492        );
2493        self.app.defer(move |_| activate());
2494        subscription
2495    }
2496
2497    /// Register a listener to be called when the given focus handle loses focus.
2498    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2499    /// is dropped.
2500    pub fn on_blur(
2501        &mut self,
2502        handle: &FocusHandle,
2503        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2504    ) -> Subscription {
2505        let view = self.view.downgrade();
2506        let focus_id = handle.id;
2507        let (subscription, activate) = self.window.focus_listeners.insert(
2508            (),
2509            Box::new(move |event, cx| {
2510                view.update(cx, |view, cx| {
2511                    if event.previous_focus_path.last() == Some(&focus_id)
2512                        && event.current_focus_path.last() != Some(&focus_id)
2513                    {
2514                        listener(view, cx)
2515                    }
2516                })
2517                .is_ok()
2518            }),
2519        );
2520        self.app.defer(move |_| activate());
2521        subscription
2522    }
2523
2524    /// Register a listener to be called when the window loses focus.
2525    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2526    /// is dropped.
2527    pub fn on_blur_window(
2528        &mut self,
2529        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2530    ) -> Subscription {
2531        let view = self.view.downgrade();
2532        let (subscription, activate) = self.window.blur_listeners.insert(
2533            (),
2534            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2535        );
2536        activate();
2537        subscription
2538    }
2539
2540    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2541    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2542    /// is dropped.
2543    pub fn on_focus_out(
2544        &mut self,
2545        handle: &FocusHandle,
2546        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2547    ) -> Subscription {
2548        let view = self.view.downgrade();
2549        let focus_id = handle.id;
2550        let (subscription, activate) = self.window.focus_listeners.insert(
2551            (),
2552            Box::new(move |event, cx| {
2553                view.update(cx, |view, cx| {
2554                    if event.previous_focus_path.contains(&focus_id)
2555                        && !event.current_focus_path.contains(&focus_id)
2556                    {
2557                        listener(view, cx)
2558                    }
2559                })
2560                .is_ok()
2561            }),
2562        );
2563        self.app.defer(move |_| activate());
2564        subscription
2565    }
2566
2567    pub fn spawn<Fut, R>(
2568        &mut self,
2569        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2570    ) -> Task<R>
2571    where
2572        R: 'static,
2573        Fut: Future<Output = R> + 'static,
2574    {
2575        let view = self.view().downgrade();
2576        self.window_cx.spawn(|cx| f(view, cx))
2577    }
2578
2579    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2580    where
2581        G: 'static,
2582    {
2583        let mut global = self.app.lease_global::<G>();
2584        let result = f(&mut global, self);
2585        self.app.end_global_lease(global);
2586        result
2587    }
2588
2589    pub fn observe_global<G: 'static>(
2590        &mut self,
2591        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2592    ) -> Subscription {
2593        let window_handle = self.window.handle;
2594        let view = self.view().downgrade();
2595        let (subscription, activate) = self.global_observers.insert(
2596            TypeId::of::<G>(),
2597            Box::new(move |cx| {
2598                window_handle
2599                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2600                    .unwrap_or(false)
2601            }),
2602        );
2603        self.app.defer(move |_| activate());
2604        subscription
2605    }
2606
2607    pub fn on_mouse_event<Event: 'static>(
2608        &mut self,
2609        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2610    ) {
2611        let handle = self.view().clone();
2612        self.window_cx.on_mouse_event(move |event, phase, cx| {
2613            handle.update(cx, |view, cx| {
2614                handler(view, event, phase, cx);
2615            })
2616        });
2617    }
2618
2619    pub fn on_key_event<Event: 'static>(
2620        &mut self,
2621        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2622    ) {
2623        let handle = self.view().clone();
2624        self.window_cx.on_key_event(move |event, phase, cx| {
2625            handle.update(cx, |view, cx| {
2626                handler(view, event, phase, cx);
2627            })
2628        });
2629    }
2630
2631    pub fn on_action(
2632        &mut self,
2633        action_type: TypeId,
2634        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2635    ) {
2636        let handle = self.view().clone();
2637        self.window_cx
2638            .on_action(action_type, move |action, phase, cx| {
2639                handle.update(cx, |view, cx| {
2640                    listener(view, action, phase, cx);
2641                })
2642            });
2643    }
2644
2645    pub fn emit<Evt>(&mut self, event: Evt)
2646    where
2647        Evt: 'static,
2648        V: EventEmitter<Evt>,
2649    {
2650        let emitter = self.view.model.entity_id;
2651        self.app.push_effect(Effect::Emit {
2652            emitter,
2653            event_type: TypeId::of::<Evt>(),
2654            event: Box::new(event),
2655        });
2656    }
2657
2658    pub fn focus_self(&mut self)
2659    where
2660        V: FocusableView,
2661    {
2662        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2663    }
2664
2665    pub fn dismiss_self(&mut self)
2666    where
2667        V: ManagedView,
2668    {
2669        self.defer(|_, cx| cx.emit(DismissEvent))
2670    }
2671
2672    pub fn listener<E>(
2673        &self,
2674        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2675    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2676        let view = self.view().downgrade();
2677        move |e: &E, cx: &mut WindowContext| {
2678            view.update(cx, |view, cx| f(view, e, cx)).ok();
2679        }
2680    }
2681}
2682
2683impl<V> Context for ViewContext<'_, V> {
2684    type Result<U> = U;
2685
2686    fn build_model<T: 'static>(
2687        &mut self,
2688        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2689    ) -> Model<T> {
2690        self.window_cx.build_model(build_model)
2691    }
2692
2693    fn update_model<T: 'static, R>(
2694        &mut self,
2695        model: &Model<T>,
2696        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2697    ) -> R {
2698        self.window_cx.update_model(model, update)
2699    }
2700
2701    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2702    where
2703        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2704    {
2705        self.window_cx.update_window(window, update)
2706    }
2707
2708    fn read_model<T, R>(
2709        &self,
2710        handle: &Model<T>,
2711        read: impl FnOnce(&T, &AppContext) -> R,
2712    ) -> Self::Result<R>
2713    where
2714        T: 'static,
2715    {
2716        self.window_cx.read_model(handle, read)
2717    }
2718
2719    fn read_window<T, R>(
2720        &self,
2721        window: &WindowHandle<T>,
2722        read: impl FnOnce(View<T>, &AppContext) -> R,
2723    ) -> Result<R>
2724    where
2725        T: 'static,
2726    {
2727        self.window_cx.read_window(window, read)
2728    }
2729}
2730
2731impl<V: 'static> VisualContext for ViewContext<'_, V> {
2732    fn build_view<W: Render + 'static>(
2733        &mut self,
2734        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2735    ) -> Self::Result<View<W>> {
2736        self.window_cx.build_view(build_view_state)
2737    }
2738
2739    fn update_view<V2: 'static, R>(
2740        &mut self,
2741        view: &View<V2>,
2742        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2743    ) -> Self::Result<R> {
2744        self.window_cx.update_view(view, update)
2745    }
2746
2747    fn replace_root_view<W>(
2748        &mut self,
2749        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2750    ) -> Self::Result<View<W>>
2751    where
2752        W: 'static + Render,
2753    {
2754        self.window_cx.replace_root_view(build_view)
2755    }
2756
2757    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2758        self.window_cx.focus_view(view)
2759    }
2760
2761    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2762        self.window_cx.dismiss_view(view)
2763    }
2764}
2765
2766impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2767    type Target = WindowContext<'a>;
2768
2769    fn deref(&self) -> &Self::Target {
2770        &self.window_cx
2771    }
2772}
2773
2774impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2775    fn deref_mut(&mut self) -> &mut Self::Target {
2776        &mut self.window_cx
2777    }
2778}
2779
2780// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2781slotmap::new_key_type! { pub struct WindowId; }
2782
2783impl WindowId {
2784    pub fn as_u64(&self) -> u64 {
2785        self.0.as_ffi()
2786    }
2787}
2788
2789#[derive(Deref, DerefMut)]
2790pub struct WindowHandle<V> {
2791    #[deref]
2792    #[deref_mut]
2793    pub(crate) any_handle: AnyWindowHandle,
2794    state_type: PhantomData<V>,
2795}
2796
2797impl<V: 'static + Render> WindowHandle<V> {
2798    pub fn new(id: WindowId) -> Self {
2799        WindowHandle {
2800            any_handle: AnyWindowHandle {
2801                id,
2802                state_type: TypeId::of::<V>(),
2803            },
2804            state_type: PhantomData,
2805        }
2806    }
2807
2808    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2809    where
2810        C: Context,
2811    {
2812        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2813            root_view
2814                .downcast::<V>()
2815                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2816        }))
2817    }
2818
2819    pub fn update<C, R>(
2820        &self,
2821        cx: &mut C,
2822        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2823    ) -> Result<R>
2824    where
2825        C: Context,
2826    {
2827        cx.update_window(self.any_handle, |root_view, cx| {
2828            let view = root_view
2829                .downcast::<V>()
2830                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2831            Ok(cx.update_view(&view, update))
2832        })?
2833    }
2834
2835    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2836        let x = cx
2837            .windows
2838            .get(self.id)
2839            .and_then(|window| {
2840                window
2841                    .as_ref()
2842                    .and_then(|window| window.root_view.clone())
2843                    .map(|root_view| root_view.downcast::<V>())
2844            })
2845            .ok_or_else(|| anyhow!("window not found"))?
2846            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2847
2848        Ok(x.read(cx))
2849    }
2850
2851    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2852    where
2853        C: Context,
2854    {
2855        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2856    }
2857
2858    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2859    where
2860        C: Context,
2861    {
2862        cx.read_window(self, |root_view, _cx| root_view.clone())
2863    }
2864
2865    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2866        cx.windows
2867            .get(self.id)
2868            .and_then(|window| window.as_ref().map(|window| window.active))
2869    }
2870}
2871
2872impl<V> Copy for WindowHandle<V> {}
2873
2874impl<V> Clone for WindowHandle<V> {
2875    fn clone(&self) -> Self {
2876        WindowHandle {
2877            any_handle: self.any_handle,
2878            state_type: PhantomData,
2879        }
2880    }
2881}
2882
2883impl<V> PartialEq for WindowHandle<V> {
2884    fn eq(&self, other: &Self) -> bool {
2885        self.any_handle == other.any_handle
2886    }
2887}
2888
2889impl<V> Eq for WindowHandle<V> {}
2890
2891impl<V> Hash for WindowHandle<V> {
2892    fn hash<H: Hasher>(&self, state: &mut H) {
2893        self.any_handle.hash(state);
2894    }
2895}
2896
2897impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2898    fn into(self) -> AnyWindowHandle {
2899        self.any_handle
2900    }
2901}
2902
2903#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2904pub struct AnyWindowHandle {
2905    pub(crate) id: WindowId,
2906    state_type: TypeId,
2907}
2908
2909impl AnyWindowHandle {
2910    pub fn window_id(&self) -> WindowId {
2911        self.id
2912    }
2913
2914    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2915        if TypeId::of::<T>() == self.state_type {
2916            Some(WindowHandle {
2917                any_handle: *self,
2918                state_type: PhantomData,
2919            })
2920        } else {
2921            None
2922        }
2923    }
2924
2925    pub fn update<C, R>(
2926        self,
2927        cx: &mut C,
2928        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2929    ) -> Result<R>
2930    where
2931        C: Context,
2932    {
2933        cx.update_window(self, update)
2934    }
2935
2936    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2937    where
2938        C: Context,
2939        T: 'static,
2940    {
2941        let view = self
2942            .downcast::<T>()
2943            .context("the type of the window's root view has changed")?;
2944
2945        cx.read_window(&view, read)
2946    }
2947}
2948
2949// #[cfg(any(test, feature = "test-support"))]
2950// impl From<SmallVec<[u32; 16]>> for StackingOrder {
2951//     fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2952//         StackingOrder(small_vec)
2953//     }
2954// }
2955
2956#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2957pub enum ElementId {
2958    View(EntityId),
2959    Integer(usize),
2960    Name(SharedString),
2961    FocusHandle(FocusId),
2962    NamedInteger(SharedString, usize),
2963}
2964
2965impl ElementId {
2966    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2967        ElementId::View(entity_id)
2968    }
2969}
2970
2971impl TryInto<SharedString> for ElementId {
2972    type Error = anyhow::Error;
2973
2974    fn try_into(self) -> anyhow::Result<SharedString> {
2975        if let ElementId::Name(name) = self {
2976            Ok(name)
2977        } else {
2978            Err(anyhow!("element id is not string"))
2979        }
2980    }
2981}
2982
2983impl From<usize> for ElementId {
2984    fn from(id: usize) -> Self {
2985        ElementId::Integer(id)
2986    }
2987}
2988
2989impl From<i32> for ElementId {
2990    fn from(id: i32) -> Self {
2991        Self::Integer(id as usize)
2992    }
2993}
2994
2995impl From<SharedString> for ElementId {
2996    fn from(name: SharedString) -> Self {
2997        ElementId::Name(name)
2998    }
2999}
3000
3001impl From<&'static str> for ElementId {
3002    fn from(name: &'static str) -> Self {
3003        ElementId::Name(name.into())
3004    }
3005}
3006
3007impl<'a> From<&'a FocusHandle> for ElementId {
3008    fn from(handle: &'a FocusHandle) -> Self {
3009        ElementId::FocusHandle(handle.id)
3010    }
3011}
3012
3013impl From<(&'static str, EntityId)> for ElementId {
3014    fn from((name, id): (&'static str, EntityId)) -> Self {
3015        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3016    }
3017}
3018
3019impl From<(&'static str, usize)> for ElementId {
3020    fn from((name, id): (&'static str, usize)) -> Self {
3021        ElementId::NamedInteger(name.into(), id)
3022    }
3023}
3024
3025impl From<(&'static str, u64)> for ElementId {
3026    fn from((name, id): (&'static str, u64)) -> Self {
3027        ElementId::NamedInteger(name.into(), id as usize)
3028    }
3029}
3030
3031/// A rectangle, to be rendered on the screen by GPUI at the given position and size.
3032pub struct PaintQuad {
3033    bounds: Bounds<Pixels>,
3034    corner_radii: Corners<Pixels>,
3035    background: Hsla,
3036    border_widths: Edges<Pixels>,
3037    border_color: Hsla,
3038}
3039
3040impl PaintQuad {
3041    /// Set the corner radii of the quad.
3042    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3043        PaintQuad {
3044            corner_radii: corner_radii.into(),
3045            ..self
3046        }
3047    }
3048
3049    /// Set the border widths of the quad.
3050    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3051        PaintQuad {
3052            border_widths: border_widths.into(),
3053            ..self
3054        }
3055    }
3056
3057    /// Set the border color of the quad.
3058    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3059        PaintQuad {
3060            border_color: border_color.into(),
3061            ..self
3062        }
3063    }
3064
3065    /// Set the background color of the quad.
3066    pub fn background(self, background: impl Into<Hsla>) -> Self {
3067        PaintQuad {
3068            background: background.into(),
3069            ..self
3070        }
3071    }
3072}
3073
3074/// Create a quad with the given parameters.
3075pub fn quad(
3076    bounds: Bounds<Pixels>,
3077    corner_radii: impl Into<Corners<Pixels>>,
3078    background: impl Into<Hsla>,
3079    border_widths: impl Into<Edges<Pixels>>,
3080    border_color: impl Into<Hsla>,
3081) -> PaintQuad {
3082    PaintQuad {
3083        bounds,
3084        corner_radii: corner_radii.into(),
3085        background: background.into(),
3086        border_widths: border_widths.into(),
3087        border_color: border_color.into(),
3088    }
3089}
3090
3091/// Create a filled quad with the given bounds and background color.
3092pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3093    PaintQuad {
3094        bounds: bounds.into(),
3095        corner_radii: (0.).into(),
3096        background: background.into(),
3097        border_widths: (0.).into(),
3098        border_color: transparent_black(),
3099    }
3100}
3101
3102/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3103pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3104    PaintQuad {
3105        bounds: bounds.into(),
3106        corner_radii: (0.).into(),
3107        background: transparent_black(),
3108        border_widths: (1.).into(),
3109        border_color: border_color.into(),
3110    }
3111}