window.rs

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