window.rs

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