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, paths } => {
1466                    self.window.mouse_position = position;
1467                    if self.active_drag.is_none() {
1468                        self.active_drag = Some(AnyDrag {
1469                            value: Box::new(paths.clone()),
1470                            view: self.new_view(|_| paths).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`][element_input_handler], which interfaces with the
1830    /// platform to receive textual input with proper integration with concerns such
1831    /// as IME interactions.
1832    ///
1833    /// [element_input_handler]: crate::ElementInputHandler
1834    pub fn handle_input(
1835        &mut self,
1836        focus_handle: &FocusHandle,
1837        input_handler: impl PlatformInputHandler,
1838    ) {
1839        if focus_handle.is_focused(self) {
1840            self.window
1841                .platform_window
1842                .set_input_handler(Box::new(input_handler));
1843        }
1844    }
1845
1846    pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1847        let mut this = self.to_async();
1848        self.window
1849            .platform_window
1850            .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1851    }
1852}
1853
1854impl Context for WindowContext<'_> {
1855    type Result<T> = T;
1856
1857    fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
1858    where
1859        T: 'static,
1860    {
1861        let slot = self.app.entities.reserve();
1862        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1863        self.entities.insert(slot, model)
1864    }
1865
1866    fn update_model<T: 'static, R>(
1867        &mut self,
1868        model: &Model<T>,
1869        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1870    ) -> R {
1871        let mut entity = self.entities.lease(model);
1872        let result = update(
1873            &mut *entity,
1874            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1875        );
1876        self.entities.end_lease(entity);
1877        result
1878    }
1879
1880    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1881    where
1882        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1883    {
1884        if window == self.window.handle {
1885            let root_view = self.window.root_view.clone().unwrap();
1886            Ok(update(root_view, self))
1887        } else {
1888            window.update(self.app, update)
1889        }
1890    }
1891
1892    fn read_model<T, R>(
1893        &self,
1894        handle: &Model<T>,
1895        read: impl FnOnce(&T, &AppContext) -> R,
1896    ) -> Self::Result<R>
1897    where
1898        T: 'static,
1899    {
1900        let entity = self.entities.read(handle);
1901        read(entity, &*self.app)
1902    }
1903
1904    fn read_window<T, R>(
1905        &self,
1906        window: &WindowHandle<T>,
1907        read: impl FnOnce(View<T>, &AppContext) -> R,
1908    ) -> Result<R>
1909    where
1910        T: 'static,
1911    {
1912        if window.any_handle == self.window.handle {
1913            let root_view = self
1914                .window
1915                .root_view
1916                .clone()
1917                .unwrap()
1918                .downcast::<T>()
1919                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1920            Ok(read(root_view, self))
1921        } else {
1922            self.app.read_window(window, read)
1923        }
1924    }
1925}
1926
1927impl VisualContext for WindowContext<'_> {
1928    fn new_view<V>(
1929        &mut self,
1930        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1931    ) -> Self::Result<View<V>>
1932    where
1933        V: 'static + Render,
1934    {
1935        let slot = self.app.entities.reserve();
1936        let view = View {
1937            model: slot.clone(),
1938        };
1939        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1940        let entity = build_view_state(&mut cx);
1941        cx.entities.insert(slot, entity);
1942
1943        cx.new_view_observers
1944            .clone()
1945            .retain(&TypeId::of::<V>(), |observer| {
1946                let any_view = AnyView::from(view.clone());
1947                (observer)(any_view, self);
1948                true
1949            });
1950
1951        view
1952    }
1953
1954    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1955    fn update_view<T: 'static, R>(
1956        &mut self,
1957        view: &View<T>,
1958        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1959    ) -> Self::Result<R> {
1960        let mut lease = self.app.entities.lease(&view.model);
1961        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
1962        let result = update(&mut *lease, &mut cx);
1963        cx.app.entities.end_lease(lease);
1964        result
1965    }
1966
1967    fn replace_root_view<V>(
1968        &mut self,
1969        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1970    ) -> Self::Result<View<V>>
1971    where
1972        V: 'static + Render,
1973    {
1974        let view = self.new_view(build_view);
1975        self.window.root_view = Some(view.clone().into());
1976        self.notify();
1977        view
1978    }
1979
1980    fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1981        self.update_view(view, |view, cx| {
1982            view.focus_handle(cx).clone().focus(cx);
1983        })
1984    }
1985
1986    fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1987    where
1988        V: ManagedView,
1989    {
1990        self.update_view(view, |_, cx| cx.emit(DismissEvent))
1991    }
1992}
1993
1994impl<'a> std::ops::Deref for WindowContext<'a> {
1995    type Target = AppContext;
1996
1997    fn deref(&self) -> &Self::Target {
1998        self.app
1999    }
2000}
2001
2002impl<'a> std::ops::DerefMut for WindowContext<'a> {
2003    fn deref_mut(&mut self) -> &mut Self::Target {
2004        self.app
2005    }
2006}
2007
2008impl<'a> Borrow<AppContext> for WindowContext<'a> {
2009    fn borrow(&self) -> &AppContext {
2010        self.app
2011    }
2012}
2013
2014impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
2015    fn borrow_mut(&mut self) -> &mut AppContext {
2016        self.app
2017    }
2018}
2019
2020pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
2021    fn app_mut(&mut self) -> &mut AppContext {
2022        self.borrow_mut()
2023    }
2024
2025    fn app(&self) -> &AppContext {
2026        self.borrow()
2027    }
2028
2029    fn window(&self) -> &Window {
2030        self.borrow()
2031    }
2032
2033    fn window_mut(&mut self) -> &mut Window {
2034        self.borrow_mut()
2035    }
2036
2037    /// Pushes the given element id onto the global stack and invokes the given closure
2038    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
2039    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
2040    /// used to associate state with identified elements across separate frames.
2041    fn with_element_id<R>(
2042        &mut self,
2043        id: Option<impl Into<ElementId>>,
2044        f: impl FnOnce(&mut Self) -> R,
2045    ) -> R {
2046        if let Some(id) = id.map(Into::into) {
2047            let window = self.window_mut();
2048            window.element_id_stack.push(id);
2049            let result = f(self);
2050            let window: &mut Window = self.borrow_mut();
2051            window.element_id_stack.pop();
2052            result
2053        } else {
2054            f(self)
2055        }
2056    }
2057
2058    /// Invoke the given function with the given content mask after intersecting it
2059    /// with the current mask.
2060    fn with_content_mask<R>(
2061        &mut self,
2062        mask: Option<ContentMask<Pixels>>,
2063        f: impl FnOnce(&mut Self) -> R,
2064    ) -> R {
2065        if let Some(mask) = mask {
2066            let mask = mask.intersect(&self.content_mask());
2067            self.window_mut().next_frame.content_mask_stack.push(mask);
2068            let result = f(self);
2069            self.window_mut().next_frame.content_mask_stack.pop();
2070            result
2071        } else {
2072            f(self)
2073        }
2074    }
2075
2076    /// Invoke the given function with the content mask reset to that
2077    /// of the window.
2078    fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2079        let mask = ContentMask {
2080            bounds: Bounds {
2081                origin: Point::default(),
2082                size: self.window().viewport_size,
2083            },
2084        };
2085        let new_stacking_order_id =
2086            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2087        let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
2088        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2089        self.window_mut().next_frame.content_mask_stack.push(mask);
2090        let result = f(self);
2091        self.window_mut().next_frame.content_mask_stack.pop();
2092        self.window_mut().next_frame.z_index_stack = old_stacking_order;
2093        result
2094    }
2095
2096    /// Called during painting to invoke the given closure in a new stacking context. The given
2097    /// z-index is interpreted relative to the previous call to `stack`.
2098    fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2099        let new_stacking_order_id =
2100            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
2101        let old_stacking_order_id = mem::replace(
2102            &mut self.window_mut().next_frame.z_index_stack.id,
2103            new_stacking_order_id,
2104        );
2105        self.window_mut().next_frame.z_index_stack.id = new_stacking_order_id;
2106        self.window_mut().next_frame.z_index_stack.push(z_index);
2107        let result = f(self);
2108        self.window_mut().next_frame.z_index_stack.id = old_stacking_order_id;
2109        self.window_mut().next_frame.z_index_stack.pop();
2110        result
2111    }
2112
2113    /// Update the global element offset relative to the current offset. This is used to implement
2114    /// scrolling.
2115    fn with_element_offset<R>(
2116        &mut self,
2117        offset: Point<Pixels>,
2118        f: impl FnOnce(&mut Self) -> R,
2119    ) -> R {
2120        if offset.is_zero() {
2121            return f(self);
2122        };
2123
2124        let abs_offset = self.element_offset() + offset;
2125        self.with_absolute_element_offset(abs_offset, f)
2126    }
2127
2128    /// Update the global element offset based on the given offset. This is used to implement
2129    /// drag handles and other manual painting of elements.
2130    fn with_absolute_element_offset<R>(
2131        &mut self,
2132        offset: Point<Pixels>,
2133        f: impl FnOnce(&mut Self) -> R,
2134    ) -> R {
2135        self.window_mut()
2136            .next_frame
2137            .element_offset_stack
2138            .push(offset);
2139        let result = f(self);
2140        self.window_mut().next_frame.element_offset_stack.pop();
2141        result
2142    }
2143
2144    /// Obtain the current element offset.
2145    fn element_offset(&self) -> Point<Pixels> {
2146        self.window()
2147            .next_frame
2148            .element_offset_stack
2149            .last()
2150            .copied()
2151            .unwrap_or_default()
2152    }
2153
2154    /// Update or initialize state for an element with the given id that lives across multiple
2155    /// frames. If an element with this id existed in the rendered frame, its state will be passed
2156    /// to the given closure. The state returned by the closure will be stored so it can be referenced
2157    /// when drawing the next frame.
2158    fn with_element_state<S, R>(
2159        &mut self,
2160        id: ElementId,
2161        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2162    ) -> R
2163    where
2164        S: 'static,
2165    {
2166        self.with_element_id(Some(id), |cx| {
2167            let global_id = cx.window().element_id_stack.clone();
2168
2169            if let Some(any) = cx
2170                .window_mut()
2171                .next_frame
2172                .element_states
2173                .remove(&global_id)
2174                .or_else(|| {
2175                    cx.window_mut()
2176                        .rendered_frame
2177                        .element_states
2178                        .remove(&global_id)
2179                })
2180            {
2181                let ElementStateBox {
2182                    inner,
2183
2184                    #[cfg(debug_assertions)]
2185                    type_name
2186                } = any;
2187                // Using the extra inner option to avoid needing to reallocate a new box.
2188                let mut state_box = inner
2189                    .downcast::<Option<S>>()
2190                    .map_err(|_| {
2191                        #[cfg(debug_assertions)]
2192                        {
2193                            anyhow!(
2194                                "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2195                                std::any::type_name::<S>(),
2196                                type_name
2197                            )
2198                        }
2199
2200                        #[cfg(not(debug_assertions))]
2201                        {
2202                            anyhow!(
2203                                "invalid element state type for id, requested_type {:?}",
2204                                std::any::type_name::<S>(),
2205                            )
2206                        }
2207                    })
2208                    .unwrap();
2209
2210                // Actual: Option<AnyElement> <- View
2211                // Requested: () <- AnyElemet
2212                let state = state_box
2213                    .take()
2214                    .expect("element state is already on the stack");
2215                let (result, state) = f(Some(state), cx);
2216                state_box.replace(state);
2217                cx.window_mut()
2218                    .next_frame
2219                    .element_states
2220                    .insert(global_id, ElementStateBox {
2221                        inner: state_box,
2222
2223                        #[cfg(debug_assertions)]
2224                        type_name
2225                    });
2226                result
2227            } else {
2228                let (result, state) = f(None, cx);
2229                cx.window_mut()
2230                    .next_frame
2231                    .element_states
2232                    .insert(global_id,
2233                        ElementStateBox {
2234                            inner: Box::new(Some(state)),
2235
2236                            #[cfg(debug_assertions)]
2237                            type_name: std::any::type_name::<S>()
2238                        }
2239
2240                    );
2241                result
2242            }
2243        })
2244    }
2245
2246    /// Obtain the current content mask.
2247    fn content_mask(&self) -> ContentMask<Pixels> {
2248        self.window()
2249            .next_frame
2250            .content_mask_stack
2251            .last()
2252            .cloned()
2253            .unwrap_or_else(|| ContentMask {
2254                bounds: Bounds {
2255                    origin: Point::default(),
2256                    size: self.window().viewport_size,
2257                },
2258            })
2259    }
2260
2261    /// The size of an em for the base font of the application. Adjusting this value allows the
2262    /// UI to scale, just like zooming a web page.
2263    fn rem_size(&self) -> Pixels {
2264        self.window().rem_size
2265    }
2266}
2267
2268impl Borrow<Window> for WindowContext<'_> {
2269    fn borrow(&self) -> &Window {
2270        self.window
2271    }
2272}
2273
2274impl BorrowMut<Window> for WindowContext<'_> {
2275    fn borrow_mut(&mut self) -> &mut Window {
2276        self.window
2277    }
2278}
2279
2280impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2281
2282pub struct ViewContext<'a, V> {
2283    window_cx: WindowContext<'a>,
2284    view: &'a View<V>,
2285}
2286
2287impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2288    fn borrow(&self) -> &AppContext {
2289        &*self.window_cx.app
2290    }
2291}
2292
2293impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2294    fn borrow_mut(&mut self) -> &mut AppContext {
2295        &mut *self.window_cx.app
2296    }
2297}
2298
2299impl<V> Borrow<Window> for ViewContext<'_, V> {
2300    fn borrow(&self) -> &Window {
2301        &*self.window_cx.window
2302    }
2303}
2304
2305impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2306    fn borrow_mut(&mut self) -> &mut Window {
2307        &mut *self.window_cx.window
2308    }
2309}
2310
2311impl<'a, V: 'static> ViewContext<'a, V> {
2312    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2313        Self {
2314            window_cx: WindowContext::new(app, window),
2315            view,
2316        }
2317    }
2318
2319    pub fn entity_id(&self) -> EntityId {
2320        self.view.entity_id()
2321    }
2322
2323    pub fn view(&self) -> &View<V> {
2324        self.view
2325    }
2326
2327    pub fn model(&self) -> &Model<V> {
2328        &self.view.model
2329    }
2330
2331    /// Access the underlying window context.
2332    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2333        &mut self.window_cx
2334    }
2335
2336    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2337    where
2338        V: 'static,
2339    {
2340        let view = self.view().clone();
2341        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2342    }
2343
2344    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2345    /// that are currently on the stack to be returned to the app.
2346    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2347        let view = self.view().downgrade();
2348        self.window_cx.defer(move |cx| {
2349            view.update(cx, f).ok();
2350        });
2351    }
2352
2353    pub fn observe<V2, E>(
2354        &mut self,
2355        entity: &E,
2356        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2357    ) -> Subscription
2358    where
2359        V2: 'static,
2360        V: 'static,
2361        E: Entity<V2>,
2362    {
2363        let view = self.view().downgrade();
2364        let entity_id = entity.entity_id();
2365        let entity = entity.downgrade();
2366        let window_handle = self.window.handle;
2367        let (subscription, activate) = self.app.observers.insert(
2368            entity_id,
2369            Box::new(move |cx| {
2370                window_handle
2371                    .update(cx, |_, cx| {
2372                        if let Some(handle) = E::upgrade_from(&entity) {
2373                            view.update(cx, |this, cx| on_notify(this, handle, cx))
2374                                .is_ok()
2375                        } else {
2376                            false
2377                        }
2378                    })
2379                    .unwrap_or(false)
2380            }),
2381        );
2382        self.app.defer(move |_| activate());
2383        subscription
2384    }
2385
2386    pub fn subscribe<V2, E, Evt>(
2387        &mut self,
2388        entity: &E,
2389        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2390    ) -> Subscription
2391    where
2392        V2: EventEmitter<Evt>,
2393        E: Entity<V2>,
2394        Evt: 'static,
2395    {
2396        let view = self.view().downgrade();
2397        let entity_id = entity.entity_id();
2398        let handle = entity.downgrade();
2399        let window_handle = self.window.handle;
2400        let (subscription, activate) = self.app.event_listeners.insert(
2401            entity_id,
2402            (
2403                TypeId::of::<Evt>(),
2404                Box::new(move |event, cx| {
2405                    window_handle
2406                        .update(cx, |_, cx| {
2407                            if let Some(handle) = E::upgrade_from(&handle) {
2408                                let event = event.downcast_ref().expect("invalid event type");
2409                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
2410                                    .is_ok()
2411                            } else {
2412                                false
2413                            }
2414                        })
2415                        .unwrap_or(false)
2416                }),
2417            ),
2418        );
2419        self.app.defer(move |_| activate());
2420        subscription
2421    }
2422
2423    /// Register a callback to be invoked when the view is released.
2424    ///
2425    /// The callback receives a handle to the view's window. This handle may be
2426    /// invalid, if the window was closed before the view was released.
2427    pub fn on_release(
2428        &mut self,
2429        on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
2430    ) -> Subscription {
2431        let window_handle = self.window.handle;
2432        let (subscription, activate) = self.app.release_listeners.insert(
2433            self.view.model.entity_id,
2434            Box::new(move |this, cx| {
2435                let this = this.downcast_mut().expect("invalid entity type");
2436                on_release(this, window_handle, cx)
2437            }),
2438        );
2439        activate();
2440        subscription
2441    }
2442
2443    pub fn observe_release<V2, E>(
2444        &mut self,
2445        entity: &E,
2446        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2447    ) -> Subscription
2448    where
2449        V: 'static,
2450        V2: 'static,
2451        E: Entity<V2>,
2452    {
2453        let view = self.view().downgrade();
2454        let entity_id = entity.entity_id();
2455        let window_handle = self.window.handle;
2456        let (subscription, activate) = self.app.release_listeners.insert(
2457            entity_id,
2458            Box::new(move |entity, cx| {
2459                let entity = entity.downcast_mut().expect("invalid entity type");
2460                let _ = window_handle.update(cx, |_, cx| {
2461                    view.update(cx, |this, cx| on_release(this, entity, cx))
2462                });
2463            }),
2464        );
2465        activate();
2466        subscription
2467    }
2468
2469    pub fn notify(&mut self) {
2470        if !self.window.drawing {
2471            self.window_cx.notify();
2472            self.window_cx.app.push_effect(Effect::Notify {
2473                emitter: self.view.model.entity_id,
2474            });
2475        }
2476    }
2477
2478    pub fn observe_window_bounds(
2479        &mut self,
2480        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2481    ) -> Subscription {
2482        let view = self.view.downgrade();
2483        let (subscription, activate) = self.window.bounds_observers.insert(
2484            (),
2485            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2486        );
2487        activate();
2488        subscription
2489    }
2490
2491    pub fn observe_window_activation(
2492        &mut self,
2493        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2494    ) -> Subscription {
2495        let view = self.view.downgrade();
2496        let (subscription, activate) = self.window.activation_observers.insert(
2497            (),
2498            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2499        );
2500        activate();
2501        subscription
2502    }
2503
2504    /// Register a listener to be called when the given focus handle receives focus.
2505    /// Returns a subscription and persists until the subscription is dropped.
2506    pub fn on_focus(
2507        &mut self,
2508        handle: &FocusHandle,
2509        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2510    ) -> Subscription {
2511        let view = self.view.downgrade();
2512        let focus_id = handle.id;
2513        let (subscription, activate) = self.window.focus_listeners.insert(
2514            (),
2515            Box::new(move |event, cx| {
2516                view.update(cx, |view, cx| {
2517                    if event.previous_focus_path.last() != Some(&focus_id)
2518                        && event.current_focus_path.last() == Some(&focus_id)
2519                    {
2520                        listener(view, cx)
2521                    }
2522                })
2523                .is_ok()
2524            }),
2525        );
2526        self.app.defer(move |_| activate());
2527        subscription
2528    }
2529
2530    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2531    /// Returns a subscription and persists until the subscription 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    /// Returns a subscription and persists until the subscription is dropped.
2558    pub fn on_blur(
2559        &mut self,
2560        handle: &FocusHandle,
2561        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2562    ) -> Subscription {
2563        let view = self.view.downgrade();
2564        let focus_id = handle.id;
2565        let (subscription, activate) = self.window.focus_listeners.insert(
2566            (),
2567            Box::new(move |event, cx| {
2568                view.update(cx, |view, cx| {
2569                    if event.previous_focus_path.last() == Some(&focus_id)
2570                        && event.current_focus_path.last() != Some(&focus_id)
2571                    {
2572                        listener(view, cx)
2573                    }
2574                })
2575                .is_ok()
2576            }),
2577        );
2578        self.app.defer(move |_| activate());
2579        subscription
2580    }
2581
2582    /// Register a listener to be called when the window loses focus.
2583    /// Returns a subscription and persists until the subscription is dropped.
2584    pub fn on_blur_window(
2585        &mut self,
2586        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2587    ) -> Subscription {
2588        let view = self.view.downgrade();
2589        let (subscription, activate) = self.window.blur_listeners.insert(
2590            (),
2591            Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2592        );
2593        activate();
2594        subscription
2595    }
2596
2597    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2598    /// Returns a subscription and persists until the subscription is dropped.
2599    pub fn on_focus_out(
2600        &mut self,
2601        handle: &FocusHandle,
2602        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2603    ) -> Subscription {
2604        let view = self.view.downgrade();
2605        let focus_id = handle.id;
2606        let (subscription, activate) = self.window.focus_listeners.insert(
2607            (),
2608            Box::new(move |event, cx| {
2609                view.update(cx, |view, cx| {
2610                    if event.previous_focus_path.contains(&focus_id)
2611                        && !event.current_focus_path.contains(&focus_id)
2612                    {
2613                        listener(view, cx)
2614                    }
2615                })
2616                .is_ok()
2617            }),
2618        );
2619        self.app.defer(move |_| activate());
2620        subscription
2621    }
2622
2623    pub fn spawn<Fut, R>(
2624        &mut self,
2625        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2626    ) -> Task<R>
2627    where
2628        R: 'static,
2629        Fut: Future<Output = R> + 'static,
2630    {
2631        let view = self.view().downgrade();
2632        self.window_cx.spawn(|cx| f(view, cx))
2633    }
2634
2635    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2636    where
2637        G: 'static,
2638    {
2639        let mut global = self.app.lease_global::<G>();
2640        let result = f(&mut global, self);
2641        self.app.end_global_lease(global);
2642        result
2643    }
2644
2645    pub fn observe_global<G: 'static>(
2646        &mut self,
2647        mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2648    ) -> Subscription {
2649        let window_handle = self.window.handle;
2650        let view = self.view().downgrade();
2651        let (subscription, activate) = self.global_observers.insert(
2652            TypeId::of::<G>(),
2653            Box::new(move |cx| {
2654                window_handle
2655                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2656                    .unwrap_or(false)
2657            }),
2658        );
2659        self.app.defer(move |_| activate());
2660        subscription
2661    }
2662
2663    pub fn on_mouse_event<Event: 'static>(
2664        &mut self,
2665        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2666    ) {
2667        let handle = self.view().clone();
2668        self.window_cx.on_mouse_event(move |event, phase, cx| {
2669            handle.update(cx, |view, cx| {
2670                handler(view, event, phase, cx);
2671            })
2672        });
2673    }
2674
2675    pub fn on_key_event<Event: 'static>(
2676        &mut self,
2677        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2678    ) {
2679        let handle = self.view().clone();
2680        self.window_cx.on_key_event(move |event, phase, cx| {
2681            handle.update(cx, |view, cx| {
2682                handler(view, event, phase, cx);
2683            })
2684        });
2685    }
2686
2687    pub fn on_action(
2688        &mut self,
2689        action_type: TypeId,
2690        listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2691    ) {
2692        let handle = self.view().clone();
2693        self.window_cx
2694            .on_action(action_type, move |action, phase, cx| {
2695                handle.update(cx, |view, cx| {
2696                    listener(view, action, phase, cx);
2697                })
2698            });
2699    }
2700
2701    pub fn emit<Evt>(&mut self, event: Evt)
2702    where
2703        Evt: 'static,
2704        V: EventEmitter<Evt>,
2705    {
2706        let emitter = self.view.model.entity_id;
2707        self.app.push_effect(Effect::Emit {
2708            emitter,
2709            event_type: TypeId::of::<Evt>(),
2710            event: Box::new(event),
2711        });
2712    }
2713
2714    pub fn focus_self(&mut self)
2715    where
2716        V: FocusableView,
2717    {
2718        self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2719    }
2720
2721    pub fn listener<E>(
2722        &self,
2723        f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2724    ) -> impl Fn(&E, &mut WindowContext) + 'static {
2725        let view = self.view().downgrade();
2726        move |e: &E, cx: &mut WindowContext| {
2727            view.update(cx, |view, cx| f(view, e, cx)).ok();
2728        }
2729    }
2730}
2731
2732impl<V> Context for ViewContext<'_, V> {
2733    type Result<U> = U;
2734
2735    fn new_model<T: 'static>(
2736        &mut self,
2737        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2738    ) -> Model<T> {
2739        self.window_cx.new_model(build_model)
2740    }
2741
2742    fn update_model<T: 'static, R>(
2743        &mut self,
2744        model: &Model<T>,
2745        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2746    ) -> R {
2747        self.window_cx.update_model(model, update)
2748    }
2749
2750    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2751    where
2752        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2753    {
2754        self.window_cx.update_window(window, update)
2755    }
2756
2757    fn read_model<T, R>(
2758        &self,
2759        handle: &Model<T>,
2760        read: impl FnOnce(&T, &AppContext) -> R,
2761    ) -> Self::Result<R>
2762    where
2763        T: 'static,
2764    {
2765        self.window_cx.read_model(handle, read)
2766    }
2767
2768    fn read_window<T, R>(
2769        &self,
2770        window: &WindowHandle<T>,
2771        read: impl FnOnce(View<T>, &AppContext) -> R,
2772    ) -> Result<R>
2773    where
2774        T: 'static,
2775    {
2776        self.window_cx.read_window(window, read)
2777    }
2778}
2779
2780impl<V: 'static> VisualContext for ViewContext<'_, V> {
2781    fn new_view<W: Render + 'static>(
2782        &mut self,
2783        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2784    ) -> Self::Result<View<W>> {
2785        self.window_cx.new_view(build_view_state)
2786    }
2787
2788    fn update_view<V2: 'static, R>(
2789        &mut self,
2790        view: &View<V2>,
2791        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2792    ) -> Self::Result<R> {
2793        self.window_cx.update_view(view, update)
2794    }
2795
2796    fn replace_root_view<W>(
2797        &mut self,
2798        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2799    ) -> Self::Result<View<W>>
2800    where
2801        W: 'static + Render,
2802    {
2803        self.window_cx.replace_root_view(build_view)
2804    }
2805
2806    fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2807        self.window_cx.focus_view(view)
2808    }
2809
2810    fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2811        self.window_cx.dismiss_view(view)
2812    }
2813}
2814
2815impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2816    type Target = WindowContext<'a>;
2817
2818    fn deref(&self) -> &Self::Target {
2819        &self.window_cx
2820    }
2821}
2822
2823impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2824    fn deref_mut(&mut self) -> &mut Self::Target {
2825        &mut self.window_cx
2826    }
2827}
2828
2829// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2830slotmap::new_key_type! { pub struct WindowId; }
2831
2832impl WindowId {
2833    pub fn as_u64(&self) -> u64 {
2834        self.0.as_ffi()
2835    }
2836}
2837
2838#[derive(Deref, DerefMut)]
2839pub struct WindowHandle<V> {
2840    #[deref]
2841    #[deref_mut]
2842    pub(crate) any_handle: AnyWindowHandle,
2843    state_type: PhantomData<V>,
2844}
2845
2846impl<V: 'static + Render> WindowHandle<V> {
2847    pub fn new(id: WindowId) -> Self {
2848        WindowHandle {
2849            any_handle: AnyWindowHandle {
2850                id,
2851                state_type: TypeId::of::<V>(),
2852            },
2853            state_type: PhantomData,
2854        }
2855    }
2856
2857    pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2858    where
2859        C: Context,
2860    {
2861        Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2862            root_view
2863                .downcast::<V>()
2864                .map_err(|_| anyhow!("the type of the window's root view has changed"))
2865        }))
2866    }
2867
2868    pub fn update<C, R>(
2869        &self,
2870        cx: &mut C,
2871        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2872    ) -> Result<R>
2873    where
2874        C: Context,
2875    {
2876        cx.update_window(self.any_handle, |root_view, cx| {
2877            let view = root_view
2878                .downcast::<V>()
2879                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2880            Ok(cx.update_view(&view, update))
2881        })?
2882    }
2883
2884    pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2885        let x = cx
2886            .windows
2887            .get(self.id)
2888            .and_then(|window| {
2889                window
2890                    .as_ref()
2891                    .and_then(|window| window.root_view.clone())
2892                    .map(|root_view| root_view.downcast::<V>())
2893            })
2894            .ok_or_else(|| anyhow!("window not found"))?
2895            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2896
2897        Ok(x.read(cx))
2898    }
2899
2900    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2901    where
2902        C: Context,
2903    {
2904        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2905    }
2906
2907    pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2908    where
2909        C: Context,
2910    {
2911        cx.read_window(self, |root_view, _cx| root_view.clone())
2912    }
2913
2914    pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2915        cx.windows
2916            .get(self.id)
2917            .and_then(|window| window.as_ref().map(|window| window.active))
2918    }
2919}
2920
2921impl<V> Copy for WindowHandle<V> {}
2922
2923impl<V> Clone for WindowHandle<V> {
2924    fn clone(&self) -> Self {
2925        *self
2926    }
2927}
2928
2929impl<V> PartialEq for WindowHandle<V> {
2930    fn eq(&self, other: &Self) -> bool {
2931        self.any_handle == other.any_handle
2932    }
2933}
2934
2935impl<V> Eq for WindowHandle<V> {}
2936
2937impl<V> Hash for WindowHandle<V> {
2938    fn hash<H: Hasher>(&self, state: &mut H) {
2939        self.any_handle.hash(state);
2940    }
2941}
2942
2943impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
2944    fn from(val: WindowHandle<V>) -> Self {
2945        val.any_handle
2946    }
2947}
2948
2949#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2950pub struct AnyWindowHandle {
2951    pub(crate) id: WindowId,
2952    state_type: TypeId,
2953}
2954
2955impl AnyWindowHandle {
2956    pub fn window_id(&self) -> WindowId {
2957        self.id
2958    }
2959
2960    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2961        if TypeId::of::<T>() == self.state_type {
2962            Some(WindowHandle {
2963                any_handle: *self,
2964                state_type: PhantomData,
2965            })
2966        } else {
2967            None
2968        }
2969    }
2970
2971    pub fn update<C, R>(
2972        self,
2973        cx: &mut C,
2974        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2975    ) -> Result<R>
2976    where
2977        C: Context,
2978    {
2979        cx.update_window(self, update)
2980    }
2981
2982    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2983    where
2984        C: Context,
2985        T: 'static,
2986    {
2987        let view = self
2988            .downcast::<T>()
2989            .context("the type of the window's root view has changed")?;
2990
2991        cx.read_window(&view, read)
2992    }
2993}
2994
2995// #[cfg(any(test, feature = "test-support"))]
2996// impl From<SmallVec<[u32; 16]>> for StackingOrder {
2997//     fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2998//         StackingOrder(small_vec)
2999//     }
3000// }
3001
3002#[derive(Clone, Debug, Eq, PartialEq, Hash)]
3003pub enum ElementId {
3004    View(EntityId),
3005    Integer(usize),
3006    Name(SharedString),
3007    FocusHandle(FocusId),
3008    NamedInteger(SharedString, usize),
3009}
3010
3011impl ElementId {
3012    pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
3013        ElementId::View(entity_id)
3014    }
3015}
3016
3017impl TryInto<SharedString> for ElementId {
3018    type Error = anyhow::Error;
3019
3020    fn try_into(self) -> anyhow::Result<SharedString> {
3021        if let ElementId::Name(name) = self {
3022            Ok(name)
3023        } else {
3024            Err(anyhow!("element id is not string"))
3025        }
3026    }
3027}
3028
3029impl From<usize> for ElementId {
3030    fn from(id: usize) -> Self {
3031        ElementId::Integer(id)
3032    }
3033}
3034
3035impl From<i32> for ElementId {
3036    fn from(id: i32) -> Self {
3037        Self::Integer(id as usize)
3038    }
3039}
3040
3041impl From<SharedString> for ElementId {
3042    fn from(name: SharedString) -> Self {
3043        ElementId::Name(name)
3044    }
3045}
3046
3047impl From<&'static str> for ElementId {
3048    fn from(name: &'static str) -> Self {
3049        ElementId::Name(name.into())
3050    }
3051}
3052
3053impl<'a> From<&'a FocusHandle> for ElementId {
3054    fn from(handle: &'a FocusHandle) -> Self {
3055        ElementId::FocusHandle(handle.id)
3056    }
3057}
3058
3059impl From<(&'static str, EntityId)> for ElementId {
3060    fn from((name, id): (&'static str, EntityId)) -> Self {
3061        ElementId::NamedInteger(name.into(), id.as_u64() as usize)
3062    }
3063}
3064
3065impl From<(&'static str, usize)> for ElementId {
3066    fn from((name, id): (&'static str, usize)) -> Self {
3067        ElementId::NamedInteger(name.into(), id)
3068    }
3069}
3070
3071impl From<(&'static str, u64)> for ElementId {
3072    fn from((name, id): (&'static str, u64)) -> Self {
3073        ElementId::NamedInteger(name.into(), id as usize)
3074    }
3075}
3076
3077/// A rectangle, to be rendered on the screen by GPUI at the given position and size.
3078#[derive(Clone)]
3079pub struct PaintQuad {
3080    bounds: Bounds<Pixels>,
3081    corner_radii: Corners<Pixels>,
3082    background: Hsla,
3083    border_widths: Edges<Pixels>,
3084    border_color: Hsla,
3085}
3086
3087impl PaintQuad {
3088    /// Set the corner radii of the quad.
3089    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3090        PaintQuad {
3091            corner_radii: corner_radii.into(),
3092            ..self
3093        }
3094    }
3095
3096    /// Set the border widths of the quad.
3097    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3098        PaintQuad {
3099            border_widths: border_widths.into(),
3100            ..self
3101        }
3102    }
3103
3104    /// Set the border color of the quad.
3105    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3106        PaintQuad {
3107            border_color: border_color.into(),
3108            ..self
3109        }
3110    }
3111
3112    /// Set the background color of the quad.
3113    pub fn background(self, background: impl Into<Hsla>) -> Self {
3114        PaintQuad {
3115            background: background.into(),
3116            ..self
3117        }
3118    }
3119}
3120
3121/// Create a quad with the given parameters.
3122pub fn quad(
3123    bounds: Bounds<Pixels>,
3124    corner_radii: impl Into<Corners<Pixels>>,
3125    background: impl Into<Hsla>,
3126    border_widths: impl Into<Edges<Pixels>>,
3127    border_color: impl Into<Hsla>,
3128) -> PaintQuad {
3129    PaintQuad {
3130        bounds,
3131        corner_radii: corner_radii.into(),
3132        background: background.into(),
3133        border_widths: border_widths.into(),
3134        border_color: border_color.into(),
3135    }
3136}
3137
3138/// Create a filled quad with the given bounds and background color.
3139pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3140    PaintQuad {
3141        bounds: bounds.into(),
3142        corner_radii: (0.).into(),
3143        background: background.into(),
3144        border_widths: (0.).into(),
3145        border_color: transparent_black(),
3146    }
3147}
3148
3149/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3150pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3151    PaintQuad {
3152        bounds: bounds.into(),
3153        corner_radii: (0.).into(),
3154        background: transparent_black(),
3155        border_widths: (1.).into(),
3156        border_color: border_color.into(),
3157    }
3158}