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 ops::Range,
20 rc::Rc,
21 sync::Arc,
22};
23
24use anyhow::Result;
25use collections::FxHashMap;
26use derive_more::{Deref, DerefMut};
27#[cfg(target_os = "macos")]
28use media::core_video::CVImageBuffer;
29use smallvec::SmallVec;
30
31use crate::{
32 prelude::*, size, AnyElement, AnyTooltip, AppContext, AvailableSpace, Bounds, BoxShadow,
33 ContentMask, Corners, CursorStyle, DevicePixels, DispatchNodeId, DispatchPhase, DispatchTree,
34 DrawPhase, ElementId, ElementStateBox, EntityId, FocusHandle, FocusId, FontId, GlobalElementId,
35 GlyphId, Hsla, ImageData, InputHandler, IsZero, KeyContext, KeyEvent, LayoutId,
36 LineLayoutIndex, MonochromeSprite, MouseEvent, PaintQuad, Path, Pixels, PlatformInputHandler,
37 Point, PolychromeSprite, Quad, RenderGlyphParams, RenderImageParams, RenderSvgParams, Scene,
38 Shadow, SharedString, Size, StrikethroughStyle, Style, TextStyleRefinement, Underline,
39 UnderlineStyle, Window, WindowContext, SUBPIXEL_VARIANTS,
40};
41
42pub(crate) type AnyMouseListener =
43 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut ElementContext) + 'static>;
44
45#[derive(Clone)]
46pub(crate) struct CursorStyleRequest {
47 pub(crate) hitbox_id: HitboxId,
48 pub(crate) style: CursorStyle,
49}
50
51/// An identifier for a [Hitbox].
52#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
53pub struct HitboxId(usize);
54
55impl HitboxId {
56 /// Checks if the hitbox with this id is currently hovered.
57 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
58 cx.window.mouse_hit_test.0.contains(self)
59 }
60}
61
62/// A rectangular region that potentially blocks hitboxes inserted prior.
63/// See [ElementContext::insert_hitbox] for more details.
64#[derive(Clone, Debug, Deref)]
65pub struct Hitbox {
66 /// A unique identifier for the hitbox
67 pub id: HitboxId,
68 /// The bounds of the hitbox
69 #[deref]
70 pub bounds: Bounds<Pixels>,
71 /// Whether the hitbox occludes other hitboxes inserted prior.
72 pub opaque: bool,
73}
74
75impl Hitbox {
76 /// Checks if the hitbox is currently hovered.
77 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
78 self.id.is_hovered(cx)
79 }
80}
81
82#[derive(Default)]
83pub(crate) struct HitTest(SmallVec<[HitboxId; 8]>);
84
85pub(crate) struct DeferredDraw {
86 priority: usize,
87 parent_node: DispatchNodeId,
88 element_id_stack: GlobalElementId,
89 text_style_stack: Vec<TextStyleRefinement>,
90 element: Option<AnyElement>,
91 absolute_offset: Point<Pixels>,
92 layout_range: Range<AfterLayoutIndex>,
93 paint_range: Range<PaintIndex>,
94}
95
96pub(crate) struct Frame {
97 pub(crate) focus: Option<FocusId>,
98 pub(crate) window_active: bool,
99 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
100 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
101 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
102 pub(crate) dispatch_tree: DispatchTree,
103 pub(crate) scene: Scene,
104 pub(crate) hitboxes: Vec<Hitbox>,
105 pub(crate) deferred_draws: Vec<DeferredDraw>,
106 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
107 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
108 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
109 pub(crate) tooltip_requests: Vec<Option<AnyTooltip>>,
110 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
111 #[cfg(any(test, feature = "test-support"))]
112 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
113}
114
115#[derive(Clone, Default)]
116pub(crate) struct AfterLayoutIndex {
117 hitboxes_index: usize,
118 tooltips_index: usize,
119 deferred_draws_index: usize,
120 dispatch_tree_index: usize,
121 accessed_element_states_index: usize,
122 line_layout_index: LineLayoutIndex,
123}
124
125#[derive(Clone, Default)]
126pub(crate) struct PaintIndex {
127 scene_index: usize,
128 mouse_listeners_index: usize,
129 input_handlers_index: usize,
130 cursor_styles_index: usize,
131 accessed_element_states_index: usize,
132 line_layout_index: LineLayoutIndex,
133}
134
135impl Frame {
136 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
137 Frame {
138 focus: None,
139 window_active: false,
140 element_states: FxHashMap::default(),
141 accessed_element_states: Vec::new(),
142 mouse_listeners: Vec::new(),
143 dispatch_tree,
144 scene: Scene::default(),
145 hitboxes: Vec::new(),
146 deferred_draws: Vec::new(),
147 content_mask_stack: Vec::new(),
148 element_offset_stack: Vec::new(),
149 input_handlers: Vec::new(),
150 tooltip_requests: Vec::new(),
151 cursor_styles: Vec::new(),
152
153 #[cfg(any(test, feature = "test-support"))]
154 debug_bounds: FxHashMap::default(),
155 }
156 }
157
158 pub(crate) fn clear(&mut self) {
159 self.element_states.clear();
160 self.accessed_element_states.clear();
161 self.mouse_listeners.clear();
162 self.dispatch_tree.clear();
163 self.scene.clear();
164 self.input_handlers.clear();
165 self.tooltip_requests.clear();
166 self.cursor_styles.clear();
167 self.hitboxes.clear();
168 self.deferred_draws.clear();
169 }
170
171 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
172 let mut hit_test = HitTest::default();
173 for hitbox in self.hitboxes.iter().rev() {
174 if hitbox.bounds.contains(&position) {
175 hit_test.0.push(hitbox.id);
176 if hitbox.opaque {
177 break;
178 }
179 }
180 }
181 hit_test
182 }
183
184 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
185 self.focus
186 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
187 .unwrap_or_default()
188 }
189
190 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
191 for element_state_key in &self.accessed_element_states {
192 if let Some(element_state) = prev_frame.element_states.remove(element_state_key) {
193 self.element_states
194 .insert(element_state_key.clone(), element_state);
195 }
196 }
197
198 self.scene.finish();
199 }
200}
201
202/// This context is used for assisting in the implementation of the element trait
203#[derive(Deref, DerefMut)]
204pub struct ElementContext<'a> {
205 pub(crate) cx: WindowContext<'a>,
206}
207
208impl<'a> WindowContext<'a> {
209 /// Convert this window context into an ElementContext in this callback.
210 /// If you need to use this method, you're probably intermixing the imperative
211 /// and declarative APIs, which is not recommended.
212 pub fn with_element_context<R>(&mut self, f: impl FnOnce(&mut ElementContext) -> R) -> R {
213 f(&mut ElementContext {
214 cx: WindowContext::new(self.app, self.window),
215 })
216 }
217}
218
219impl<'a> Borrow<AppContext> for ElementContext<'a> {
220 fn borrow(&self) -> &AppContext {
221 self.cx.app
222 }
223}
224
225impl<'a> BorrowMut<AppContext> for ElementContext<'a> {
226 fn borrow_mut(&mut self) -> &mut AppContext {
227 self.cx.borrow_mut()
228 }
229}
230
231impl<'a> Borrow<WindowContext<'a>> for ElementContext<'a> {
232 fn borrow(&self) -> &WindowContext<'a> {
233 &self.cx
234 }
235}
236
237impl<'a> BorrowMut<WindowContext<'a>> for ElementContext<'a> {
238 fn borrow_mut(&mut self) -> &mut WindowContext<'a> {
239 &mut self.cx
240 }
241}
242
243impl<'a> Borrow<Window> for ElementContext<'a> {
244 fn borrow(&self) -> &Window {
245 self.cx.window
246 }
247}
248
249impl<'a> BorrowMut<Window> for ElementContext<'a> {
250 fn borrow_mut(&mut self) -> &mut Window {
251 self.cx.borrow_mut()
252 }
253}
254
255impl<'a> Context for ElementContext<'a> {
256 type Result<T> = <WindowContext<'a> as Context>::Result<T>;
257
258 fn new_model<T: 'static>(
259 &mut self,
260 build_model: impl FnOnce(&mut crate::ModelContext<'_, T>) -> T,
261 ) -> Self::Result<crate::Model<T>> {
262 self.cx.new_model(build_model)
263 }
264
265 fn update_model<T, R>(
266 &mut self,
267 handle: &crate::Model<T>,
268 update: impl FnOnce(&mut T, &mut crate::ModelContext<'_, T>) -> R,
269 ) -> Self::Result<R>
270 where
271 T: 'static,
272 {
273 self.cx.update_model(handle, update)
274 }
275
276 fn read_model<T, R>(
277 &self,
278 handle: &crate::Model<T>,
279 read: impl FnOnce(&T, &AppContext) -> R,
280 ) -> Self::Result<R>
281 where
282 T: 'static,
283 {
284 self.cx.read_model(handle, read)
285 }
286
287 fn update_window<T, F>(&mut self, window: crate::AnyWindowHandle, f: F) -> Result<T>
288 where
289 F: FnOnce(crate::AnyView, &mut WindowContext<'_>) -> T,
290 {
291 self.cx.update_window(window, f)
292 }
293
294 fn read_window<T, R>(
295 &self,
296 window: &crate::WindowHandle<T>,
297 read: impl FnOnce(crate::View<T>, &AppContext) -> R,
298 ) -> Result<R>
299 where
300 T: 'static,
301 {
302 self.cx.read_window(window, read)
303 }
304}
305
306impl<'a> VisualContext for ElementContext<'a> {
307 fn new_view<V>(
308 &mut self,
309 build_view: impl FnOnce(&mut crate::ViewContext<'_, V>) -> V,
310 ) -> Self::Result<crate::View<V>>
311 where
312 V: 'static + Render,
313 {
314 self.cx.new_view(build_view)
315 }
316
317 fn update_view<V: 'static, R>(
318 &mut self,
319 view: &crate::View<V>,
320 update: impl FnOnce(&mut V, &mut crate::ViewContext<'_, V>) -> R,
321 ) -> Self::Result<R> {
322 self.cx.update_view(view, update)
323 }
324
325 fn replace_root_view<V>(
326 &mut self,
327 build_view: impl FnOnce(&mut crate::ViewContext<'_, V>) -> V,
328 ) -> Self::Result<crate::View<V>>
329 where
330 V: 'static + Render,
331 {
332 self.cx.replace_root_view(build_view)
333 }
334
335 fn focus_view<V>(&mut self, view: &crate::View<V>) -> Self::Result<()>
336 where
337 V: crate::FocusableView,
338 {
339 self.cx.focus_view(view)
340 }
341
342 fn dismiss_view<V>(&mut self, view: &crate::View<V>) -> Self::Result<()>
343 where
344 V: crate::ManagedView,
345 {
346 self.cx.dismiss_view(view)
347 }
348}
349
350impl<'a> ElementContext<'a> {
351 pub(crate) fn draw_roots(&mut self) {
352 self.window.draw_phase = DrawPhase::Layout;
353
354 // Layout all root elements.
355 let mut root_element = self.window.root_view.as_ref().unwrap().clone().into_any();
356 root_element.layout(Point::default(), self.window.viewport_size.into(), self);
357
358 let mut prompt_element = None;
359 let mut active_drag_element = None;
360 let mut tooltip_element = None;
361 if let Some(prompt) = self.window.prompt.take() {
362 let mut element = prompt.view.any_view().into_any();
363 element.layout(Point::default(), self.window.viewport_size.into(), self);
364 prompt_element = Some(element);
365 self.window.prompt = Some(prompt);
366 } else if let Some(active_drag) = self.app.active_drag.take() {
367 let mut element = active_drag.view.clone().into_any();
368 let offset = self.mouse_position() - active_drag.cursor_offset;
369 element.layout(offset, AvailableSpace::min_size(), self);
370 active_drag_element = Some(element);
371 self.app.active_drag = Some(active_drag);
372 } else if let Some(tooltip_request) =
373 self.window.next_frame.tooltip_requests.last().cloned()
374 {
375 let tooltip_request = tooltip_request.unwrap();
376 let mut element = tooltip_request.view.clone().into_any();
377 let offset = tooltip_request.cursor_offset;
378 element.layout(offset, AvailableSpace::min_size(), self);
379 tooltip_element = Some(element);
380 }
381
382 let mut sorted_deferred_draws =
383 (0..self.window.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
384 sorted_deferred_draws.sort_by_key(|ix| self.window.next_frame.deferred_draws[*ix].priority);
385 self.layout_deferred_draws(&sorted_deferred_draws);
386
387 self.window.mouse_hit_test = self.window.next_frame.hit_test(self.window.mouse_position);
388
389 // Now actually paint the elements.
390 self.window.draw_phase = DrawPhase::Paint;
391 root_element.paint(self);
392
393 if let Some(mut prompt_element) = prompt_element {
394 prompt_element.paint(self)
395 } else if let Some(mut drag_element) = active_drag_element {
396 drag_element.paint(self);
397 } else if let Some(mut tooltip_element) = tooltip_element {
398 tooltip_element.paint(self);
399 }
400
401 self.paint_deferred_draws(&sorted_deferred_draws);
402 }
403
404 fn layout_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
405 assert_eq!(self.window.element_id_stack.len(), 0);
406
407 let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
408 for deferred_draw_ix in deferred_draw_indices {
409 let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
410 self.window.element_id_stack = deferred_draw.element_id_stack.clone();
411 self.window.text_style_stack = deferred_draw.text_style_stack.clone();
412 self.window
413 .next_frame
414 .dispatch_tree
415 .set_active_node(deferred_draw.parent_node);
416
417 let layout_start = self.after_layout_index();
418 if let Some(element) = deferred_draw.element.as_mut() {
419 self.with_absolute_element_offset(deferred_draw.absolute_offset, |cx| {
420 element.after_layout(cx)
421 });
422 } else {
423 self.reuse_after_layout(deferred_draw.layout_range.clone());
424 }
425 let layout_end = self.after_layout_index();
426 deferred_draw.layout_range = layout_start..layout_end;
427 }
428 assert_eq!(
429 self.window.next_frame.deferred_draws.len(),
430 0,
431 "cannot call defer_draw during deferred drawing"
432 );
433 self.window.next_frame.deferred_draws = deferred_draws;
434 self.window.element_id_stack.clear();
435 }
436
437 fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
438 assert_eq!(self.window.element_id_stack.len(), 0);
439
440 let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
441 for deferred_draw_ix in deferred_draw_indices {
442 let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
443 self.window.element_id_stack = deferred_draw.element_id_stack.clone();
444 self.window
445 .next_frame
446 .dispatch_tree
447 .set_active_node(deferred_draw.parent_node);
448
449 let paint_start = self.paint_index();
450 if let Some(element) = deferred_draw.element.as_mut() {
451 element.paint(self);
452 } else {
453 self.reuse_paint(deferred_draw.paint_range.clone());
454 }
455 let paint_end = self.paint_index();
456 deferred_draw.paint_range = paint_start..paint_end;
457 }
458 self.window.next_frame.deferred_draws = deferred_draws;
459 self.window.element_id_stack.clear();
460 }
461
462 pub(crate) fn after_layout_index(&self) -> AfterLayoutIndex {
463 AfterLayoutIndex {
464 hitboxes_index: self.window.next_frame.hitboxes.len(),
465 tooltips_index: self.window.next_frame.tooltip_requests.len(),
466 deferred_draws_index: self.window.next_frame.deferred_draws.len(),
467 dispatch_tree_index: self.window.next_frame.dispatch_tree.len(),
468 accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
469 line_layout_index: self.window.text_system.layout_index(),
470 }
471 }
472
473 pub(crate) fn reuse_after_layout(&mut self, range: Range<AfterLayoutIndex>) {
474 let window = &mut self.window;
475 window.next_frame.hitboxes.extend(
476 window.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
477 .iter()
478 .cloned(),
479 );
480 window.next_frame.tooltip_requests.extend(
481 window.rendered_frame.tooltip_requests
482 [range.start.tooltips_index..range.end.tooltips_index]
483 .iter_mut()
484 .map(|request| request.take()),
485 );
486 window.next_frame.accessed_element_states.extend(
487 window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
488 ..range.end.accessed_element_states_index]
489 .iter()
490 .cloned(),
491 );
492 window
493 .text_system
494 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
495
496 let reused_subtree = window.next_frame.dispatch_tree.reuse_subtree(
497 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
498 &mut window.rendered_frame.dispatch_tree,
499 );
500 window.next_frame.deferred_draws.extend(
501 window.rendered_frame.deferred_draws
502 [range.start.deferred_draws_index..range.end.deferred_draws_index]
503 .iter()
504 .map(|deferred_draw| DeferredDraw {
505 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
506 element_id_stack: deferred_draw.element_id_stack.clone(),
507 text_style_stack: deferred_draw.text_style_stack.clone(),
508 priority: deferred_draw.priority,
509 element: None,
510 absolute_offset: deferred_draw.absolute_offset,
511 layout_range: deferred_draw.layout_range.clone(),
512 paint_range: deferred_draw.paint_range.clone(),
513 }),
514 );
515 }
516
517 pub(crate) fn paint_index(&self) -> PaintIndex {
518 PaintIndex {
519 scene_index: self.window.next_frame.scene.len(),
520 mouse_listeners_index: self.window.next_frame.mouse_listeners.len(),
521 input_handlers_index: self.window.next_frame.input_handlers.len(),
522 cursor_styles_index: self.window.next_frame.cursor_styles.len(),
523 accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
524 line_layout_index: self.window.text_system.layout_index(),
525 }
526 }
527
528 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
529 let window = &mut self.cx.window;
530
531 window.next_frame.cursor_styles.extend(
532 window.rendered_frame.cursor_styles
533 [range.start.cursor_styles_index..range.end.cursor_styles_index]
534 .iter()
535 .cloned(),
536 );
537 window.next_frame.input_handlers.extend(
538 window.rendered_frame.input_handlers
539 [range.start.input_handlers_index..range.end.input_handlers_index]
540 .iter_mut()
541 .map(|handler| handler.take()),
542 );
543 window.next_frame.mouse_listeners.extend(
544 window.rendered_frame.mouse_listeners
545 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
546 .iter_mut()
547 .map(|listener| listener.take()),
548 );
549 window.next_frame.accessed_element_states.extend(
550 window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
551 ..range.end.accessed_element_states_index]
552 .iter()
553 .cloned(),
554 );
555 window
556 .text_system
557 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
558 window.next_frame.scene.replay(
559 range.start.scene_index..range.end.scene_index,
560 &window.rendered_frame.scene,
561 );
562 }
563
564 /// Push a text style onto the stack, and call a function with that style active.
565 /// Use [`AppContext::text_style`] to get the current, combined text style.
566 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
567 where
568 F: FnOnce(&mut Self) -> R,
569 {
570 if let Some(style) = style {
571 self.window.text_style_stack.push(style);
572 let result = f(self);
573 self.window.text_style_stack.pop();
574 result
575 } else {
576 f(self)
577 }
578 }
579
580 /// Updates the cursor style at the platform level.
581 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
582 self.window
583 .next_frame
584 .cursor_styles
585 .push(CursorStyleRequest {
586 hitbox_id: hitbox.id,
587 style,
588 });
589 }
590
591 /// Sets a tooltip to be rendered for the upcoming frame
592 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) {
593 self.window.next_frame.tooltip_requests.push(Some(tooltip));
594 }
595
596 /// Pushes the given element id onto the global stack and invokes the given closure
597 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
598 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
599 /// used to associate state with identified elements across separate frames.
600 pub fn with_element_id<R>(
601 &mut self,
602 id: Option<impl Into<ElementId>>,
603 f: impl FnOnce(&mut Self) -> R,
604 ) -> R {
605 if let Some(id) = id.map(Into::into) {
606 let window = self.window_mut();
607 window.element_id_stack.push(id);
608 let result = f(self);
609 let window: &mut Window = self.borrow_mut();
610 window.element_id_stack.pop();
611 result
612 } else {
613 f(self)
614 }
615 }
616
617 /// Invoke the given function with the given content mask after intersecting it
618 /// with the current mask.
619 pub fn with_content_mask<R>(
620 &mut self,
621 mask: Option<ContentMask<Pixels>>,
622 f: impl FnOnce(&mut Self) -> R,
623 ) -> R {
624 if let Some(mask) = mask {
625 let mask = mask.intersect(&self.content_mask());
626 self.window_mut().next_frame.content_mask_stack.push(mask);
627 let result = f(self);
628 self.window_mut().next_frame.content_mask_stack.pop();
629 result
630 } else {
631 f(self)
632 }
633 }
634
635 /// Updates the global element offset relative to the current offset. This is used to implement
636 /// scrolling.
637 pub fn with_element_offset<R>(
638 &mut self,
639 offset: Point<Pixels>,
640 f: impl FnOnce(&mut Self) -> R,
641 ) -> R {
642 if offset.is_zero() {
643 return f(self);
644 };
645
646 let abs_offset = self.element_offset() + offset;
647 self.with_absolute_element_offset(abs_offset, f)
648 }
649
650 /// Updates the global element offset based on the given offset. This is used to implement
651 /// drag handles and other manual painting of elements.
652 pub fn with_absolute_element_offset<R>(
653 &mut self,
654 offset: Point<Pixels>,
655 f: impl FnOnce(&mut Self) -> R,
656 ) -> R {
657 self.window_mut()
658 .next_frame
659 .element_offset_stack
660 .push(offset);
661 let result = f(self);
662 self.window_mut().next_frame.element_offset_stack.pop();
663 result
664 }
665
666 /// Obtain the current element offset.
667 pub fn element_offset(&self) -> Point<Pixels> {
668 self.window()
669 .next_frame
670 .element_offset_stack
671 .last()
672 .copied()
673 .unwrap_or_default()
674 }
675
676 /// Obtain the current content mask.
677 pub fn content_mask(&self) -> ContentMask<Pixels> {
678 self.window()
679 .next_frame
680 .content_mask_stack
681 .last()
682 .cloned()
683 .unwrap_or_else(|| ContentMask {
684 bounds: Bounds {
685 origin: Point::default(),
686 size: self.window().viewport_size,
687 },
688 })
689 }
690
691 /// The size of an em for the base font of the application. Adjusting this value allows the
692 /// UI to scale, just like zooming a web page.
693 pub fn rem_size(&self) -> Pixels {
694 self.window().rem_size
695 }
696
697 /// Updates or initializes state for an element with the given id that lives across multiple
698 /// frames. If an element with this ID existed in the rendered frame, its state will be passed
699 /// to the given closure. The state returned by the closure will be stored so it can be referenced
700 /// when drawing the next frame.
701 pub fn with_element_state<S, R>(
702 &mut self,
703 element_id: Option<ElementId>,
704 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
705 ) -> R
706 where
707 S: 'static,
708 {
709 let id_is_none = element_id.is_none();
710 self.with_element_id(element_id, |cx| {
711 if id_is_none {
712 let (result, state) = f(None, cx);
713 debug_assert!(state.is_none(), "you must not return an element state when passing None for the element id");
714 result
715 } else {
716 let global_id = cx.window().element_id_stack.clone();
717 let key = (global_id, TypeId::of::<S>());
718 cx.window.next_frame.accessed_element_states.push(key.clone());
719
720 if let Some(any) = cx
721 .window_mut()
722 .next_frame
723 .element_states
724 .remove(&key)
725 .or_else(|| {
726 cx.window_mut()
727 .rendered_frame
728 .element_states
729 .remove(&key)
730 })
731 {
732 let ElementStateBox {
733 inner,
734 #[cfg(debug_assertions)]
735 type_name
736 } = any;
737 // Using the extra inner option to avoid needing to reallocate a new box.
738 let mut state_box = inner
739 .downcast::<Option<S>>()
740 .map_err(|_| {
741 #[cfg(debug_assertions)]
742 {
743 anyhow::anyhow!(
744 "invalid element state type for id, requested_type {:?}, actual type: {:?}",
745 std::any::type_name::<S>(),
746 type_name
747 )
748 }
749
750 #[cfg(not(debug_assertions))]
751 {
752 anyhow::anyhow!(
753 "invalid element state type for id, requested_type {:?}",
754 std::any::type_name::<S>(),
755 )
756 }
757 })
758 .unwrap();
759
760 // Actual: Option<AnyElement> <- View
761 // Requested: () <- AnyElement
762 let state = state_box
763 .take()
764 .expect("reentrant call to with_element_state for the same state type and element id");
765 let (result, state) = f(Some(Some(state)), cx);
766 state_box.replace(state.expect("you must return "));
767 cx.window_mut()
768 .next_frame
769 .element_states
770 .insert(key, ElementStateBox {
771 inner: state_box,
772 #[cfg(debug_assertions)]
773 type_name
774 });
775 result
776 } else {
777 let (result, state) = f(Some(None), cx);
778 cx.window_mut()
779 .next_frame
780 .element_states
781 .insert(key,
782 ElementStateBox {
783 inner: Box::new(Some(state.expect("you must return Some<State> when you pass some element id"))),
784 #[cfg(debug_assertions)]
785 type_name: std::any::type_name::<S>()
786 }
787
788 );
789 result
790 }
791 }
792 })
793 }
794
795 /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
796 /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
797 /// with higher values being drawn on top.
798 pub fn defer_draw(
799 &mut self,
800 element: AnyElement,
801 absolute_offset: Point<Pixels>,
802 priority: usize,
803 ) {
804 let window = &mut self.cx.window;
805 assert_eq!(
806 window.draw_phase,
807 DrawPhase::Layout,
808 "defer_draw can only be called during before_layout or after_layout"
809 );
810 let parent_node = window.next_frame.dispatch_tree.active_node_id().unwrap();
811 window.next_frame.deferred_draws.push(DeferredDraw {
812 parent_node,
813 element_id_stack: window.element_id_stack.clone(),
814 text_style_stack: window.text_style_stack.clone(),
815 priority,
816 element: Some(element),
817 absolute_offset,
818 layout_range: AfterLayoutIndex::default()..AfterLayoutIndex::default(),
819 paint_range: PaintIndex::default()..PaintIndex::default(),
820 });
821 }
822
823 /// Creates a new painting layer for the specified bounds. A "layer" is a batch
824 /// of geometry that are non-overlapping and have the same draw order. This is typically used
825 /// for performance reasons.
826 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
827 let scale_factor = self.scale_factor();
828 let content_mask = self.content_mask();
829 let clipped_bounds = bounds.intersect(&content_mask.bounds);
830 if !clipped_bounds.is_empty() {
831 self.window
832 .next_frame
833 .scene
834 .push_layer(clipped_bounds.scale(scale_factor));
835 }
836
837 let result = f(self);
838
839 if !clipped_bounds.is_empty() {
840 self.window.next_frame.scene.pop_layer();
841 }
842
843 result
844 }
845
846 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
847 pub fn paint_shadows(
848 &mut self,
849 bounds: Bounds<Pixels>,
850 corner_radii: Corners<Pixels>,
851 shadows: &[BoxShadow],
852 ) {
853 let scale_factor = self.scale_factor();
854 let content_mask = self.content_mask();
855 for shadow in shadows {
856 let mut shadow_bounds = bounds;
857 shadow_bounds.origin += shadow.offset;
858 shadow_bounds.dilate(shadow.spread_radius);
859 self.window.next_frame.scene.insert_primitive(Shadow {
860 order: 0,
861 blur_radius: shadow.blur_radius.scale(scale_factor),
862 bounds: shadow_bounds.scale(scale_factor),
863 content_mask: content_mask.scale(scale_factor),
864 corner_radii: corner_radii.scale(scale_factor),
865 color: shadow.color,
866 });
867 }
868 }
869
870 /// Paint one or more quads into the scene for the next frame at the current stacking context.
871 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
872 /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
873 pub fn paint_quad(&mut self, quad: PaintQuad) {
874 let scale_factor = self.scale_factor();
875 let content_mask = self.content_mask();
876 self.window.next_frame.scene.insert_primitive(Quad {
877 order: 0,
878 pad: 0,
879 bounds: quad.bounds.scale(scale_factor),
880 content_mask: content_mask.scale(scale_factor),
881 background: quad.background,
882 border_color: quad.border_color,
883 corner_radii: quad.corner_radii.scale(scale_factor),
884 border_widths: quad.border_widths.scale(scale_factor),
885 });
886 }
887
888 /// Paint the given `Path` into the scene for the next frame at the current z-index.
889 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
890 let scale_factor = self.scale_factor();
891 let content_mask = self.content_mask();
892 path.content_mask = content_mask;
893 path.color = color.into();
894 self.window
895 .next_frame
896 .scene
897 .insert_primitive(path.scale(scale_factor));
898 }
899
900 /// Paint an underline into the scene for the next frame at the current z-index.
901 pub fn paint_underline(
902 &mut self,
903 origin: Point<Pixels>,
904 width: Pixels,
905 style: &UnderlineStyle,
906 ) {
907 let scale_factor = self.scale_factor();
908 let height = if style.wavy {
909 style.thickness * 3.
910 } else {
911 style.thickness
912 };
913 let bounds = Bounds {
914 origin,
915 size: size(width, height),
916 };
917 let content_mask = self.content_mask();
918
919 self.window.next_frame.scene.insert_primitive(Underline {
920 order: 0,
921 pad: 0,
922 bounds: bounds.scale(scale_factor),
923 content_mask: content_mask.scale(scale_factor),
924 color: style.color.unwrap_or_default(),
925 thickness: style.thickness.scale(scale_factor),
926 wavy: style.wavy,
927 });
928 }
929
930 /// Paint a strikethrough into the scene for the next frame at the current z-index.
931 pub fn paint_strikethrough(
932 &mut self,
933 origin: Point<Pixels>,
934 width: Pixels,
935 style: &StrikethroughStyle,
936 ) {
937 let scale_factor = self.scale_factor();
938 let height = style.thickness;
939 let bounds = Bounds {
940 origin,
941 size: size(width, height),
942 };
943 let content_mask = self.content_mask();
944
945 self.window.next_frame.scene.insert_primitive(Underline {
946 order: 0,
947 pad: 0,
948 bounds: bounds.scale(scale_factor),
949 content_mask: content_mask.scale(scale_factor),
950 thickness: style.thickness.scale(scale_factor),
951 color: style.color.unwrap_or_default(),
952 wavy: false,
953 });
954 }
955
956 /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
957 ///
958 /// The y component of the origin is the baseline of the glyph.
959 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
960 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
961 /// This method is only useful if you need to paint a single glyph that has already been shaped.
962 pub fn paint_glyph(
963 &mut self,
964 origin: Point<Pixels>,
965 font_id: FontId,
966 glyph_id: GlyphId,
967 font_size: Pixels,
968 color: Hsla,
969 ) -> Result<()> {
970 let scale_factor = self.scale_factor();
971 let glyph_origin = origin.scale(scale_factor);
972 let subpixel_variant = Point {
973 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
974 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
975 };
976 let params = RenderGlyphParams {
977 font_id,
978 glyph_id,
979 font_size,
980 subpixel_variant,
981 scale_factor,
982 is_emoji: false,
983 };
984
985 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
986 if !raster_bounds.is_zero() {
987 let tile =
988 self.window
989 .sprite_atlas
990 .get_or_insert_with(¶ms.clone().into(), &mut || {
991 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
992 Ok((size, Cow::Owned(bytes)))
993 })?;
994 let bounds = Bounds {
995 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
996 size: tile.bounds.size.map(Into::into),
997 };
998 let content_mask = self.content_mask().scale(scale_factor);
999 self.window
1000 .next_frame
1001 .scene
1002 .insert_primitive(MonochromeSprite {
1003 order: 0,
1004 pad: 0,
1005 bounds,
1006 content_mask,
1007 color,
1008 tile,
1009 });
1010 }
1011 Ok(())
1012 }
1013
1014 /// Paints an emoji glyph into the scene for the next frame at the current z-index.
1015 ///
1016 /// The y component of the origin is the baseline of the glyph.
1017 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
1018 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
1019 /// This method is only useful if you need to paint a single emoji that has already been shaped.
1020 pub fn paint_emoji(
1021 &mut self,
1022 origin: Point<Pixels>,
1023 font_id: FontId,
1024 glyph_id: GlyphId,
1025 font_size: Pixels,
1026 ) -> Result<()> {
1027 let scale_factor = self.scale_factor();
1028 let glyph_origin = origin.scale(scale_factor);
1029 let params = RenderGlyphParams {
1030 font_id,
1031 glyph_id,
1032 font_size,
1033 // We don't render emojis with subpixel variants.
1034 subpixel_variant: Default::default(),
1035 scale_factor,
1036 is_emoji: true,
1037 };
1038
1039 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1040 if !raster_bounds.is_zero() {
1041 let tile =
1042 self.window
1043 .sprite_atlas
1044 .get_or_insert_with(¶ms.clone().into(), &mut || {
1045 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1046 Ok((size, Cow::Owned(bytes)))
1047 })?;
1048 let bounds = Bounds {
1049 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1050 size: tile.bounds.size.map(Into::into),
1051 };
1052 let content_mask = self.content_mask().scale(scale_factor);
1053
1054 self.window
1055 .next_frame
1056 .scene
1057 .insert_primitive(PolychromeSprite {
1058 order: 0,
1059 grayscale: false,
1060 bounds,
1061 corner_radii: Default::default(),
1062 content_mask,
1063 tile,
1064 });
1065 }
1066 Ok(())
1067 }
1068
1069 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1070 pub fn paint_svg(
1071 &mut self,
1072 bounds: Bounds<Pixels>,
1073 path: SharedString,
1074 color: Hsla,
1075 ) -> Result<()> {
1076 let scale_factor = self.scale_factor();
1077 let bounds = bounds.scale(scale_factor);
1078 // Render the SVG at twice the size to get a higher quality result.
1079 let params = RenderSvgParams {
1080 path,
1081 size: bounds
1082 .size
1083 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1084 };
1085
1086 let tile =
1087 self.window
1088 .sprite_atlas
1089 .get_or_insert_with(¶ms.clone().into(), &mut || {
1090 let bytes = self.svg_renderer.render(¶ms)?;
1091 Ok((params.size, Cow::Owned(bytes)))
1092 })?;
1093 let content_mask = self.content_mask().scale(scale_factor);
1094
1095 self.window
1096 .next_frame
1097 .scene
1098 .insert_primitive(MonochromeSprite {
1099 order: 0,
1100 pad: 0,
1101 bounds,
1102 content_mask,
1103 color,
1104 tile,
1105 });
1106
1107 Ok(())
1108 }
1109
1110 /// Paint an image into the scene for the next frame at the current z-index.
1111 pub fn paint_image(
1112 &mut self,
1113 bounds: Bounds<Pixels>,
1114 corner_radii: Corners<Pixels>,
1115 data: Arc<ImageData>,
1116 grayscale: bool,
1117 ) -> Result<()> {
1118 let scale_factor = self.scale_factor();
1119 let bounds = bounds.scale(scale_factor);
1120 let params = RenderImageParams { image_id: data.id };
1121
1122 let tile = self
1123 .window
1124 .sprite_atlas
1125 .get_or_insert_with(¶ms.clone().into(), &mut || {
1126 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1127 })?;
1128 let content_mask = self.content_mask().scale(scale_factor);
1129 let corner_radii = corner_radii.scale(scale_factor);
1130
1131 self.window
1132 .next_frame
1133 .scene
1134 .insert_primitive(PolychromeSprite {
1135 order: 0,
1136 grayscale,
1137 bounds,
1138 content_mask,
1139 corner_radii,
1140 tile,
1141 });
1142 Ok(())
1143 }
1144
1145 /// Paint a surface into the scene for the next frame at the current z-index.
1146 #[cfg(target_os = "macos")]
1147 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1148 let scale_factor = self.scale_factor();
1149 let bounds = bounds.scale(scale_factor);
1150 let content_mask = self.content_mask().scale(scale_factor);
1151 self.window
1152 .next_frame
1153 .scene
1154 .insert_primitive(crate::Surface {
1155 order: 0,
1156 bounds,
1157 content_mask,
1158 image_buffer,
1159 });
1160 }
1161
1162 #[must_use]
1163 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
1164 /// layout is being requested, along with the layout ids of any children. This method is called during
1165 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
1166 pub fn request_layout(
1167 &mut self,
1168 style: &Style,
1169 children: impl IntoIterator<Item = LayoutId>,
1170 ) -> LayoutId {
1171 self.app.layout_id_buffer.clear();
1172 self.app.layout_id_buffer.extend(children);
1173 let rem_size = self.rem_size();
1174
1175 self.cx
1176 .window
1177 .layout_engine
1178 .as_mut()
1179 .unwrap()
1180 .before_layout(style, rem_size, &self.cx.app.layout_id_buffer)
1181 }
1182
1183 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
1184 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
1185 /// determine the element's size. One place this is used internally is when measuring text.
1186 ///
1187 /// The given closure is invoked at layout time with the known dimensions and available space and
1188 /// returns a `Size`.
1189 pub fn request_measured_layout<
1190 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
1191 + 'static,
1192 >(
1193 &mut self,
1194 style: Style,
1195 measure: F,
1196 ) -> LayoutId {
1197 let rem_size = self.rem_size();
1198 self.window
1199 .layout_engine
1200 .as_mut()
1201 .unwrap()
1202 .request_measured_layout(style, rem_size, measure)
1203 }
1204
1205 /// Compute the layout for the given id within the given available space.
1206 /// This method is called for its side effect, typically by the framework prior to painting.
1207 /// After calling it, you can request the bounds of the given layout node id or any descendant.
1208 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
1209 let mut layout_engine = self.window.layout_engine.take().unwrap();
1210 layout_engine.compute_layout(layout_id, available_space, self);
1211 self.window.layout_engine = Some(layout_engine);
1212 }
1213
1214 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
1215 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
1216 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
1217 let mut bounds = self
1218 .window
1219 .layout_engine
1220 .as_mut()
1221 .unwrap()
1222 .layout_bounds(layout_id)
1223 .map(Into::into);
1224 bounds.origin += self.element_offset();
1225 bounds
1226 }
1227
1228 /// This method should be called during `after_layout`. You can use
1229 /// the returned [Hitbox] during `paint` or in an event handler
1230 /// to determine whether the inserted hitbox was the topmost.
1231 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
1232 let content_mask = self.content_mask();
1233 let window = &mut self.window;
1234 let id = window.next_hitbox_id;
1235 window.next_hitbox_id.0 += 1;
1236 let hitbox = Hitbox {
1237 id,
1238 bounds: bounds.intersect(&content_mask.bounds),
1239 opaque,
1240 };
1241 window.next_frame.hitboxes.push(hitbox.clone());
1242 hitbox
1243 }
1244
1245 /// Sets the key context for the current element. This context will be used to translate
1246 /// keybindings into actions.
1247 pub fn set_key_context(&mut self, context: KeyContext) {
1248 self.window
1249 .next_frame
1250 .dispatch_tree
1251 .set_key_context(context);
1252 }
1253
1254 /// Sets the focus handle for the current element. This handle will be used to manage focus state
1255 /// and keyboard event dispatch for the element.
1256 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
1257 self.window
1258 .next_frame
1259 .dispatch_tree
1260 .set_focus_id(focus_handle.id);
1261 }
1262
1263 /// Sets the view id for the current element, which will be used to manage view caching.
1264 pub fn set_view_id(&mut self, view_id: EntityId) {
1265 self.window.next_frame.dispatch_tree.set_view_id(view_id);
1266 }
1267
1268 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
1269 /// platform to receive textual input with proper integration with concerns such
1270 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
1271 /// rendered.
1272 ///
1273 /// [element_input_handler]: crate::ElementInputHandler
1274 pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
1275 if focus_handle.is_focused(self) {
1276 let cx = self.to_async();
1277 self.window
1278 .next_frame
1279 .input_handlers
1280 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
1281 }
1282 }
1283
1284 /// Register a mouse event listener on the window for the next frame. The type of event
1285 /// is determined by the first parameter of the given listener. When the next frame is rendered
1286 /// the listener will be cleared.
1287 pub fn on_mouse_event<Event: MouseEvent>(
1288 &mut self,
1289 mut handler: impl FnMut(&Event, DispatchPhase, &mut ElementContext) + 'static,
1290 ) {
1291 self.window.next_frame.mouse_listeners.push(Some(Box::new(
1292 move |event: &dyn Any, phase: DispatchPhase, cx: &mut ElementContext<'_>| {
1293 if let Some(event) = event.downcast_ref() {
1294 handler(event, phase, cx)
1295 }
1296 },
1297 )));
1298 }
1299
1300 /// Register a key event listener on the window for the next frame. The type of event
1301 /// is determined by the first parameter of the given listener. When the next frame is rendered
1302 /// the listener will be cleared.
1303 ///
1304 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
1305 /// a specific need to register a global listener.
1306 pub fn on_key_event<Event: KeyEvent>(
1307 &mut self,
1308 listener: impl Fn(&Event, DispatchPhase, &mut ElementContext) + 'static,
1309 ) {
1310 self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
1311 move |event: &dyn Any, phase, cx: &mut ElementContext<'_>| {
1312 if let Some(event) = event.downcast_ref::<Event>() {
1313 listener(event, phase, cx)
1314 }
1315 },
1316 ));
1317 }
1318}