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