window.rs

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