window.rs

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