window.rs

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