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