window.rs

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