element_cx.rs

   1//! The element context is the main interface for interacting with the frame during a paint.
   2//!
   3//! Elements are hierarchical and with a few exceptions the context accumulates state in a stack
   4//! as it processes all of the elements in the frame. The methods that interact with this stack
   5//! are generally marked with `with_*`, and take a callback to denote the region of code that
   6//! should be executed with that state.
   7//!
   8//! The other main interface is the `paint_*` family of methods, which push basic drawing commands
   9//! to the GPU. Everything in a GPUI app is drawn with these methods.
  10//!
  11//! There are also several internal methods that GPUI uses, such as [`ElementContext::with_element_state`]
  12//! to call the paint and layout methods on elements. These have been included as they're often useful
  13//! for taking manual control of the layouting or painting of specialized elements.
  14
  15use std::{
  16    any::{Any, TypeId},
  17    borrow::{Borrow, BorrowMut, Cow},
  18    mem,
  19    rc::Rc,
  20    sync::Arc,
  21};
  22
  23use anyhow::Result;
  24use collections::{FxHashMap, FxHashSet};
  25use derive_more::{Deref, DerefMut};
  26use media::core_video::CVImageBuffer;
  27use smallvec::SmallVec;
  28use util::post_inc;
  29
  30use crate::{
  31    prelude::*, size, AnyTooltip, AppContext, AvailableSpace, Bounds, BoxShadow, ContentMask,
  32    Corners, CursorStyle, DevicePixels, DispatchPhase, DispatchTree, ElementId, ElementStateBox,
  33    EntityId, FocusHandle, FocusId, FontId, GlobalElementId, GlyphId, Hsla, ImageData,
  34    InputHandler, IsZero, KeyContext, KeyEvent, KeymatchMode, LayoutId, MonochromeSprite,
  35    MouseEvent, PaintQuad, Path, Pixels, PlatformInputHandler, Point, PolychromeSprite, Quad,
  36    RenderGlyphParams, RenderImageParams, RenderSvgParams, Scene, Shadow, SharedString, Size,
  37    StackingContext, StackingOrder, Style, Surface, TextStyleRefinement, Underline, UnderlineStyle,
  38    Window, WindowContext, SUBPIXEL_VARIANTS,
  39};
  40
  41type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut ElementContext) + 'static>;
  42
  43pub(crate) struct RequestedInputHandler {
  44    pub(crate) view_id: EntityId,
  45    pub(crate) handler: Option<PlatformInputHandler>,
  46}
  47
  48pub(crate) struct TooltipRequest {
  49    pub(crate) view_id: EntityId,
  50    pub(crate) tooltip: AnyTooltip,
  51}
  52
  53pub(crate) struct Frame {
  54    pub(crate) focus: Option<FocusId>,
  55    pub(crate) window_active: bool,
  56    pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
  57    pub(crate) mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, EntityId, AnyMouseListener)>>,
  58    pub(crate) dispatch_tree: DispatchTree,
  59    pub(crate) scene: Scene,
  60    pub(crate) depth_map: Vec<(StackingOrder, EntityId, Bounds<Pixels>)>,
  61    pub(crate) z_index_stack: StackingOrder,
  62    pub(crate) next_stacking_order_id: u16,
  63    pub(crate) next_root_z_index: u16,
  64    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
  65    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
  66    pub(crate) requested_input_handler: Option<RequestedInputHandler>,
  67    pub(crate) tooltip_request: Option<TooltipRequest>,
  68    pub(crate) cursor_styles: FxHashMap<EntityId, CursorStyle>,
  69    pub(crate) requested_cursor_style: Option<CursorStyle>,
  70    pub(crate) view_stack: Vec<EntityId>,
  71    pub(crate) reused_views: FxHashSet<EntityId>,
  72
  73    #[cfg(any(test, feature = "test-support"))]
  74    pub(crate) debug_bounds: collections::FxHashMap<String, Bounds<Pixels>>,
  75}
  76
  77impl Frame {
  78    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
  79        Frame {
  80            focus: None,
  81            window_active: false,
  82            element_states: FxHashMap::default(),
  83            mouse_listeners: FxHashMap::default(),
  84            dispatch_tree,
  85            scene: Scene::default(),
  86            depth_map: Vec::new(),
  87            z_index_stack: StackingOrder::default(),
  88            next_stacking_order_id: 0,
  89            next_root_z_index: 0,
  90            content_mask_stack: Vec::new(),
  91            element_offset_stack: Vec::new(),
  92            requested_input_handler: None,
  93            tooltip_request: None,
  94            cursor_styles: FxHashMap::default(),
  95            requested_cursor_style: None,
  96            view_stack: Vec::new(),
  97            reused_views: FxHashSet::default(),
  98
  99            #[cfg(any(test, feature = "test-support"))]
 100            debug_bounds: FxHashMap::default(),
 101        }
 102    }
 103
 104    pub(crate) fn clear(&mut self) {
 105        self.element_states.clear();
 106        self.mouse_listeners.values_mut().for_each(Vec::clear);
 107        self.dispatch_tree.clear();
 108        self.depth_map.clear();
 109        self.next_stacking_order_id = 0;
 110        self.next_root_z_index = 0;
 111        self.reused_views.clear();
 112        self.scene.clear();
 113        self.requested_input_handler.take();
 114        self.tooltip_request.take();
 115        self.cursor_styles.clear();
 116        self.requested_cursor_style.take();
 117        debug_assert_eq!(self.view_stack.len(), 0);
 118    }
 119
 120    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
 121        self.focus
 122            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
 123            .unwrap_or_default()
 124    }
 125
 126    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
 127        // Reuse mouse listeners that didn't change since the last frame.
 128        for (type_id, listeners) in &mut prev_frame.mouse_listeners {
 129            let next_listeners = self.mouse_listeners.entry(*type_id).or_default();
 130            for (order, view_id, listener) in listeners.drain(..) {
 131                if self.reused_views.contains(&view_id) {
 132                    next_listeners.push((order, view_id, listener));
 133                }
 134            }
 135        }
 136
 137        // Reuse entries in the depth map that didn't change since the last frame.
 138        for (order, view_id, bounds) in prev_frame.depth_map.drain(..) {
 139            if self.reused_views.contains(&view_id) {
 140                match self
 141                    .depth_map
 142                    .binary_search_by(|(level, _, _)| order.cmp(level))
 143                {
 144                    Ok(i) | Err(i) => self.depth_map.insert(i, (order, view_id, bounds)),
 145                }
 146            }
 147        }
 148
 149        // Retain element states for views that didn't change since the last frame.
 150        for (element_id, state) in prev_frame.element_states.drain() {
 151            if self.reused_views.contains(&state.parent_view_id) {
 152                self.element_states.entry(element_id).or_insert(state);
 153            }
 154        }
 155
 156        // Reuse geometry that didn't change since the last frame.
 157        self.scene
 158            .reuse_views(&self.reused_views, &mut prev_frame.scene);
 159        self.scene.finish();
 160    }
 161}
 162
 163/// This context is used for assisting in the implementation of the element trait
 164#[derive(Deref, DerefMut)]
 165pub struct ElementContext<'a> {
 166    pub(crate) cx: WindowContext<'a>,
 167}
 168
 169impl<'a> WindowContext<'a> {
 170    /// Convert this window context into an ElementContext in this callback.
 171    /// If you need to use this method, you're probably intermixing the imperative
 172    /// and declarative APIs, which is not recommended.
 173    pub fn with_element_context<R>(&mut self, f: impl FnOnce(&mut ElementContext) -> R) -> R {
 174        f(&mut ElementContext {
 175            cx: WindowContext::new(self.app, self.window),
 176        })
 177    }
 178}
 179
 180impl<'a> Borrow<AppContext> for ElementContext<'a> {
 181    fn borrow(&self) -> &AppContext {
 182        self.cx.app
 183    }
 184}
 185
 186impl<'a> BorrowMut<AppContext> for ElementContext<'a> {
 187    fn borrow_mut(&mut self) -> &mut AppContext {
 188        self.cx.borrow_mut()
 189    }
 190}
 191
 192impl<'a> Borrow<WindowContext<'a>> for ElementContext<'a> {
 193    fn borrow(&self) -> &WindowContext<'a> {
 194        &self.cx
 195    }
 196}
 197
 198impl<'a> BorrowMut<WindowContext<'a>> for ElementContext<'a> {
 199    fn borrow_mut(&mut self) -> &mut WindowContext<'a> {
 200        &mut self.cx
 201    }
 202}
 203
 204impl<'a> Borrow<Window> for ElementContext<'a> {
 205    fn borrow(&self) -> &Window {
 206        self.cx.window
 207    }
 208}
 209
 210impl<'a> BorrowMut<Window> for ElementContext<'a> {
 211    fn borrow_mut(&mut self) -> &mut Window {
 212        self.cx.borrow_mut()
 213    }
 214}
 215
 216impl<'a> Context for ElementContext<'a> {
 217    type Result<T> = <WindowContext<'a> as Context>::Result<T>;
 218
 219    fn new_model<T: 'static>(
 220        &mut self,
 221        build_model: impl FnOnce(&mut crate::ModelContext<'_, T>) -> T,
 222    ) -> Self::Result<crate::Model<T>> {
 223        self.cx.new_model(build_model)
 224    }
 225
 226    fn update_model<T, R>(
 227        &mut self,
 228        handle: &crate::Model<T>,
 229        update: impl FnOnce(&mut T, &mut crate::ModelContext<'_, T>) -> R,
 230    ) -> Self::Result<R>
 231    where
 232        T: 'static,
 233    {
 234        self.cx.update_model(handle, update)
 235    }
 236
 237    fn read_model<T, R>(
 238        &self,
 239        handle: &crate::Model<T>,
 240        read: impl FnOnce(&T, &AppContext) -> R,
 241    ) -> Self::Result<R>
 242    where
 243        T: 'static,
 244    {
 245        self.cx.read_model(handle, read)
 246    }
 247
 248    fn update_window<T, F>(&mut self, window: crate::AnyWindowHandle, f: F) -> Result<T>
 249    where
 250        F: FnOnce(crate::AnyView, &mut WindowContext<'_>) -> T,
 251    {
 252        self.cx.update_window(window, f)
 253    }
 254
 255    fn read_window<T, R>(
 256        &self,
 257        window: &crate::WindowHandle<T>,
 258        read: impl FnOnce(crate::View<T>, &AppContext) -> R,
 259    ) -> Result<R>
 260    where
 261        T: 'static,
 262    {
 263        self.cx.read_window(window, read)
 264    }
 265}
 266
 267impl<'a> VisualContext for ElementContext<'a> {
 268    fn new_view<V>(
 269        &mut self,
 270        build_view: impl FnOnce(&mut crate::ViewContext<'_, V>) -> V,
 271    ) -> Self::Result<crate::View<V>>
 272    where
 273        V: 'static + Render,
 274    {
 275        self.cx.new_view(build_view)
 276    }
 277
 278    fn update_view<V: 'static, R>(
 279        &mut self,
 280        view: &crate::View<V>,
 281        update: impl FnOnce(&mut V, &mut crate::ViewContext<'_, V>) -> R,
 282    ) -> Self::Result<R> {
 283        self.cx.update_view(view, update)
 284    }
 285
 286    fn replace_root_view<V>(
 287        &mut self,
 288        build_view: impl FnOnce(&mut crate::ViewContext<'_, V>) -> V,
 289    ) -> Self::Result<crate::View<V>>
 290    where
 291        V: 'static + Render,
 292    {
 293        self.cx.replace_root_view(build_view)
 294    }
 295
 296    fn focus_view<V>(&mut self, view: &crate::View<V>) -> Self::Result<()>
 297    where
 298        V: crate::FocusableView,
 299    {
 300        self.cx.focus_view(view)
 301    }
 302
 303    fn dismiss_view<V>(&mut self, view: &crate::View<V>) -> Self::Result<()>
 304    where
 305        V: crate::ManagedView,
 306    {
 307        self.cx.dismiss_view(view)
 308    }
 309}
 310
 311impl<'a> ElementContext<'a> {
 312    pub(crate) fn reuse_view(&mut self, next_stacking_order_id: u16) {
 313        let view_id = self.parent_view_id();
 314        let grafted_view_ids = self
 315            .cx
 316            .window
 317            .next_frame
 318            .dispatch_tree
 319            .reuse_view(view_id, &mut self.cx.window.rendered_frame.dispatch_tree);
 320        for view_id in grafted_view_ids {
 321            assert!(self.window.next_frame.reused_views.insert(view_id));
 322
 323            // Reuse the previous input handler requested during painting of the reused view.
 324            if self
 325                .window
 326                .rendered_frame
 327                .requested_input_handler
 328                .as_ref()
 329                .map_or(false, |requested| requested.view_id == view_id)
 330            {
 331                self.window.next_frame.requested_input_handler =
 332                    self.window.rendered_frame.requested_input_handler.take();
 333            }
 334
 335            // Reuse the tooltip previously requested during painting of the reused view.
 336            if self
 337                .window
 338                .rendered_frame
 339                .tooltip_request
 340                .as_ref()
 341                .map_or(false, |requested| requested.view_id == view_id)
 342            {
 343                self.window.next_frame.tooltip_request =
 344                    self.window.rendered_frame.tooltip_request.take();
 345            }
 346
 347            // Reuse the cursor styles previously requested during painting of the reused view.
 348            if let Some(style) = self.window.rendered_frame.cursor_styles.remove(&view_id) {
 349                self.window.next_frame.cursor_styles.insert(view_id, style);
 350                self.window.next_frame.requested_cursor_style = Some(style);
 351            }
 352        }
 353
 354        debug_assert!(next_stacking_order_id >= self.window.next_frame.next_stacking_order_id);
 355        self.window.next_frame.next_stacking_order_id = next_stacking_order_id;
 356    }
 357
 358    /// Push a text style onto the stack, and call a function with that style active.
 359    /// Use [`AppContext::text_style`] to get the current, combined text style.
 360    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
 361    where
 362        F: FnOnce(&mut Self) -> R,
 363    {
 364        if let Some(style) = style {
 365            self.push_text_style(style);
 366            let result = f(self);
 367            self.pop_text_style();
 368            result
 369        } else {
 370            f(self)
 371        }
 372    }
 373
 374    /// Updates the cursor style at the platform level.
 375    pub fn set_cursor_style(&mut self, style: CursorStyle) {
 376        let view_id = self.parent_view_id();
 377        self.window.next_frame.cursor_styles.insert(view_id, style);
 378        self.window.next_frame.requested_cursor_style = Some(style);
 379    }
 380
 381    /// Sets a tooltip to be rendered for the upcoming frame
 382    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) {
 383        let view_id = self.parent_view_id();
 384        self.window.next_frame.tooltip_request = Some(TooltipRequest { view_id, tooltip });
 385    }
 386
 387    /// Pushes the given element id onto the global stack and invokes the given closure
 388    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
 389    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
 390    /// used to associate state with identified elements across separate frames.
 391    pub fn with_element_id<R>(
 392        &mut self,
 393        id: Option<impl Into<ElementId>>,
 394        f: impl FnOnce(&mut Self) -> R,
 395    ) -> R {
 396        if let Some(id) = id.map(Into::into) {
 397            let window = self.window_mut();
 398            window.element_id_stack.push(id);
 399            let result = f(self);
 400            let window: &mut Window = self.borrow_mut();
 401            window.element_id_stack.pop();
 402            result
 403        } else {
 404            f(self)
 405        }
 406    }
 407
 408    /// Invoke the given function with the given content mask after intersecting it
 409    /// with the current mask.
 410    pub fn with_content_mask<R>(
 411        &mut self,
 412        mask: Option<ContentMask<Pixels>>,
 413        f: impl FnOnce(&mut Self) -> R,
 414    ) -> R {
 415        if let Some(mask) = mask {
 416            let mask = mask.intersect(&self.content_mask());
 417            self.window_mut().next_frame.content_mask_stack.push(mask);
 418            let result = f(self);
 419            self.window_mut().next_frame.content_mask_stack.pop();
 420            result
 421        } else {
 422            f(self)
 423        }
 424    }
 425
 426    /// Invoke the given function with the content mask reset to that
 427    /// of the window.
 428    pub fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
 429        let mask = ContentMask {
 430            bounds: Bounds {
 431                origin: Point::default(),
 432                size: self.window().viewport_size,
 433            },
 434        };
 435
 436        let new_root_z_index = post_inc(&mut self.window_mut().next_frame.next_root_z_index);
 437        let new_stacking_order_id =
 438            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
 439        let new_context = StackingContext {
 440            z_index: new_root_z_index,
 441            id: new_stacking_order_id,
 442        };
 443
 444        let old_stacking_order = mem::take(&mut self.window_mut().next_frame.z_index_stack);
 445
 446        self.window_mut().next_frame.z_index_stack.push(new_context);
 447        self.window_mut().next_frame.content_mask_stack.push(mask);
 448        let result = f(self);
 449        self.window_mut().next_frame.content_mask_stack.pop();
 450        self.window_mut().next_frame.z_index_stack = old_stacking_order;
 451
 452        result
 453    }
 454
 455    /// Called during painting to invoke the given closure in a new stacking context. The given
 456    /// z-index is interpreted relative to the previous call to `stack`.
 457    pub fn with_z_index<R>(&mut self, z_index: u16, f: impl FnOnce(&mut Self) -> R) -> R {
 458        let new_stacking_order_id =
 459            post_inc(&mut self.window_mut().next_frame.next_stacking_order_id);
 460        let new_context = StackingContext {
 461            z_index,
 462            id: new_stacking_order_id,
 463        };
 464
 465        self.window_mut().next_frame.z_index_stack.push(new_context);
 466        let result = f(self);
 467        self.window_mut().next_frame.z_index_stack.pop();
 468
 469        result
 470    }
 471
 472    /// Updates the global element offset relative to the current offset. This is used to implement
 473    /// scrolling.
 474    pub fn with_element_offset<R>(
 475        &mut self,
 476        offset: Point<Pixels>,
 477        f: impl FnOnce(&mut Self) -> R,
 478    ) -> R {
 479        if offset.is_zero() {
 480            return f(self);
 481        };
 482
 483        let abs_offset = self.element_offset() + offset;
 484        self.with_absolute_element_offset(abs_offset, f)
 485    }
 486
 487    /// Updates the global element offset based on the given offset. This is used to implement
 488    /// drag handles and other manual painting of elements.
 489    pub fn with_absolute_element_offset<R>(
 490        &mut self,
 491        offset: Point<Pixels>,
 492        f: impl FnOnce(&mut Self) -> R,
 493    ) -> R {
 494        self.window_mut()
 495            .next_frame
 496            .element_offset_stack
 497            .push(offset);
 498        let result = f(self);
 499        self.window_mut().next_frame.element_offset_stack.pop();
 500        result
 501    }
 502
 503    /// Obtain the current element offset.
 504    pub fn element_offset(&self) -> Point<Pixels> {
 505        self.window()
 506            .next_frame
 507            .element_offset_stack
 508            .last()
 509            .copied()
 510            .unwrap_or_default()
 511    }
 512
 513    /// Obtain the current content mask.
 514    pub fn content_mask(&self) -> ContentMask<Pixels> {
 515        self.window()
 516            .next_frame
 517            .content_mask_stack
 518            .last()
 519            .cloned()
 520            .unwrap_or_else(|| ContentMask {
 521                bounds: Bounds {
 522                    origin: Point::default(),
 523                    size: self.window().viewport_size,
 524                },
 525            })
 526    }
 527
 528    /// The size of an em for the base font of the application. Adjusting this value allows the
 529    /// UI to scale, just like zooming a web page.
 530    pub fn rem_size(&self) -> Pixels {
 531        self.window().rem_size
 532    }
 533
 534    /// Updates or initializes state for an element with the given id that lives across multiple
 535    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
 536    /// to the given closure. The state returned by the closure will be stored so it can be referenced
 537    /// when drawing the next frame.
 538    pub fn with_element_state<S, R>(
 539        &mut self,
 540        id: ElementId,
 541        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
 542    ) -> R
 543    where
 544        S: 'static,
 545    {
 546        self.with_element_id(Some(id), |cx| {
 547                let global_id = cx.window().element_id_stack.clone();
 548
 549                if let Some(any) = cx
 550                    .window_mut()
 551                    .next_frame
 552                    .element_states
 553                    .remove(&global_id)
 554                    .or_else(|| {
 555                        cx.window_mut()
 556                            .rendered_frame
 557                            .element_states
 558                            .remove(&global_id)
 559                    })
 560                {
 561                    let ElementStateBox {
 562                        inner,
 563                        parent_view_id,
 564                        #[cfg(debug_assertions)]
 565                        type_name
 566                    } = any;
 567                    // Using the extra inner option to avoid needing to reallocate a new box.
 568                    let mut state_box = inner
 569                        .downcast::<Option<S>>()
 570                        .map_err(|_| {
 571                            #[cfg(debug_assertions)]
 572                            {
 573                                anyhow::anyhow!(
 574                                    "invalid element state type for id, requested_type {:?}, actual type: {:?}",
 575                                    std::any::type_name::<S>(),
 576                                    type_name
 577                                )
 578                            }
 579
 580                            #[cfg(not(debug_assertions))]
 581                            {
 582                                anyhow::anyhow!(
 583                                    "invalid element state type for id, requested_type {:?}",
 584                                    std::any::type_name::<S>(),
 585                                )
 586                            }
 587                        })
 588                        .unwrap();
 589
 590                    // Actual: Option<AnyElement> <- View
 591                    // Requested: () <- AnyElement
 592                    let state = state_box
 593                        .take()
 594                        .expect("element state is already on the stack");
 595                    let (result, state) = f(Some(state), cx);
 596                    state_box.replace(state);
 597                    cx.window_mut()
 598                        .next_frame
 599                        .element_states
 600                        .insert(global_id, ElementStateBox {
 601                            inner: state_box,
 602                            parent_view_id,
 603                            #[cfg(debug_assertions)]
 604                            type_name
 605                        });
 606                    result
 607                } else {
 608                    let (result, state) = f(None, cx);
 609                    let parent_view_id = cx.parent_view_id();
 610                    cx.window_mut()
 611                        .next_frame
 612                        .element_states
 613                        .insert(global_id,
 614                            ElementStateBox {
 615                                inner: Box::new(Some(state)),
 616                                parent_view_id,
 617                                #[cfg(debug_assertions)]
 618                                type_name: std::any::type_name::<S>()
 619                            }
 620
 621                        );
 622                    result
 623                }
 624            })
 625    }
 626    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
 627    pub fn paint_shadows(
 628        &mut self,
 629        bounds: Bounds<Pixels>,
 630        corner_radii: Corners<Pixels>,
 631        shadows: &[BoxShadow],
 632    ) {
 633        let scale_factor = self.scale_factor();
 634        let content_mask = self.content_mask();
 635        let view_id = self.parent_view_id();
 636        let window = &mut *self.window;
 637        for shadow in shadows {
 638            let mut shadow_bounds = bounds;
 639            shadow_bounds.origin += shadow.offset;
 640            shadow_bounds.dilate(shadow.spread_radius);
 641            window.next_frame.scene.insert(
 642                &window.next_frame.z_index_stack,
 643                Shadow {
 644                    view_id: view_id.into(),
 645                    layer_id: 0,
 646                    order: 0,
 647                    bounds: shadow_bounds.scale(scale_factor),
 648                    content_mask: content_mask.scale(scale_factor),
 649                    corner_radii: corner_radii.scale(scale_factor),
 650                    color: shadow.color,
 651                    blur_radius: shadow.blur_radius.scale(scale_factor),
 652                },
 653            );
 654        }
 655    }
 656
 657    /// Paint one or more quads into the scene for the next frame at the current stacking context.
 658    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 659    /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
 660    pub fn paint_quad(&mut self, quad: PaintQuad) {
 661        let scale_factor = self.scale_factor();
 662        let content_mask = self.content_mask();
 663        let view_id = self.parent_view_id();
 664
 665        let window = &mut *self.window;
 666        window.next_frame.scene.insert(
 667            &window.next_frame.z_index_stack,
 668            Quad {
 669                view_id: view_id.into(),
 670                layer_id: 0,
 671                order: 0,
 672                bounds: quad.bounds.scale(scale_factor),
 673                content_mask: content_mask.scale(scale_factor),
 674                background: quad.background,
 675                border_color: quad.border_color,
 676                corner_radii: quad.corner_radii.scale(scale_factor),
 677                border_widths: quad.border_widths.scale(scale_factor),
 678            },
 679        );
 680    }
 681
 682    /// Paint the given `Path` into the scene for the next frame at the current z-index.
 683    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 684        let scale_factor = self.scale_factor();
 685        let content_mask = self.content_mask();
 686        let view_id = self.parent_view_id();
 687
 688        path.content_mask = content_mask;
 689        path.color = color.into();
 690        path.view_id = view_id.into();
 691        let window = &mut *self.window;
 692        window
 693            .next_frame
 694            .scene
 695            .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
 696    }
 697
 698    /// Paint an underline into the scene for the next frame at the current z-index.
 699    pub fn paint_underline(
 700        &mut self,
 701        origin: Point<Pixels>,
 702        width: Pixels,
 703        style: &UnderlineStyle,
 704    ) {
 705        let scale_factor = self.scale_factor();
 706        let height = if style.wavy {
 707            style.thickness * 3.
 708        } else {
 709            style.thickness
 710        };
 711        let bounds = Bounds {
 712            origin,
 713            size: size(width, height),
 714        };
 715        let content_mask = self.content_mask();
 716        let view_id = self.parent_view_id();
 717
 718        let window = &mut *self.window;
 719        window.next_frame.scene.insert(
 720            &window.next_frame.z_index_stack,
 721            Underline {
 722                view_id: view_id.into(),
 723                layer_id: 0,
 724                order: 0,
 725                bounds: bounds.scale(scale_factor),
 726                content_mask: content_mask.scale(scale_factor),
 727                thickness: style.thickness.scale(scale_factor),
 728                color: style.color.unwrap_or_default(),
 729                wavy: style.wavy,
 730            },
 731        );
 732    }
 733
 734    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
 735    ///
 736    /// The y component of the origin is the baseline of the glyph.
 737    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
 738    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
 739    /// This method is only useful if you need to paint a single glyph that has already been shaped.
 740    pub fn paint_glyph(
 741        &mut self,
 742        origin: Point<Pixels>,
 743        font_id: FontId,
 744        glyph_id: GlyphId,
 745        font_size: Pixels,
 746        color: Hsla,
 747    ) -> Result<()> {
 748        let scale_factor = self.scale_factor();
 749        let glyph_origin = origin.scale(scale_factor);
 750        let subpixel_variant = Point {
 751            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 752            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 753        };
 754        let params = RenderGlyphParams {
 755            font_id,
 756            glyph_id,
 757            font_size,
 758            subpixel_variant,
 759            scale_factor,
 760            is_emoji: false,
 761        };
 762
 763        let raster_bounds = self.text_system().raster_bounds(&params)?;
 764        if !raster_bounds.is_zero() {
 765            let tile =
 766                self.window
 767                    .sprite_atlas
 768                    .get_or_insert_with(&params.clone().into(), &mut || {
 769                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 770                        Ok((size, Cow::Owned(bytes)))
 771                    })?;
 772            let bounds = Bounds {
 773                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 774                size: tile.bounds.size.map(Into::into),
 775            };
 776            let content_mask = self.content_mask().scale(scale_factor);
 777            let view_id = self.parent_view_id();
 778            let window = &mut *self.window;
 779            window.next_frame.scene.insert(
 780                &window.next_frame.z_index_stack,
 781                MonochromeSprite {
 782                    view_id: view_id.into(),
 783                    layer_id: 0,
 784                    order: 0,
 785                    bounds,
 786                    content_mask,
 787                    color,
 788                    tile,
 789                },
 790            );
 791        }
 792        Ok(())
 793    }
 794
 795    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
 796    ///
 797    /// The y component of the origin is the baseline of the glyph.
 798    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
 799    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
 800    /// This method is only useful if you need to paint a single emoji that has already been shaped.
 801    pub fn paint_emoji(
 802        &mut self,
 803        origin: Point<Pixels>,
 804        font_id: FontId,
 805        glyph_id: GlyphId,
 806        font_size: Pixels,
 807    ) -> Result<()> {
 808        let scale_factor = self.scale_factor();
 809        let glyph_origin = origin.scale(scale_factor);
 810        let params = RenderGlyphParams {
 811            font_id,
 812            glyph_id,
 813            font_size,
 814            // We don't render emojis with subpixel variants.
 815            subpixel_variant: Default::default(),
 816            scale_factor,
 817            is_emoji: true,
 818        };
 819
 820        let raster_bounds = self.text_system().raster_bounds(&params)?;
 821        if !raster_bounds.is_zero() {
 822            let tile =
 823                self.window
 824                    .sprite_atlas
 825                    .get_or_insert_with(&params.clone().into(), &mut || {
 826                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 827                        Ok((size, Cow::Owned(bytes)))
 828                    })?;
 829            let bounds = Bounds {
 830                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 831                size: tile.bounds.size.map(Into::into),
 832            };
 833            let content_mask = self.content_mask().scale(scale_factor);
 834            let view_id = self.parent_view_id();
 835            let window = &mut *self.window;
 836
 837            window.next_frame.scene.insert(
 838                &window.next_frame.z_index_stack,
 839                PolychromeSprite {
 840                    view_id: view_id.into(),
 841                    layer_id: 0,
 842                    order: 0,
 843                    bounds,
 844                    corner_radii: Default::default(),
 845                    content_mask,
 846                    tile,
 847                    grayscale: false,
 848                },
 849            );
 850        }
 851        Ok(())
 852    }
 853
 854    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
 855    pub fn paint_svg(
 856        &mut self,
 857        bounds: Bounds<Pixels>,
 858        path: SharedString,
 859        color: Hsla,
 860    ) -> Result<()> {
 861        let scale_factor = self.scale_factor();
 862        let bounds = bounds.scale(scale_factor);
 863        // Render the SVG at twice the size to get a higher quality result.
 864        let params = RenderSvgParams {
 865            path,
 866            size: bounds
 867                .size
 868                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 869        };
 870
 871        let tile =
 872            self.window
 873                .sprite_atlas
 874                .get_or_insert_with(&params.clone().into(), &mut || {
 875                    let bytes = self.svg_renderer.render(&params)?;
 876                    Ok((params.size, Cow::Owned(bytes)))
 877                })?;
 878        let content_mask = self.content_mask().scale(scale_factor);
 879        let view_id = self.parent_view_id();
 880
 881        let window = &mut *self.window;
 882        window.next_frame.scene.insert(
 883            &window.next_frame.z_index_stack,
 884            MonochromeSprite {
 885                view_id: view_id.into(),
 886                layer_id: 0,
 887                order: 0,
 888                bounds,
 889                content_mask,
 890                color,
 891                tile,
 892            },
 893        );
 894
 895        Ok(())
 896    }
 897
 898    /// Paint an image into the scene for the next frame at the current z-index.
 899    pub fn paint_image(
 900        &mut self,
 901        bounds: Bounds<Pixels>,
 902        corner_radii: Corners<Pixels>,
 903        data: Arc<ImageData>,
 904        grayscale: bool,
 905    ) -> Result<()> {
 906        let scale_factor = self.scale_factor();
 907        let bounds = bounds.scale(scale_factor);
 908        let params = RenderImageParams { image_id: data.id };
 909
 910        let tile = self
 911            .window
 912            .sprite_atlas
 913            .get_or_insert_with(&params.clone().into(), &mut || {
 914                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
 915            })?;
 916        let content_mask = self.content_mask().scale(scale_factor);
 917        let corner_radii = corner_radii.scale(scale_factor);
 918        let view_id = self.parent_view_id();
 919
 920        let window = &mut *self.window;
 921        window.next_frame.scene.insert(
 922            &window.next_frame.z_index_stack,
 923            PolychromeSprite {
 924                view_id: view_id.into(),
 925                layer_id: 0,
 926                order: 0,
 927                bounds,
 928                content_mask,
 929                corner_radii,
 930                tile,
 931                grayscale,
 932            },
 933        );
 934        Ok(())
 935    }
 936
 937    /// Paint a surface into the scene for the next frame at the current z-index.
 938    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
 939        let scale_factor = self.scale_factor();
 940        let bounds = bounds.scale(scale_factor);
 941        let content_mask = self.content_mask().scale(scale_factor);
 942        let view_id = self.parent_view_id();
 943        let window = &mut *self.window;
 944        window.next_frame.scene.insert(
 945            &window.next_frame.z_index_stack,
 946            Surface {
 947                view_id: view_id.into(),
 948                layer_id: 0,
 949                order: 0,
 950                bounds,
 951                content_mask,
 952                image_buffer,
 953            },
 954        );
 955    }
 956
 957    #[must_use]
 958    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 959    /// layout is being requested, along with the layout ids of any children. This method is called during
 960    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 961    pub fn request_layout(
 962        &mut self,
 963        style: &Style,
 964        children: impl IntoIterator<Item = LayoutId>,
 965    ) -> LayoutId {
 966        self.app.layout_id_buffer.clear();
 967        self.app.layout_id_buffer.extend(children);
 968        let rem_size = self.rem_size();
 969
 970        self.cx
 971            .window
 972            .layout_engine
 973            .as_mut()
 974            .unwrap()
 975            .request_layout(style, rem_size, &self.cx.app.layout_id_buffer)
 976    }
 977
 978    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 979    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 980    /// determine the element's size. One place this is used internally is when measuring text.
 981    ///
 982    /// The given closure is invoked at layout time with the known dimensions and available space and
 983    /// returns a `Size`.
 984    pub fn request_measured_layout<
 985        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
 986            + 'static,
 987    >(
 988        &mut self,
 989        style: Style,
 990        measure: F,
 991    ) -> LayoutId {
 992        let rem_size = self.rem_size();
 993        self.window
 994            .layout_engine
 995            .as_mut()
 996            .unwrap()
 997            .request_measured_layout(style, rem_size, measure)
 998    }
 999
1000    /// Compute the layout for the given id within the given available space.
1001    /// This method is called for its side effect, typically by the framework prior to painting.
1002    /// After calling it, you can request the bounds of the given layout node id or any descendant.
1003    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
1004        let mut layout_engine = self.window.layout_engine.take().unwrap();
1005        layout_engine.compute_layout(layout_id, available_space, self);
1006        self.window.layout_engine = Some(layout_engine);
1007    }
1008
1009    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
1010    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
1011    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
1012        let mut bounds = self
1013            .window
1014            .layout_engine
1015            .as_mut()
1016            .unwrap()
1017            .layout_bounds(layout_id)
1018            .map(Into::into);
1019        bounds.origin += self.element_offset();
1020        bounds
1021    }
1022
1023    pub(crate) fn layout_style(&self, layout_id: LayoutId) -> Option<&Style> {
1024        self.window
1025            .layout_engine
1026            .as_ref()
1027            .unwrap()
1028            .requested_style(layout_id)
1029    }
1030
1031    /// Called during painting to track which z-index is on top at each pixel position
1032    pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
1033        let stacking_order = self.window.next_frame.z_index_stack.clone();
1034        let view_id = self.parent_view_id();
1035        let depth_map = &mut self.window.next_frame.depth_map;
1036        match depth_map.binary_search_by(|(level, _, _)| stacking_order.cmp(level)) {
1037            Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, view_id, bounds)),
1038        }
1039    }
1040
1041    /// Invoke the given function with the given focus handle present on the key dispatch stack.
1042    /// If you want an element to participate in key dispatch, use this method to push its key context and focus handle into the stack during paint.
1043    pub fn with_key_dispatch<R>(
1044        &mut self,
1045        context: Option<KeyContext>,
1046        focus_handle: Option<FocusHandle>,
1047        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1048    ) -> R {
1049        let window = &mut self.window;
1050        let focus_id = focus_handle.as_ref().map(|handle| handle.id);
1051        window
1052            .next_frame
1053            .dispatch_tree
1054            .push_node(context.clone(), focus_id, None);
1055
1056        let result = f(focus_handle, self);
1057
1058        self.window.next_frame.dispatch_tree.pop_node();
1059
1060        result
1061    }
1062
1063    /// Invoke the given function with the given view id present on the view stack.
1064    /// This is a fairly low-level method used to layout views.
1065    pub fn with_view_id<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
1066        let text_system = self.text_system().clone();
1067        text_system.with_view(view_id, || {
1068            if self.window.next_frame.view_stack.last() == Some(&view_id) {
1069                f(self)
1070            } else {
1071                self.window.next_frame.view_stack.push(view_id);
1072                let result = f(self);
1073                self.window.next_frame.view_stack.pop();
1074                result
1075            }
1076        })
1077    }
1078
1079    /// Invoke the given function with the given view id present on the view stack.
1080    /// This is a fairly low-level method used to paint views.
1081    pub fn paint_view<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
1082        let text_system = self.text_system().clone();
1083        text_system.with_view(view_id, || {
1084            if self.window.next_frame.view_stack.last() == Some(&view_id) {
1085                f(self)
1086            } else {
1087                self.window.next_frame.view_stack.push(view_id);
1088                self.window
1089                    .next_frame
1090                    .dispatch_tree
1091                    .push_node(None, None, Some(view_id));
1092                let result = f(self);
1093                self.window.next_frame.dispatch_tree.pop_node();
1094                self.window.next_frame.view_stack.pop();
1095                result
1096            }
1097        })
1098    }
1099
1100    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
1101    /// platform to receive textual input with proper integration with concerns such
1102    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
1103    /// rendered.
1104    ///
1105    /// [element_input_handler]: crate::ElementInputHandler
1106    pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
1107        if focus_handle.is_focused(self) {
1108            let view_id = self.parent_view_id();
1109            self.window.next_frame.requested_input_handler = Some(RequestedInputHandler {
1110                view_id,
1111                handler: Some(PlatformInputHandler::new(
1112                    self.to_async(),
1113                    Box::new(input_handler),
1114                )),
1115            })
1116        }
1117    }
1118
1119    /// keymatch mode immediate instructs GPUI to prefer shorter action bindings.
1120    /// In the case that you have a keybinding of `"cmd-k": "terminal::Clear"` and
1121    /// `"cmd-k left": "workspace::MoveLeft"`, GPUI will by default wait for 1s after
1122    /// you type cmd-k to see if you're going to type left.
1123    /// This is problematic in the terminal
1124    pub fn keymatch_mode_immediate(&mut self) {
1125        self.window.next_frame.dispatch_tree.keymatch_mode = KeymatchMode::Immediate;
1126    }
1127
1128    /// Register a mouse event listener on the window for the next frame. The type of event
1129    /// is determined by the first parameter of the given listener. When the next frame is rendered
1130    /// the listener will be cleared.
1131    pub fn on_mouse_event<Event: MouseEvent>(
1132        &mut self,
1133        mut handler: impl FnMut(&Event, DispatchPhase, &mut ElementContext) + 'static,
1134    ) {
1135        let view_id = self.parent_view_id();
1136        let order = self.window.next_frame.z_index_stack.clone();
1137        self.window
1138            .next_frame
1139            .mouse_listeners
1140            .entry(TypeId::of::<Event>())
1141            .or_default()
1142            .push((
1143                order,
1144                view_id,
1145                Box::new(
1146                    move |event: &dyn Any, phase: DispatchPhase, cx: &mut ElementContext<'_>| {
1147                        handler(event.downcast_ref().unwrap(), phase, cx)
1148                    },
1149                ),
1150            ))
1151    }
1152
1153    /// Register a key event listener on the window for the next frame. The type of event
1154    /// is determined by the first parameter of the given listener. When the next frame is rendered
1155    /// the listener will be cleared.
1156    ///
1157    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
1158    /// a specific need to register a global listener.
1159    pub fn on_key_event<Event: KeyEvent>(
1160        &mut self,
1161        listener: impl Fn(&Event, DispatchPhase, &mut ElementContext) + 'static,
1162    ) {
1163        self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
1164            move |event: &dyn Any, phase, cx: &mut ElementContext<'_>| {
1165                if let Some(event) = event.downcast_ref::<Event>() {
1166                    listener(event, phase, cx)
1167                }
1168            },
1169        ));
1170    }
1171}