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`], [`outline`], and [`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    /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
 735    /// The y component of the origin is the baseline of the glyph.
 736    /// You should generally prefer to use the [`ShapedLine::paint`] or [`WrappedLine::paint`] methods in the [`text_system`].
 737    /// This method is only useful if you need to paint a single glyph that has already been shaped.
 738    pub fn paint_glyph(
 739        &mut self,
 740        origin: Point<Pixels>,
 741        font_id: FontId,
 742        glyph_id: GlyphId,
 743        font_size: Pixels,
 744        color: Hsla,
 745    ) -> Result<()> {
 746        let scale_factor = self.scale_factor();
 747        let glyph_origin = origin.scale(scale_factor);
 748        let subpixel_variant = Point {
 749            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 750            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 751        };
 752        let params = RenderGlyphParams {
 753            font_id,
 754            glyph_id,
 755            font_size,
 756            subpixel_variant,
 757            scale_factor,
 758            is_emoji: false,
 759        };
 760
 761        let raster_bounds = self.text_system().raster_bounds(&params)?;
 762        if !raster_bounds.is_zero() {
 763            let tile =
 764                self.window
 765                    .sprite_atlas
 766                    .get_or_insert_with(&params.clone().into(), &mut || {
 767                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 768                        Ok((size, Cow::Owned(bytes)))
 769                    })?;
 770            let bounds = Bounds {
 771                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 772                size: tile.bounds.size.map(Into::into),
 773            };
 774            let content_mask = self.content_mask().scale(scale_factor);
 775            let view_id = self.parent_view_id();
 776            let window = &mut *self.window;
 777            window.next_frame.scene.insert(
 778                &window.next_frame.z_index_stack,
 779                MonochromeSprite {
 780                    view_id: view_id.into(),
 781                    layer_id: 0,
 782                    order: 0,
 783                    bounds,
 784                    content_mask,
 785                    color,
 786                    tile,
 787                },
 788            );
 789        }
 790        Ok(())
 791    }
 792
 793    /// Paint an emoji glyph into the scene for the next frame at the current z-index.
 794    /// The y component of the origin is the baseline of the glyph.
 795    /// You should generally prefer to use the [`ShapedLine::paint`] or [`WrappedLine::paint`] methods in the [`text_system`].
 796    /// This method is only useful if you need to paint a single emoji that has already been shaped.
 797    pub fn paint_emoji(
 798        &mut self,
 799        origin: Point<Pixels>,
 800        font_id: FontId,
 801        glyph_id: GlyphId,
 802        font_size: Pixels,
 803    ) -> Result<()> {
 804        let scale_factor = self.scale_factor();
 805        let glyph_origin = origin.scale(scale_factor);
 806        let params = RenderGlyphParams {
 807            font_id,
 808            glyph_id,
 809            font_size,
 810            // We don't render emojis with subpixel variants.
 811            subpixel_variant: Default::default(),
 812            scale_factor,
 813            is_emoji: true,
 814        };
 815
 816        let raster_bounds = self.text_system().raster_bounds(&params)?;
 817        if !raster_bounds.is_zero() {
 818            let tile =
 819                self.window
 820                    .sprite_atlas
 821                    .get_or_insert_with(&params.clone().into(), &mut || {
 822                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 823                        Ok((size, Cow::Owned(bytes)))
 824                    })?;
 825            let bounds = Bounds {
 826                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 827                size: tile.bounds.size.map(Into::into),
 828            };
 829            let content_mask = self.content_mask().scale(scale_factor);
 830            let view_id = self.parent_view_id();
 831            let window = &mut *self.window;
 832
 833            window.next_frame.scene.insert(
 834                &window.next_frame.z_index_stack,
 835                PolychromeSprite {
 836                    view_id: view_id.into(),
 837                    layer_id: 0,
 838                    order: 0,
 839                    bounds,
 840                    corner_radii: Default::default(),
 841                    content_mask,
 842                    tile,
 843                    grayscale: false,
 844                },
 845            );
 846        }
 847        Ok(())
 848    }
 849
 850    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
 851    pub fn paint_svg(
 852        &mut self,
 853        bounds: Bounds<Pixels>,
 854        path: SharedString,
 855        color: Hsla,
 856    ) -> Result<()> {
 857        let scale_factor = self.scale_factor();
 858        let bounds = bounds.scale(scale_factor);
 859        // Render the SVG at twice the size to get a higher quality result.
 860        let params = RenderSvgParams {
 861            path,
 862            size: bounds
 863                .size
 864                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 865        };
 866
 867        let tile =
 868            self.window
 869                .sprite_atlas
 870                .get_or_insert_with(&params.clone().into(), &mut || {
 871                    let bytes = self.svg_renderer.render(&params)?;
 872                    Ok((params.size, Cow::Owned(bytes)))
 873                })?;
 874        let content_mask = self.content_mask().scale(scale_factor);
 875        let view_id = self.parent_view_id();
 876
 877        let window = &mut *self.window;
 878        window.next_frame.scene.insert(
 879            &window.next_frame.z_index_stack,
 880            MonochromeSprite {
 881                view_id: view_id.into(),
 882                layer_id: 0,
 883                order: 0,
 884                bounds,
 885                content_mask,
 886                color,
 887                tile,
 888            },
 889        );
 890
 891        Ok(())
 892    }
 893
 894    /// Paint an image into the scene for the next frame at the current z-index.
 895    pub fn paint_image(
 896        &mut self,
 897        bounds: Bounds<Pixels>,
 898        corner_radii: Corners<Pixels>,
 899        data: Arc<ImageData>,
 900        grayscale: bool,
 901    ) -> Result<()> {
 902        let scale_factor = self.scale_factor();
 903        let bounds = bounds.scale(scale_factor);
 904        let params = RenderImageParams { image_id: data.id };
 905
 906        let tile = self
 907            .window
 908            .sprite_atlas
 909            .get_or_insert_with(&params.clone().into(), &mut || {
 910                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
 911            })?;
 912        let content_mask = self.content_mask().scale(scale_factor);
 913        let corner_radii = corner_radii.scale(scale_factor);
 914        let view_id = self.parent_view_id();
 915
 916        let window = &mut *self.window;
 917        window.next_frame.scene.insert(
 918            &window.next_frame.z_index_stack,
 919            PolychromeSprite {
 920                view_id: view_id.into(),
 921                layer_id: 0,
 922                order: 0,
 923                bounds,
 924                content_mask,
 925                corner_radii,
 926                tile,
 927                grayscale,
 928            },
 929        );
 930        Ok(())
 931    }
 932
 933    /// Paint a surface into the scene for the next frame at the current z-index.
 934    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
 935        let scale_factor = self.scale_factor();
 936        let bounds = bounds.scale(scale_factor);
 937        let content_mask = self.content_mask().scale(scale_factor);
 938        let view_id = self.parent_view_id();
 939        let window = &mut *self.window;
 940        window.next_frame.scene.insert(
 941            &window.next_frame.z_index_stack,
 942            Surface {
 943                view_id: view_id.into(),
 944                layer_id: 0,
 945                order: 0,
 946                bounds,
 947                content_mask,
 948                image_buffer,
 949            },
 950        );
 951    }
 952
 953    #[must_use]
 954    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 955    /// layout is being requested, along with the layout ids of any children. This method is called during
 956    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 957    pub fn request_layout(
 958        &mut self,
 959        style: &Style,
 960        children: impl IntoIterator<Item = LayoutId>,
 961    ) -> LayoutId {
 962        self.app.layout_id_buffer.clear();
 963        self.app.layout_id_buffer.extend(children);
 964        let rem_size = self.rem_size();
 965
 966        self.cx
 967            .window
 968            .layout_engine
 969            .as_mut()
 970            .unwrap()
 971            .request_layout(style, rem_size, &self.cx.app.layout_id_buffer)
 972    }
 973
 974    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 975    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 976    /// determine the element's size. One place this is used internally is when measuring text.
 977    ///
 978    /// The given closure is invoked at layout time with the known dimensions and available space and
 979    /// returns a `Size`.
 980    pub fn request_measured_layout<
 981        F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
 982            + 'static,
 983    >(
 984        &mut self,
 985        style: Style,
 986        measure: F,
 987    ) -> LayoutId {
 988        let rem_size = self.rem_size();
 989        self.window
 990            .layout_engine
 991            .as_mut()
 992            .unwrap()
 993            .request_measured_layout(style, rem_size, measure)
 994    }
 995
 996    /// Compute the layout for the given id within the given available space.
 997    /// This method is called for its side effect, typically by the framework prior to painting.
 998    /// After calling it, you can request the bounds of the given layout node id or any descendant.
 999    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
1000        let mut layout_engine = self.window.layout_engine.take().unwrap();
1001        layout_engine.compute_layout(layout_id, available_space, self);
1002        self.window.layout_engine = Some(layout_engine);
1003    }
1004
1005    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
1006    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
1007    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
1008        let mut bounds = self
1009            .window
1010            .layout_engine
1011            .as_mut()
1012            .unwrap()
1013            .layout_bounds(layout_id)
1014            .map(Into::into);
1015        bounds.origin += self.element_offset();
1016        bounds
1017    }
1018
1019    pub(crate) fn layout_style(&self, layout_id: LayoutId) -> Option<&Style> {
1020        self.window
1021            .layout_engine
1022            .as_ref()
1023            .unwrap()
1024            .requested_style(layout_id)
1025    }
1026
1027    /// Called during painting to track which z-index is on top at each pixel position
1028    pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
1029        let stacking_order = self.window.next_frame.z_index_stack.clone();
1030        let view_id = self.parent_view_id();
1031        let depth_map = &mut self.window.next_frame.depth_map;
1032        match depth_map.binary_search_by(|(level, _, _)| stacking_order.cmp(level)) {
1033            Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, view_id, bounds)),
1034        }
1035    }
1036
1037    /// Invoke the given function with the given focus handle present on the key dispatch stack.
1038    /// 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.
1039    pub fn with_key_dispatch<R>(
1040        &mut self,
1041        context: Option<KeyContext>,
1042        focus_handle: Option<FocusHandle>,
1043        f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1044    ) -> R {
1045        let window = &mut self.window;
1046        let focus_id = focus_handle.as_ref().map(|handle| handle.id);
1047        window
1048            .next_frame
1049            .dispatch_tree
1050            .push_node(context.clone(), focus_id, None);
1051
1052        let result = f(focus_handle, self);
1053
1054        self.window.next_frame.dispatch_tree.pop_node();
1055
1056        result
1057    }
1058
1059    /// Invoke the given function with the given view id present on the view stack.
1060    /// This is a fairly low-level method used to layout views.
1061    pub fn with_view_id<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
1062        let text_system = self.text_system().clone();
1063        text_system.with_view(view_id, || {
1064            if self.window.next_frame.view_stack.last() == Some(&view_id) {
1065                f(self)
1066            } else {
1067                self.window.next_frame.view_stack.push(view_id);
1068                let result = f(self);
1069                self.window.next_frame.view_stack.pop();
1070                result
1071            }
1072        })
1073    }
1074
1075    /// Invoke the given function with the given view id present on the view stack.
1076    /// This is a fairly low-level method used to paint views.
1077    pub fn paint_view<R>(&mut self, view_id: EntityId, f: impl FnOnce(&mut Self) -> R) -> R {
1078        let text_system = self.text_system().clone();
1079        text_system.with_view(view_id, || {
1080            if self.window.next_frame.view_stack.last() == Some(&view_id) {
1081                f(self)
1082            } else {
1083                self.window.next_frame.view_stack.push(view_id);
1084                self.window
1085                    .next_frame
1086                    .dispatch_tree
1087                    .push_node(None, None, Some(view_id));
1088                let result = f(self);
1089                self.window.next_frame.dispatch_tree.pop_node();
1090                self.window.next_frame.view_stack.pop();
1091                result
1092            }
1093        })
1094    }
1095
1096    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
1097    /// platform to receive textual input with proper integration with concerns such
1098    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
1099    /// rendered.
1100    ///
1101    /// [element_input_handler]: crate::ElementInputHandler
1102    pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
1103        if focus_handle.is_focused(self) {
1104            let view_id = self.parent_view_id();
1105            self.window.next_frame.requested_input_handler = Some(RequestedInputHandler {
1106                view_id,
1107                handler: Some(PlatformInputHandler::new(
1108                    self.to_async(),
1109                    Box::new(input_handler),
1110                )),
1111            })
1112        }
1113    }
1114
1115    /// keymatch mode immediate instructs GPUI to prefer shorter action bindings.
1116    /// In the case that you have a keybinding of `"cmd-k": "terminal::Clear"` and
1117    /// `"cmd-k left": "workspace::MoveLeft"`, GPUI will by default wait for 1s after
1118    /// you type cmd-k to see if you're going to type left.
1119    /// This is problematic in the terminal
1120    pub fn keymatch_mode_immediate(&mut self) {
1121        self.window.next_frame.dispatch_tree.keymatch_mode = KeymatchMode::Immediate;
1122    }
1123
1124    /// Register a mouse event listener on the window for the next frame. The type of event
1125    /// is determined by the first parameter of the given listener. When the next frame is rendered
1126    /// the listener will be cleared.
1127    pub fn on_mouse_event<Event: MouseEvent>(
1128        &mut self,
1129        mut handler: impl FnMut(&Event, DispatchPhase, &mut ElementContext) + 'static,
1130    ) {
1131        let view_id = self.parent_view_id();
1132        let order = self.window.next_frame.z_index_stack.clone();
1133        self.window
1134            .next_frame
1135            .mouse_listeners
1136            .entry(TypeId::of::<Event>())
1137            .or_default()
1138            .push((
1139                order,
1140                view_id,
1141                Box::new(
1142                    move |event: &dyn Any, phase: DispatchPhase, cx: &mut ElementContext<'_>| {
1143                        handler(event.downcast_ref().unwrap(), phase, cx)
1144                    },
1145                ),
1146            ))
1147    }
1148
1149    /// Register a key event listener on the window for the next frame. The type of event
1150    /// is determined by the first parameter of the given listener. When the next frame is rendered
1151    /// the listener will be cleared.
1152    ///
1153    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
1154    /// a specific need to register a global listener.
1155    pub fn on_key_event<Event: KeyEvent>(
1156        &mut self,
1157        listener: impl Fn(&Event, DispatchPhase, &mut ElementContext) + 'static,
1158    ) {
1159        self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
1160            move |event: &dyn Any, phase, cx: &mut ElementContext<'_>| {
1161                if let Some(event) = event.downcast_ref::<Event>() {
1162                    listener(event, phase, cx)
1163                }
1164            },
1165        ));
1166    }
1167}