1use crate::{
2 hash, point, prelude::*, px, size, transparent_black, Action, AnyDrag, AnyElement, AnyTooltip,
3 AnyView, AppContext, Arena, Asset, AsyncWindowContext, AvailableSpace, Bounds, BoxShadow,
4 Context, Corners, CursorStyle, DevicePixels, DispatchActionListener, DispatchNodeId,
5 DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, Flatten,
6 FontId, Global, GlobalElementId, GlyphId, Hsla, ImageData, InputHandler, IsZero, KeyBinding,
7 KeyContext, KeyDownEvent, KeyEvent, KeyMatch, KeymatchResult, Keystroke, KeystrokeEvent,
8 LayoutId, LineLayoutIndex, Model, ModelContext, Modifiers, ModifiersChangedEvent,
9 MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
10 PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
11 PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams,
12 RenderSvgParams, ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style,
13 SubscriberSet, Subscription, TaffyLayoutEngine, Task, TextStyle, TextStyleRefinement,
14 TransformationMatrix, Underline, UnderlineStyle, View, VisualContext, WeakView,
15 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowOptions, WindowParams,
16 WindowTextSystem, SUBPIXEL_VARIANTS,
17};
18use anyhow::{anyhow, Context as _, Result};
19use collections::{FxHashMap, FxHashSet};
20use derive_more::{Deref, DerefMut};
21use futures::channel::oneshot;
22use futures::{future::Shared, FutureExt};
23#[cfg(target_os = "macos")]
24use media::core_video::CVImageBuffer;
25use parking_lot::RwLock;
26use refineable::Refineable;
27use slotmap::SlotMap;
28use smallvec::SmallVec;
29use std::{
30 any::{Any, TypeId},
31 borrow::{Borrow, BorrowMut, Cow},
32 cell::{Cell, RefCell},
33 cmp,
34 fmt::{Debug, Display},
35 future::Future,
36 hash::{Hash, Hasher},
37 marker::PhantomData,
38 mem,
39 ops::Range,
40 rc::Rc,
41 sync::{
42 atomic::{AtomicUsize, Ordering::SeqCst},
43 Arc, Weak,
44 },
45 time::{Duration, Instant},
46};
47use util::post_inc;
48use util::{measure, ResultExt};
49use uuid::Uuid;
50
51mod prompts;
52
53pub use prompts::*;
54
55pub(crate) const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1024.), px(700.));
56
57/// Represents the two different phases when dispatching events.
58#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
59pub enum DispatchPhase {
60 /// After the capture phase comes the bubble phase, in which mouse event listeners are
61 /// invoked front to back and keyboard event listeners are invoked from the focused element
62 /// to the root of the element tree. This is the phase you'll most commonly want to use when
63 /// registering event listeners.
64 #[default]
65 Bubble,
66 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
67 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
68 /// is used for special purposes such as clearing the "pressed" state for click events. If
69 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
70 /// outside of the immediate region may rely on detecting non-local events during this phase.
71 Capture,
72}
73
74impl DispatchPhase {
75 /// Returns true if this represents the "bubble" phase.
76 pub fn bubble(self) -> bool {
77 self == DispatchPhase::Bubble
78 }
79
80 /// Returns true if this represents the "capture" phase.
81 pub fn capture(self) -> bool {
82 self == DispatchPhase::Capture
83 }
84}
85
86type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
87
88type AnyWindowFocusListener =
89 Box<dyn FnMut(&WindowFocusEvent, &mut WindowContext) -> bool + 'static>;
90
91struct WindowFocusEvent {
92 previous_focus_path: SmallVec<[FocusId; 8]>,
93 current_focus_path: SmallVec<[FocusId; 8]>,
94}
95
96impl WindowFocusEvent {
97 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
98 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
99 }
100
101 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
102 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
103 }
104}
105
106/// This is provided when subscribing for `ViewContext::on_focus_out` events.
107pub struct FocusOutEvent {
108 /// A weak focus handle representing what was blurred.
109 pub blurred: WeakFocusHandle,
110}
111
112slotmap::new_key_type! {
113 /// A globally unique identifier for a focusable element.
114 pub struct FocusId;
115}
116
117thread_local! {
118 /// 8MB wasn't quite enough...
119 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(32 * 1024 * 1024));
120}
121
122impl FocusId {
123 /// Obtains whether the element associated with this handle is currently focused.
124 pub fn is_focused(&self, cx: &WindowContext) -> bool {
125 cx.window.focus == Some(*self)
126 }
127
128 /// Obtains whether the element associated with this handle contains the focused
129 /// element or is itself focused.
130 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
131 cx.focused()
132 .map_or(false, |focused| self.contains(focused.id, cx))
133 }
134
135 /// Obtains whether the element associated with this handle is contained within the
136 /// focused element or is itself focused.
137 pub fn within_focused(&self, cx: &WindowContext) -> bool {
138 let focused = cx.focused();
139 focused.map_or(false, |focused| focused.id.contains(*self, cx))
140 }
141
142 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
143 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
144 cx.window
145 .rendered_frame
146 .dispatch_tree
147 .focus_contains(*self, other)
148 }
149}
150
151/// A handle which can be used to track and manipulate the focused element in a window.
152pub struct FocusHandle {
153 pub(crate) id: FocusId,
154 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
155}
156
157impl std::fmt::Debug for FocusHandle {
158 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
160 }
161}
162
163impl FocusHandle {
164 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
165 let id = handles.write().insert(AtomicUsize::new(1));
166 Self {
167 id,
168 handles: handles.clone(),
169 }
170 }
171
172 pub(crate) fn for_id(
173 id: FocusId,
174 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
175 ) -> Option<Self> {
176 let lock = handles.read();
177 let ref_count = lock.get(id)?;
178 if ref_count.load(SeqCst) == 0 {
179 None
180 } else {
181 ref_count.fetch_add(1, SeqCst);
182 Some(Self {
183 id,
184 handles: handles.clone(),
185 })
186 }
187 }
188
189 /// Converts this focus handle into a weak variant, which does not prevent it from being released.
190 pub fn downgrade(&self) -> WeakFocusHandle {
191 WeakFocusHandle {
192 id: self.id,
193 handles: Arc::downgrade(&self.handles),
194 }
195 }
196
197 /// Moves the focus to the element associated with this handle.
198 pub fn focus(&self, cx: &mut WindowContext) {
199 cx.focus(self)
200 }
201
202 /// Obtains whether the element associated with this handle is currently focused.
203 pub fn is_focused(&self, cx: &WindowContext) -> bool {
204 self.id.is_focused(cx)
205 }
206
207 /// Obtains whether the element associated with this handle contains the focused
208 /// element or is itself focused.
209 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
210 self.id.contains_focused(cx)
211 }
212
213 /// Obtains whether the element associated with this handle is contained within the
214 /// focused element or is itself focused.
215 pub fn within_focused(&self, cx: &WindowContext) -> bool {
216 self.id.within_focused(cx)
217 }
218
219 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
220 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
221 self.id.contains(other.id, cx)
222 }
223
224 /// Dispatch an action on the element that rendered this focus handle
225 pub fn dispatch_action(&self, action: &dyn Action, cx: &mut WindowContext) {
226 if let Some(node_id) = cx
227 .window
228 .rendered_frame
229 .dispatch_tree
230 .focusable_node_id(self.id)
231 {
232 cx.dispatch_action_on_node(node_id, action)
233 }
234 }
235}
236
237impl Clone for FocusHandle {
238 fn clone(&self) -> Self {
239 Self::for_id(self.id, &self.handles).unwrap()
240 }
241}
242
243impl PartialEq for FocusHandle {
244 fn eq(&self, other: &Self) -> bool {
245 self.id == other.id
246 }
247}
248
249impl Eq for FocusHandle {}
250
251impl Drop for FocusHandle {
252 fn drop(&mut self) {
253 self.handles
254 .read()
255 .get(self.id)
256 .unwrap()
257 .fetch_sub(1, SeqCst);
258 }
259}
260
261/// A weak reference to a focus handle.
262#[derive(Clone, Debug)]
263pub struct WeakFocusHandle {
264 pub(crate) id: FocusId,
265 handles: Weak<RwLock<SlotMap<FocusId, AtomicUsize>>>,
266}
267
268impl WeakFocusHandle {
269 /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
270 pub fn upgrade(&self) -> Option<FocusHandle> {
271 let handles = self.handles.upgrade()?;
272 FocusHandle::for_id(self.id, &handles)
273 }
274}
275
276impl PartialEq for WeakFocusHandle {
277 fn eq(&self, other: &WeakFocusHandle) -> bool {
278 self.id == other.id
279 }
280}
281
282impl Eq for WeakFocusHandle {}
283
284impl PartialEq<FocusHandle> for WeakFocusHandle {
285 fn eq(&self, other: &FocusHandle) -> bool {
286 self.id == other.id
287 }
288}
289
290impl PartialEq<WeakFocusHandle> for FocusHandle {
291 fn eq(&self, other: &WeakFocusHandle) -> bool {
292 self.id == other.id
293 }
294}
295
296/// FocusableView allows users of your view to easily
297/// focus it (using cx.focus_view(view))
298pub trait FocusableView: 'static + Render {
299 /// Returns the focus handle associated with this view.
300 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
301}
302
303/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
304/// where the lifecycle of the view is handled by another view.
305pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
306
307impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
308
309/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
310pub struct DismissEvent;
311
312type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
313
314pub(crate) type AnyMouseListener =
315 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
316
317#[derive(Clone)]
318pub(crate) struct CursorStyleRequest {
319 pub(crate) hitbox_id: HitboxId,
320 pub(crate) style: CursorStyle,
321}
322
323/// An identifier for a [Hitbox].
324#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
325pub struct HitboxId(usize);
326
327impl HitboxId {
328 /// Checks if the hitbox with this id is currently hovered.
329 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
330 cx.window.mouse_hit_test.0.contains(self)
331 }
332}
333
334/// A rectangular region that potentially blocks hitboxes inserted prior.
335/// See [WindowContext::insert_hitbox] for more details.
336#[derive(Clone, Debug, Deref)]
337pub struct Hitbox {
338 /// A unique identifier for the hitbox.
339 pub id: HitboxId,
340 /// The bounds of the hitbox.
341 #[deref]
342 pub bounds: Bounds<Pixels>,
343 /// The content mask when the hitbox was inserted.
344 pub content_mask: ContentMask<Pixels>,
345 /// Whether the hitbox occludes other hitboxes inserted prior.
346 pub opaque: bool,
347}
348
349impl Hitbox {
350 /// Checks if the hitbox is currently hovered.
351 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
352 self.id.is_hovered(cx)
353 }
354}
355
356#[derive(Default, Eq, PartialEq)]
357pub(crate) struct HitTest(SmallVec<[HitboxId; 8]>);
358
359/// An identifier for a tooltip.
360#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
361pub struct TooltipId(usize);
362
363impl TooltipId {
364 /// Checks if the tooltip is currently hovered.
365 pub fn is_hovered(&self, cx: &WindowContext) -> bool {
366 cx.window
367 .tooltip_bounds
368 .as_ref()
369 .map_or(false, |tooltip_bounds| {
370 tooltip_bounds.id == *self && tooltip_bounds.bounds.contains(&cx.mouse_position())
371 })
372 }
373}
374
375pub(crate) struct TooltipBounds {
376 id: TooltipId,
377 bounds: Bounds<Pixels>,
378}
379
380#[derive(Clone)]
381pub(crate) struct TooltipRequest {
382 id: TooltipId,
383 tooltip: AnyTooltip,
384}
385
386pub(crate) struct DeferredDraw {
387 priority: usize,
388 parent_node: DispatchNodeId,
389 element_id_stack: SmallVec<[ElementId; 32]>,
390 text_style_stack: Vec<TextStyleRefinement>,
391 element: Option<AnyElement>,
392 absolute_offset: Point<Pixels>,
393 prepaint_range: Range<PrepaintStateIndex>,
394 paint_range: Range<PaintIndex>,
395}
396
397pub(crate) struct Frame {
398 pub(crate) focus: Option<FocusId>,
399 pub(crate) window_active: bool,
400 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
401 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
402 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
403 pub(crate) dispatch_tree: DispatchTree,
404 pub(crate) scene: Scene,
405 pub(crate) hitboxes: Vec<Hitbox>,
406 pub(crate) deferred_draws: Vec<DeferredDraw>,
407 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
408 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
409 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
410 #[cfg(any(test, feature = "test-support"))]
411 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
412}
413
414#[derive(Clone, Default)]
415pub(crate) struct PrepaintStateIndex {
416 hitboxes_index: usize,
417 tooltips_index: usize,
418 deferred_draws_index: usize,
419 dispatch_tree_index: usize,
420 accessed_element_states_index: usize,
421 line_layout_index: LineLayoutIndex,
422}
423
424#[derive(Clone, Default)]
425pub(crate) struct PaintIndex {
426 scene_index: usize,
427 mouse_listeners_index: usize,
428 input_handlers_index: usize,
429 cursor_styles_index: usize,
430 accessed_element_states_index: usize,
431 line_layout_index: LineLayoutIndex,
432}
433
434impl Frame {
435 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
436 Frame {
437 focus: None,
438 window_active: false,
439 element_states: FxHashMap::default(),
440 accessed_element_states: Vec::new(),
441 mouse_listeners: Vec::new(),
442 dispatch_tree,
443 scene: Scene::default(),
444 hitboxes: Vec::new(),
445 deferred_draws: Vec::new(),
446 input_handlers: Vec::new(),
447 tooltip_requests: Vec::new(),
448 cursor_styles: Vec::new(),
449
450 #[cfg(any(test, feature = "test-support"))]
451 debug_bounds: FxHashMap::default(),
452 }
453 }
454
455 pub(crate) fn clear(&mut self) {
456 self.element_states.clear();
457 self.accessed_element_states.clear();
458 self.mouse_listeners.clear();
459 self.dispatch_tree.clear();
460 self.scene.clear();
461 self.input_handlers.clear();
462 self.tooltip_requests.clear();
463 self.cursor_styles.clear();
464 self.hitboxes.clear();
465 self.deferred_draws.clear();
466 }
467
468 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
469 let mut hit_test = HitTest::default();
470 for hitbox in self.hitboxes.iter().rev() {
471 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
472 if bounds.contains(&position) {
473 hit_test.0.push(hitbox.id);
474 if hitbox.opaque {
475 break;
476 }
477 }
478 }
479 hit_test
480 }
481
482 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
483 self.focus
484 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
485 .unwrap_or_default()
486 }
487
488 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
489 for element_state_key in &self.accessed_element_states {
490 if let Some((element_state_key, element_state)) =
491 prev_frame.element_states.remove_entry(element_state_key)
492 {
493 self.element_states.insert(element_state_key, element_state);
494 }
495 }
496
497 self.scene.finish();
498 }
499}
500
501// Holds the state for a specific window.
502#[doc(hidden)]
503pub struct Window {
504 pub(crate) handle: AnyWindowHandle,
505 pub(crate) removed: bool,
506 pub(crate) platform_window: Box<dyn PlatformWindow>,
507 display_id: Option<DisplayId>,
508 sprite_atlas: Arc<dyn PlatformAtlas>,
509 text_system: Arc<WindowTextSystem>,
510 rem_size: Pixels,
511 /// The stack of override values for the window's rem size.
512 ///
513 /// This is used by `with_rem_size` to allow rendering an element tree with
514 /// a given rem size.
515 rem_size_override_stack: SmallVec<[Pixels; 8]>,
516 pub(crate) viewport_size: Size<Pixels>,
517 layout_engine: Option<TaffyLayoutEngine>,
518 pub(crate) root_view: Option<AnyView>,
519 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
520 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
521 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
522 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
523 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
524 pub(crate) rendered_frame: Frame,
525 pub(crate) next_frame: Frame,
526 pub(crate) next_hitbox_id: HitboxId,
527 pub(crate) next_tooltip_id: TooltipId,
528 pub(crate) tooltip_bounds: Option<TooltipBounds>,
529 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
530 pub(crate) dirty_views: FxHashSet<EntityId>,
531 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
532 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
533 focus_lost_listeners: SubscriberSet<(), AnyObserver>,
534 default_prevented: bool,
535 mouse_position: Point<Pixels>,
536 mouse_hit_test: HitTest,
537 modifiers: Modifiers,
538 scale_factor: f32,
539 bounds_observers: SubscriberSet<(), AnyObserver>,
540 appearance: WindowAppearance,
541 appearance_observers: SubscriberSet<(), AnyObserver>,
542 active: Rc<Cell<bool>>,
543 pub(crate) dirty: Rc<Cell<bool>>,
544 pub(crate) needs_present: Rc<Cell<bool>>,
545 pub(crate) last_input_timestamp: Rc<Cell<Instant>>,
546 pub(crate) refreshing: bool,
547 pub(crate) draw_phase: DrawPhase,
548 activation_observers: SubscriberSet<(), AnyObserver>,
549 pub(crate) focus: Option<FocusId>,
550 focus_enabled: bool,
551 pending_input: Option<PendingInput>,
552 pending_input_observers: SubscriberSet<(), AnyObserver>,
553 prompt: Option<RenderablePromptHandle>,
554}
555
556#[derive(Clone, Copy, Debug, Eq, PartialEq)]
557pub(crate) enum DrawPhase {
558 None,
559 Prepaint,
560 Paint,
561 Focus,
562}
563
564#[derive(Default, Debug)]
565struct PendingInput {
566 keystrokes: SmallVec<[Keystroke; 1]>,
567 bindings: SmallVec<[KeyBinding; 1]>,
568 focus: Option<FocusId>,
569 timer: Option<Task<()>>,
570}
571
572impl PendingInput {
573 fn input(&self) -> String {
574 self.keystrokes
575 .iter()
576 .flat_map(|k| k.ime_key.clone())
577 .collect::<Vec<String>>()
578 .join("")
579 }
580
581 fn used_by_binding(&self, binding: &KeyBinding) -> bool {
582 if self.keystrokes.is_empty() {
583 return true;
584 }
585 let keystroke = &self.keystrokes[0];
586 for candidate in keystroke.match_candidates() {
587 if binding.match_keystrokes(&[candidate]) == KeyMatch::Pending {
588 return true;
589 }
590 }
591 false
592 }
593}
594
595pub(crate) struct ElementStateBox {
596 pub(crate) inner: Box<dyn Any>,
597 #[cfg(debug_assertions)]
598 pub(crate) type_name: &'static str,
599}
600
601fn default_bounds(display_id: Option<DisplayId>, cx: &mut AppContext) -> Bounds<Pixels> {
602 const DEFAULT_WINDOW_OFFSET: Point<Pixels> = point(px(0.), px(35.));
603
604 cx.active_window()
605 .and_then(|w| w.update(cx, |_, cx| cx.bounds()).ok())
606 .map(|bounds| bounds.map_origin(|origin| origin + DEFAULT_WINDOW_OFFSET))
607 .unwrap_or_else(|| {
608 let display = display_id
609 .map(|id| cx.find_display(id))
610 .unwrap_or_else(|| cx.primary_display());
611
612 display
613 .map(|display| display.default_bounds())
614 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE))
615 })
616}
617
618impl Window {
619 pub(crate) fn new(
620 handle: AnyWindowHandle,
621 options: WindowOptions,
622 cx: &mut AppContext,
623 ) -> Result<Self> {
624 let WindowOptions {
625 window_bounds,
626 titlebar,
627 focus,
628 show,
629 kind,
630 is_movable,
631 display_id,
632 window_background,
633 app_id,
634 } = options;
635
636 let bounds = window_bounds
637 .map(|bounds| bounds.get_bounds())
638 .unwrap_or_else(|| default_bounds(display_id, cx));
639 let mut platform_window = cx.platform.open_window(
640 handle,
641 WindowParams {
642 bounds,
643 titlebar,
644 kind,
645 is_movable,
646 focus,
647 show,
648 display_id,
649 window_background,
650 },
651 )?;
652 let display_id = platform_window.display().map(|display| display.id());
653 let sprite_atlas = platform_window.sprite_atlas();
654 let mouse_position = platform_window.mouse_position();
655 let modifiers = platform_window.modifiers();
656 let content_size = platform_window.content_size();
657 let scale_factor = platform_window.scale_factor();
658 let appearance = platform_window.appearance();
659 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
660 let dirty = Rc::new(Cell::new(true));
661 let active = Rc::new(Cell::new(platform_window.is_active()));
662 let needs_present = Rc::new(Cell::new(false));
663 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
664 let last_input_timestamp = Rc::new(Cell::new(Instant::now()));
665
666 if let Some(ref window_open_state) = window_bounds {
667 match window_open_state {
668 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
669 WindowBounds::Maximized(_) => platform_window.zoom(),
670 WindowBounds::Windowed(_) => {}
671 }
672 }
673
674 platform_window.on_close(Box::new({
675 let mut cx = cx.to_async();
676 move || {
677 let _ = handle.update(&mut cx, |_, cx| cx.remove_window());
678 }
679 }));
680 platform_window.on_request_frame(Box::new({
681 let mut cx = cx.to_async();
682 let dirty = dirty.clone();
683 let active = active.clone();
684 let needs_present = needs_present.clone();
685 let next_frame_callbacks = next_frame_callbacks.clone();
686 let last_input_timestamp = last_input_timestamp.clone();
687 move || {
688 let next_frame_callbacks = next_frame_callbacks.take();
689 if !next_frame_callbacks.is_empty() {
690 handle
691 .update(&mut cx, |_, cx| {
692 for callback in next_frame_callbacks {
693 callback(cx);
694 }
695 })
696 .log_err();
697 }
698
699 // Keep presenting the current scene for 1 extra second since the
700 // last input to prevent the display from underclocking the refresh rate.
701 let needs_present = needs_present.get()
702 || (active.get()
703 && last_input_timestamp.get().elapsed() < Duration::from_secs(1));
704
705 if dirty.get() {
706 measure("frame duration", || {
707 handle
708 .update(&mut cx, |_, cx| {
709 cx.draw();
710 cx.present();
711 })
712 .log_err();
713 })
714 } else if needs_present {
715 handle.update(&mut cx, |_, cx| cx.present()).log_err();
716 }
717
718 handle
719 .update(&mut cx, |_, cx| {
720 cx.complete_frame();
721 })
722 .log_err();
723 }
724 }));
725 platform_window.on_resize(Box::new({
726 let mut cx = cx.to_async();
727 move |_, _| {
728 handle
729 .update(&mut cx, |_, cx| cx.bounds_changed())
730 .log_err();
731 }
732 }));
733 platform_window.on_moved(Box::new({
734 let mut cx = cx.to_async();
735 move || {
736 handle
737 .update(&mut cx, |_, cx| cx.bounds_changed())
738 .log_err();
739 }
740 }));
741 platform_window.on_appearance_changed(Box::new({
742 let mut cx = cx.to_async();
743 move || {
744 handle
745 .update(&mut cx, |_, cx| cx.appearance_changed())
746 .log_err();
747 }
748 }));
749 platform_window.on_active_status_change(Box::new({
750 let mut cx = cx.to_async();
751 move |active| {
752 handle
753 .update(&mut cx, |_, cx| {
754 cx.window.active.set(active);
755 cx.window
756 .activation_observers
757 .clone()
758 .retain(&(), |callback| callback(cx));
759 cx.refresh();
760 })
761 .log_err();
762 }
763 }));
764
765 platform_window.on_input({
766 let mut cx = cx.to_async();
767 Box::new(move |event| {
768 handle
769 .update(&mut cx, |_, cx| cx.dispatch_event(event))
770 .log_err()
771 .unwrap_or(DispatchEventResult::default())
772 })
773 });
774
775 if let Some(app_id) = app_id {
776 platform_window.set_app_id(&app_id);
777 }
778
779 Ok(Window {
780 handle,
781 removed: false,
782 platform_window,
783 display_id,
784 sprite_atlas,
785 text_system,
786 rem_size: px(16.),
787 rem_size_override_stack: SmallVec::new(),
788 viewport_size: content_size,
789 layout_engine: Some(TaffyLayoutEngine::new()),
790 root_view: None,
791 element_id_stack: SmallVec::default(),
792 text_style_stack: Vec::new(),
793 element_offset_stack: Vec::new(),
794 content_mask_stack: Vec::new(),
795 requested_autoscroll: None,
796 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
797 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
798 next_frame_callbacks,
799 next_hitbox_id: HitboxId::default(),
800 next_tooltip_id: TooltipId::default(),
801 tooltip_bounds: None,
802 dirty_views: FxHashSet::default(),
803 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
804 focus_listeners: SubscriberSet::new(),
805 focus_lost_listeners: SubscriberSet::new(),
806 default_prevented: true,
807 mouse_position,
808 mouse_hit_test: HitTest::default(),
809 modifiers,
810 scale_factor,
811 bounds_observers: SubscriberSet::new(),
812 appearance,
813 appearance_observers: SubscriberSet::new(),
814 active,
815 dirty,
816 needs_present,
817 last_input_timestamp,
818 refreshing: false,
819 draw_phase: DrawPhase::None,
820 activation_observers: SubscriberSet::new(),
821 focus: None,
822 focus_enabled: true,
823 pending_input: None,
824 pending_input_observers: SubscriberSet::new(),
825 prompt: None,
826 })
827 }
828 fn new_focus_listener(
829 &mut self,
830 value: AnyWindowFocusListener,
831 ) -> (Subscription, impl FnOnce()) {
832 self.focus_listeners.insert((), value)
833 }
834}
835
836#[derive(Clone, Debug, Default, PartialEq, Eq)]
837pub(crate) struct DispatchEventResult {
838 pub propagate: bool,
839 pub default_prevented: bool,
840}
841
842/// Indicates which region of the window is visible. Content falling outside of this mask will not be
843/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
844/// to leave room to support more complex shapes in the future.
845#[derive(Clone, Debug, Default, PartialEq, Eq)]
846#[repr(C)]
847pub struct ContentMask<P: Clone + Default + Debug> {
848 /// The bounds
849 pub bounds: Bounds<P>,
850}
851
852impl ContentMask<Pixels> {
853 /// Scale the content mask's pixel units by the given scaling factor.
854 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
855 ContentMask {
856 bounds: self.bounds.scale(factor),
857 }
858 }
859
860 /// Intersect the content mask with the given content mask.
861 pub fn intersect(&self, other: &Self) -> Self {
862 let bounds = self.bounds.intersect(&other.bounds);
863 ContentMask { bounds }
864 }
865}
866
867/// Provides access to application state in the context of a single window. Derefs
868/// to an [`AppContext`], so you can also pass a [`WindowContext`] to any method that takes
869/// an [`AppContext`] and call any [`AppContext`] methods.
870pub struct WindowContext<'a> {
871 pub(crate) app: &'a mut AppContext,
872 pub(crate) window: &'a mut Window,
873}
874
875impl<'a> WindowContext<'a> {
876 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
877 Self { app, window }
878 }
879
880 /// Obtain a handle to the window that belongs to this context.
881 pub fn window_handle(&self) -> AnyWindowHandle {
882 self.window.handle
883 }
884
885 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
886 pub fn refresh(&mut self) {
887 if self.window.draw_phase == DrawPhase::None {
888 self.window.refreshing = true;
889 self.window.dirty.set(true);
890 }
891 }
892
893 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
894 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
895 pub fn notify(&mut self, view_id: EntityId) {
896 for view_id in self
897 .window
898 .rendered_frame
899 .dispatch_tree
900 .view_path(view_id)
901 .into_iter()
902 .rev()
903 {
904 if !self.window.dirty_views.insert(view_id) {
905 break;
906 }
907 }
908
909 if self.window.draw_phase == DrawPhase::None {
910 self.window.dirty.set(true);
911 self.app.push_effect(Effect::Notify { emitter: view_id });
912 }
913 }
914
915 /// Close this window.
916 pub fn remove_window(&mut self) {
917 self.window.removed = true;
918 }
919
920 /// Obtain a new [`FocusHandle`], which allows you to track and manipulate the keyboard focus
921 /// for elements rendered within this window.
922 pub fn focus_handle(&mut self) -> FocusHandle {
923 FocusHandle::new(&self.window.focus_handles)
924 }
925
926 /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
927 pub fn focused(&self) -> Option<FocusHandle> {
928 self.window
929 .focus
930 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
931 }
932
933 /// Move focus to the element associated with the given [`FocusHandle`].
934 pub fn focus(&mut self, handle: &FocusHandle) {
935 if !self.window.focus_enabled || self.window.focus == Some(handle.id) {
936 return;
937 }
938
939 self.window.focus = Some(handle.id);
940 self.window
941 .rendered_frame
942 .dispatch_tree
943 .clear_pending_keystrokes();
944 self.refresh();
945 }
946
947 /// Remove focus from all elements within this context's window.
948 pub fn blur(&mut self) {
949 if !self.window.focus_enabled {
950 return;
951 }
952
953 self.window.focus = None;
954 self.refresh();
955 }
956
957 /// Blur the window and don't allow anything in it to be focused again.
958 pub fn disable_focus(&mut self) {
959 self.blur();
960 self.window.focus_enabled = false;
961 }
962
963 /// Accessor for the text system.
964 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
965 &self.window.text_system
966 }
967
968 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
969 pub fn text_style(&self) -> TextStyle {
970 let mut style = TextStyle::default();
971 for refinement in &self.window.text_style_stack {
972 style.refine(refinement);
973 }
974 style
975 }
976
977 /// Check if the platform window is maximized
978 /// On some platforms (namely Windows) this is different than the bounds being the size of the display
979 pub fn is_maximized(&self) -> bool {
980 self.window.platform_window.is_maximized()
981 }
982
983 /// Return the `WindowBounds` to indicate that how a window should be opened
984 /// after it has been closed
985 pub fn window_bounds(&self) -> WindowBounds {
986 self.window.platform_window.window_bounds()
987 }
988
989 /// Dispatch the given action on the currently focused element.
990 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
991 let focus_handle = self.focused();
992
993 let window = self.window.handle;
994 self.app.defer(move |cx| {
995 window
996 .update(cx, |_, cx| {
997 let node_id = focus_handle
998 .and_then(|handle| {
999 cx.window
1000 .rendered_frame
1001 .dispatch_tree
1002 .focusable_node_id(handle.id)
1003 })
1004 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
1005
1006 cx.dispatch_action_on_node(node_id, action.as_ref());
1007 })
1008 .log_err();
1009 })
1010 }
1011
1012 pub(crate) fn dispatch_keystroke_observers(
1013 &mut self,
1014 event: &dyn Any,
1015 action: Option<Box<dyn Action>>,
1016 ) {
1017 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1018 return;
1019 };
1020
1021 self.keystroke_observers
1022 .clone()
1023 .retain(&(), move |callback| {
1024 (callback)(
1025 &KeystrokeEvent {
1026 keystroke: key_down_event.keystroke.clone(),
1027 action: action.as_ref().map(|action| action.boxed_clone()),
1028 },
1029 self,
1030 );
1031 true
1032 });
1033 }
1034
1035 pub(crate) fn clear_pending_keystrokes(&mut self) {
1036 self.window
1037 .rendered_frame
1038 .dispatch_tree
1039 .clear_pending_keystrokes();
1040 self.window
1041 .next_frame
1042 .dispatch_tree
1043 .clear_pending_keystrokes();
1044 }
1045
1046 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1047 /// that are currently on the stack to be returned to the app.
1048 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
1049 let handle = self.window.handle;
1050 self.app.defer(move |cx| {
1051 handle.update(cx, |_, cx| f(cx)).ok();
1052 });
1053 }
1054
1055 /// Subscribe to events emitted by a model or view.
1056 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1057 /// The callback will be invoked a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a window context for the current window.
1058 pub fn observe<E, T>(
1059 &mut self,
1060 entity: &E,
1061 mut on_notify: impl FnMut(E, &mut WindowContext<'_>) + 'static,
1062 ) -> Subscription
1063 where
1064 E: Entity<T>,
1065 {
1066 let entity_id = entity.entity_id();
1067 let entity = entity.downgrade();
1068 let window_handle = self.window.handle;
1069 self.app.new_observer(
1070 entity_id,
1071 Box::new(move |cx| {
1072 window_handle
1073 .update(cx, |_, cx| {
1074 if let Some(handle) = E::upgrade_from(&entity) {
1075 on_notify(handle, cx);
1076 true
1077 } else {
1078 false
1079 }
1080 })
1081 .unwrap_or(false)
1082 }),
1083 )
1084 }
1085
1086 /// Subscribe to events emitted by a model or view.
1087 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1088 /// The callback will be invoked a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a window context for the current window.
1089 pub fn subscribe<Emitter, E, Evt>(
1090 &mut self,
1091 entity: &E,
1092 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
1093 ) -> Subscription
1094 where
1095 Emitter: EventEmitter<Evt>,
1096 E: Entity<Emitter>,
1097 Evt: 'static,
1098 {
1099 let entity_id = entity.entity_id();
1100 let entity = entity.downgrade();
1101 let window_handle = self.window.handle;
1102 self.app.new_subscription(
1103 entity_id,
1104 (
1105 TypeId::of::<Evt>(),
1106 Box::new(move |event, cx| {
1107 window_handle
1108 .update(cx, |_, cx| {
1109 if let Some(handle) = E::upgrade_from(&entity) {
1110 let event = event.downcast_ref().expect("invalid event type");
1111 on_event(handle, event, cx);
1112 true
1113 } else {
1114 false
1115 }
1116 })
1117 .unwrap_or(false)
1118 }),
1119 ),
1120 )
1121 }
1122
1123 /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
1124 /// await points in async code.
1125 pub fn to_async(&self) -> AsyncWindowContext {
1126 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
1127 }
1128
1129 /// Schedule the given closure to be run directly after the current frame is rendered.
1130 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
1131 RefCell::borrow_mut(&self.window.next_frame_callbacks).push(Box::new(callback));
1132 }
1133
1134 /// Spawn the future returned by the given closure on the application thread pool.
1135 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
1136 /// use within your future.
1137 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
1138 where
1139 R: 'static,
1140 Fut: Future<Output = R> + 'static,
1141 {
1142 self.app
1143 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
1144 }
1145
1146 fn bounds_changed(&mut self) {
1147 self.window.scale_factor = self.window.platform_window.scale_factor();
1148 self.window.viewport_size = self.window.platform_window.content_size();
1149 self.window.display_id = self
1150 .window
1151 .platform_window
1152 .display()
1153 .map(|display| display.id());
1154
1155 self.refresh();
1156
1157 self.window
1158 .bounds_observers
1159 .clone()
1160 .retain(&(), |callback| callback(self));
1161 }
1162
1163 /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
1164 pub fn bounds(&self) -> Bounds<Pixels> {
1165 self.window.platform_window.bounds()
1166 }
1167
1168 /// Returns whether or not the window is currently fullscreen
1169 pub fn is_fullscreen(&self) -> bool {
1170 self.window.platform_window.is_fullscreen()
1171 }
1172
1173 pub(crate) fn appearance_changed(&mut self) {
1174 self.window.appearance = self.window.platform_window.appearance();
1175
1176 self.window
1177 .appearance_observers
1178 .clone()
1179 .retain(&(), |callback| callback(self));
1180 }
1181
1182 /// Returns the appearance of the current window.
1183 pub fn appearance(&self) -> WindowAppearance {
1184 self.window.appearance
1185 }
1186
1187 /// Returns the size of the drawable area within the window.
1188 pub fn viewport_size(&self) -> Size<Pixels> {
1189 self.window.viewport_size
1190 }
1191
1192 /// Returns whether this window is focused by the operating system (receiving key events).
1193 pub fn is_window_active(&self) -> bool {
1194 self.window.active.get()
1195 }
1196
1197 /// Toggle zoom on the window.
1198 pub fn zoom_window(&self) {
1199 self.window.platform_window.zoom();
1200 }
1201
1202 /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
1203 pub fn show_window_menu(&self, position: Point<Pixels>) {
1204 self.window.platform_window.show_window_menu(position)
1205 }
1206
1207 /// Tells the compositor to take control of window movement (Wayland and X11)
1208 ///
1209 /// Events may not be received during a move operation.
1210 pub fn start_system_move(&self) {
1211 self.window.platform_window.start_system_move()
1212 }
1213
1214 /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
1215 pub fn should_render_window_controls(&self) -> bool {
1216 self.window.platform_window.should_render_window_controls()
1217 }
1218
1219 /// Updates the window's title at the platform level.
1220 pub fn set_window_title(&mut self, title: &str) {
1221 self.window.platform_window.set_title(title);
1222 }
1223
1224 /// Sets the application identifier.
1225 pub fn set_app_id(&mut self, app_id: &str) {
1226 self.window.platform_window.set_app_id(app_id);
1227 }
1228
1229 /// Sets the window background appearance.
1230 pub fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
1231 self.window
1232 .platform_window
1233 .set_background_appearance(background_appearance);
1234 }
1235
1236 /// Mark the window as dirty at the platform level.
1237 pub fn set_window_edited(&mut self, edited: bool) {
1238 self.window.platform_window.set_edited(edited);
1239 }
1240
1241 /// Determine the display on which the window is visible.
1242 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1243 self.platform
1244 .displays()
1245 .into_iter()
1246 .find(|display| Some(display.id()) == self.window.display_id)
1247 }
1248
1249 /// Show the platform character palette.
1250 pub fn show_character_palette(&self) {
1251 self.window.platform_window.show_character_palette();
1252 }
1253
1254 /// The scale factor of the display associated with the window. For example, it could
1255 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
1256 /// be rendered as two pixels on screen.
1257 pub fn scale_factor(&self) -> f32 {
1258 self.window.scale_factor
1259 }
1260
1261 /// The size of an em for the base font of the application. Adjusting this value allows the
1262 /// UI to scale, just like zooming a web page.
1263 pub fn rem_size(&self) -> Pixels {
1264 self.window
1265 .rem_size_override_stack
1266 .last()
1267 .copied()
1268 .unwrap_or(self.window.rem_size)
1269 }
1270
1271 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
1272 /// UI to scale, just like zooming a web page.
1273 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
1274 self.window.rem_size = rem_size.into();
1275 }
1276
1277 /// Executes the provided function with the specified rem size.
1278 ///
1279 /// This method must only be called as part of element drawing.
1280 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
1281 where
1282 F: FnOnce(&mut Self) -> R,
1283 {
1284 debug_assert!(
1285 matches!(
1286 self.window.draw_phase,
1287 DrawPhase::Prepaint | DrawPhase::Paint
1288 ),
1289 "this method can only be called during request_layout, prepaint, or paint"
1290 );
1291
1292 if let Some(rem_size) = rem_size {
1293 self.window.rem_size_override_stack.push(rem_size.into());
1294 let result = f(self);
1295 self.window.rem_size_override_stack.pop();
1296 result
1297 } else {
1298 f(self)
1299 }
1300 }
1301
1302 /// The line height associated with the current text style.
1303 pub fn line_height(&self) -> Pixels {
1304 let rem_size = self.rem_size();
1305 let text_style = self.text_style();
1306 text_style
1307 .line_height
1308 .to_pixels(text_style.font_size, rem_size)
1309 }
1310
1311 /// Call to prevent the default action of an event. Currently only used to prevent
1312 /// parent elements from becoming focused on mouse down.
1313 pub fn prevent_default(&mut self) {
1314 self.window.default_prevented = true;
1315 }
1316
1317 /// Obtain whether default has been prevented for the event currently being dispatched.
1318 pub fn default_prevented(&self) -> bool {
1319 self.window.default_prevented
1320 }
1321
1322 /// Determine whether the given action is available along the dispatch path to the currently focused element.
1323 pub fn is_action_available(&self, action: &dyn Action) -> bool {
1324 let target = self
1325 .focused()
1326 .and_then(|focused_handle| {
1327 self.window
1328 .rendered_frame
1329 .dispatch_tree
1330 .focusable_node_id(focused_handle.id)
1331 })
1332 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1333 self.window
1334 .rendered_frame
1335 .dispatch_tree
1336 .is_action_available(action, target)
1337 }
1338
1339 /// The position of the mouse relative to the window.
1340 pub fn mouse_position(&self) -> Point<Pixels> {
1341 self.window.mouse_position
1342 }
1343
1344 /// The current state of the keyboard's modifiers
1345 pub fn modifiers(&self) -> Modifiers {
1346 self.window.modifiers
1347 }
1348
1349 fn complete_frame(&self) {
1350 self.window.platform_window.completed_frame();
1351 }
1352
1353 /// Produces a new frame and assigns it to `rendered_frame`. To actually show
1354 /// the contents of the new [Scene], use [present].
1355 #[profiling::function]
1356 pub fn draw(&mut self) {
1357 self.window.dirty.set(false);
1358 self.window.requested_autoscroll = None;
1359
1360 // Restore the previously-used input handler.
1361 if let Some(input_handler) = self.window.platform_window.take_input_handler() {
1362 self.window
1363 .rendered_frame
1364 .input_handlers
1365 .push(Some(input_handler));
1366 }
1367
1368 self.draw_roots();
1369 self.window.dirty_views.clear();
1370
1371 self.window
1372 .next_frame
1373 .dispatch_tree
1374 .preserve_pending_keystrokes(
1375 &mut self.window.rendered_frame.dispatch_tree,
1376 self.window.focus,
1377 );
1378 self.window.next_frame.focus = self.window.focus;
1379 self.window.next_frame.window_active = self.window.active.get();
1380
1381 // Register requested input handler with the platform window.
1382 if let Some(input_handler) = self.window.next_frame.input_handlers.pop() {
1383 self.window
1384 .platform_window
1385 .set_input_handler(input_handler.unwrap());
1386 }
1387
1388 self.window.layout_engine.as_mut().unwrap().clear();
1389 self.text_system().finish_frame();
1390 self.window
1391 .next_frame
1392 .finish(&mut self.window.rendered_frame);
1393 ELEMENT_ARENA.with_borrow_mut(|element_arena| {
1394 let percentage = (element_arena.len() as f32 / element_arena.capacity() as f32) * 100.;
1395 if percentage >= 80. {
1396 log::warn!("elevated element arena occupation: {}.", percentage);
1397 }
1398 element_arena.clear();
1399 });
1400
1401 self.window.draw_phase = DrawPhase::Focus;
1402 let previous_focus_path = self.window.rendered_frame.focus_path();
1403 let previous_window_active = self.window.rendered_frame.window_active;
1404 mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
1405 self.window.next_frame.clear();
1406 let current_focus_path = self.window.rendered_frame.focus_path();
1407 let current_window_active = self.window.rendered_frame.window_active;
1408
1409 if previous_focus_path != current_focus_path
1410 || previous_window_active != current_window_active
1411 {
1412 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
1413 self.window
1414 .focus_lost_listeners
1415 .clone()
1416 .retain(&(), |listener| listener(self));
1417 }
1418
1419 let event = WindowFocusEvent {
1420 previous_focus_path: if previous_window_active {
1421 previous_focus_path
1422 } else {
1423 Default::default()
1424 },
1425 current_focus_path: if current_window_active {
1426 current_focus_path
1427 } else {
1428 Default::default()
1429 },
1430 };
1431 self.window
1432 .focus_listeners
1433 .clone()
1434 .retain(&(), |listener| listener(&event, self));
1435 }
1436
1437 self.reset_cursor_style();
1438 self.window.refreshing = false;
1439 self.window.draw_phase = DrawPhase::None;
1440 self.window.needs_present.set(true);
1441 }
1442
1443 #[profiling::function]
1444 fn present(&self) {
1445 self.window
1446 .platform_window
1447 .draw(&self.window.rendered_frame.scene);
1448 self.window.needs_present.set(false);
1449 profiling::finish_frame!();
1450 }
1451
1452 fn draw_roots(&mut self) {
1453 self.window.draw_phase = DrawPhase::Prepaint;
1454 self.window.tooltip_bounds.take();
1455
1456 // Layout all root elements.
1457 let mut root_element = self.window.root_view.as_ref().unwrap().clone().into_any();
1458 root_element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1459
1460 let mut sorted_deferred_draws =
1461 (0..self.window.next_frame.deferred_draws.len()).collect::<SmallVec<[_; 8]>>();
1462 sorted_deferred_draws.sort_by_key(|ix| self.window.next_frame.deferred_draws[*ix].priority);
1463 self.prepaint_deferred_draws(&sorted_deferred_draws);
1464
1465 let mut prompt_element = None;
1466 let mut active_drag_element = None;
1467 let mut tooltip_element = None;
1468 if let Some(prompt) = self.window.prompt.take() {
1469 let mut element = prompt.view.any_view().into_any();
1470 element.prepaint_as_root(Point::default(), self.window.viewport_size.into(), self);
1471 prompt_element = Some(element);
1472 self.window.prompt = Some(prompt);
1473 } else if let Some(active_drag) = self.app.active_drag.take() {
1474 let mut element = active_drag.view.clone().into_any();
1475 let offset = self.mouse_position() - active_drag.cursor_offset;
1476 element.prepaint_as_root(offset, AvailableSpace::min_size(), self);
1477 active_drag_element = Some(element);
1478 self.app.active_drag = Some(active_drag);
1479 } else {
1480 tooltip_element = self.prepaint_tooltip();
1481 }
1482
1483 self.window.mouse_hit_test = self.window.next_frame.hit_test(self.window.mouse_position);
1484
1485 // Now actually paint the elements.
1486 self.window.draw_phase = DrawPhase::Paint;
1487 root_element.paint(self);
1488
1489 self.paint_deferred_draws(&sorted_deferred_draws);
1490
1491 if let Some(mut prompt_element) = prompt_element {
1492 prompt_element.paint(self)
1493 } else if let Some(mut drag_element) = active_drag_element {
1494 drag_element.paint(self);
1495 } else if let Some(mut tooltip_element) = tooltip_element {
1496 tooltip_element.paint(self);
1497 }
1498 }
1499
1500 fn prepaint_tooltip(&mut self) -> Option<AnyElement> {
1501 let tooltip_request = self.window.next_frame.tooltip_requests.last().cloned()?;
1502 let tooltip_request = tooltip_request.unwrap();
1503 let mut element = tooltip_request.tooltip.view.clone().into_any();
1504 let mouse_position = tooltip_request.tooltip.mouse_position;
1505 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self);
1506
1507 let mut tooltip_bounds = Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
1508 let window_bounds = Bounds {
1509 origin: Point::default(),
1510 size: self.viewport_size(),
1511 };
1512
1513 if tooltip_bounds.right() > window_bounds.right() {
1514 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
1515 if new_x >= Pixels::ZERO {
1516 tooltip_bounds.origin.x = new_x;
1517 } else {
1518 tooltip_bounds.origin.x = cmp::max(
1519 Pixels::ZERO,
1520 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
1521 );
1522 }
1523 }
1524
1525 if tooltip_bounds.bottom() > window_bounds.bottom() {
1526 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
1527 if new_y >= Pixels::ZERO {
1528 tooltip_bounds.origin.y = new_y;
1529 } else {
1530 tooltip_bounds.origin.y = cmp::max(
1531 Pixels::ZERO,
1532 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
1533 );
1534 }
1535 }
1536
1537 self.with_absolute_element_offset(tooltip_bounds.origin, |cx| element.prepaint(cx));
1538
1539 self.window.tooltip_bounds = Some(TooltipBounds {
1540 id: tooltip_request.id,
1541 bounds: tooltip_bounds,
1542 });
1543 Some(element)
1544 }
1545
1546 fn prepaint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1547 assert_eq!(self.window.element_id_stack.len(), 0);
1548
1549 let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1550 for deferred_draw_ix in deferred_draw_indices {
1551 let deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1552 self.window
1553 .element_id_stack
1554 .clone_from(&deferred_draw.element_id_stack);
1555 self.window
1556 .text_style_stack
1557 .clone_from(&deferred_draw.text_style_stack);
1558 self.window
1559 .next_frame
1560 .dispatch_tree
1561 .set_active_node(deferred_draw.parent_node);
1562
1563 let prepaint_start = self.prepaint_index();
1564 if let Some(element) = deferred_draw.element.as_mut() {
1565 self.with_absolute_element_offset(deferred_draw.absolute_offset, |cx| {
1566 element.prepaint(cx)
1567 });
1568 } else {
1569 self.reuse_prepaint(deferred_draw.prepaint_range.clone());
1570 }
1571 let prepaint_end = self.prepaint_index();
1572 deferred_draw.prepaint_range = prepaint_start..prepaint_end;
1573 }
1574 assert_eq!(
1575 self.window.next_frame.deferred_draws.len(),
1576 0,
1577 "cannot call defer_draw during deferred drawing"
1578 );
1579 self.window.next_frame.deferred_draws = deferred_draws;
1580 self.window.element_id_stack.clear();
1581 self.window.text_style_stack.clear();
1582 }
1583
1584 fn paint_deferred_draws(&mut self, deferred_draw_indices: &[usize]) {
1585 assert_eq!(self.window.element_id_stack.len(), 0);
1586
1587 let mut deferred_draws = mem::take(&mut self.window.next_frame.deferred_draws);
1588 for deferred_draw_ix in deferred_draw_indices {
1589 let mut deferred_draw = &mut deferred_draws[*deferred_draw_ix];
1590 self.window
1591 .element_id_stack
1592 .clone_from(&deferred_draw.element_id_stack);
1593 self.window
1594 .next_frame
1595 .dispatch_tree
1596 .set_active_node(deferred_draw.parent_node);
1597
1598 let paint_start = self.paint_index();
1599 if let Some(element) = deferred_draw.element.as_mut() {
1600 element.paint(self);
1601 } else {
1602 self.reuse_paint(deferred_draw.paint_range.clone());
1603 }
1604 let paint_end = self.paint_index();
1605 deferred_draw.paint_range = paint_start..paint_end;
1606 }
1607 self.window.next_frame.deferred_draws = deferred_draws;
1608 self.window.element_id_stack.clear();
1609 }
1610
1611 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
1612 PrepaintStateIndex {
1613 hitboxes_index: self.window.next_frame.hitboxes.len(),
1614 tooltips_index: self.window.next_frame.tooltip_requests.len(),
1615 deferred_draws_index: self.window.next_frame.deferred_draws.len(),
1616 dispatch_tree_index: self.window.next_frame.dispatch_tree.len(),
1617 accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1618 line_layout_index: self.window.text_system.layout_index(),
1619 }
1620 }
1621
1622 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
1623 let window = &mut self.window;
1624 window.next_frame.hitboxes.extend(
1625 window.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
1626 .iter()
1627 .cloned(),
1628 );
1629 window.next_frame.tooltip_requests.extend(
1630 window.rendered_frame.tooltip_requests
1631 [range.start.tooltips_index..range.end.tooltips_index]
1632 .iter_mut()
1633 .map(|request| request.take()),
1634 );
1635 window.next_frame.accessed_element_states.extend(
1636 window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1637 ..range.end.accessed_element_states_index]
1638 .iter()
1639 .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1640 );
1641 window
1642 .text_system
1643 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1644
1645 let reused_subtree = window.next_frame.dispatch_tree.reuse_subtree(
1646 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
1647 &mut window.rendered_frame.dispatch_tree,
1648 );
1649 window.next_frame.deferred_draws.extend(
1650 window.rendered_frame.deferred_draws
1651 [range.start.deferred_draws_index..range.end.deferred_draws_index]
1652 .iter()
1653 .map(|deferred_draw| DeferredDraw {
1654 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
1655 element_id_stack: deferred_draw.element_id_stack.clone(),
1656 text_style_stack: deferred_draw.text_style_stack.clone(),
1657 priority: deferred_draw.priority,
1658 element: None,
1659 absolute_offset: deferred_draw.absolute_offset,
1660 prepaint_range: deferred_draw.prepaint_range.clone(),
1661 paint_range: deferred_draw.paint_range.clone(),
1662 }),
1663 );
1664 }
1665
1666 pub(crate) fn paint_index(&self) -> PaintIndex {
1667 PaintIndex {
1668 scene_index: self.window.next_frame.scene.len(),
1669 mouse_listeners_index: self.window.next_frame.mouse_listeners.len(),
1670 input_handlers_index: self.window.next_frame.input_handlers.len(),
1671 cursor_styles_index: self.window.next_frame.cursor_styles.len(),
1672 accessed_element_states_index: self.window.next_frame.accessed_element_states.len(),
1673 line_layout_index: self.window.text_system.layout_index(),
1674 }
1675 }
1676
1677 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
1678 let window = &mut self.window;
1679
1680 window.next_frame.cursor_styles.extend(
1681 window.rendered_frame.cursor_styles
1682 [range.start.cursor_styles_index..range.end.cursor_styles_index]
1683 .iter()
1684 .cloned(),
1685 );
1686 window.next_frame.input_handlers.extend(
1687 window.rendered_frame.input_handlers
1688 [range.start.input_handlers_index..range.end.input_handlers_index]
1689 .iter_mut()
1690 .map(|handler| handler.take()),
1691 );
1692 window.next_frame.mouse_listeners.extend(
1693 window.rendered_frame.mouse_listeners
1694 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
1695 .iter_mut()
1696 .map(|listener| listener.take()),
1697 );
1698 window.next_frame.accessed_element_states.extend(
1699 window.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
1700 ..range.end.accessed_element_states_index]
1701 .iter()
1702 .map(|(id, type_id)| (GlobalElementId(id.0.clone()), *type_id)),
1703 );
1704 window
1705 .text_system
1706 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
1707 window.next_frame.scene.replay(
1708 range.start.scene_index..range.end.scene_index,
1709 &window.rendered_frame.scene,
1710 );
1711 }
1712
1713 /// Push a text style onto the stack, and call a function with that style active.
1714 /// Use [`AppContext::text_style`] to get the current, combined text style. This method
1715 /// should only be called as part of element drawing.
1716 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
1717 where
1718 F: FnOnce(&mut Self) -> R,
1719 {
1720 debug_assert!(
1721 matches!(
1722 self.window.draw_phase,
1723 DrawPhase::Prepaint | DrawPhase::Paint
1724 ),
1725 "this method can only be called during request_layout, prepaint, or paint"
1726 );
1727 if let Some(style) = style {
1728 self.window.text_style_stack.push(style);
1729 let result = f(self);
1730 self.window.text_style_stack.pop();
1731 result
1732 } else {
1733 f(self)
1734 }
1735 }
1736
1737 /// Updates the cursor style at the platform level. This method should only be called
1738 /// during the prepaint phase of element drawing.
1739 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
1740 debug_assert_eq!(
1741 self.window.draw_phase,
1742 DrawPhase::Paint,
1743 "this method can only be called during paint"
1744 );
1745 self.window
1746 .next_frame
1747 .cursor_styles
1748 .push(CursorStyleRequest {
1749 hitbox_id: hitbox.id,
1750 style,
1751 });
1752 }
1753
1754 /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
1755 /// during the paint phase of element drawing.
1756 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
1757 debug_assert_eq!(
1758 self.window.draw_phase,
1759 DrawPhase::Prepaint,
1760 "this method can only be called during prepaint"
1761 );
1762 let id = TooltipId(post_inc(&mut self.window.next_tooltip_id.0));
1763 self.window
1764 .next_frame
1765 .tooltip_requests
1766 .push(Some(TooltipRequest { id, tooltip }));
1767 id
1768 }
1769
1770 /// Invoke the given function with the given content mask after intersecting it
1771 /// with the current mask. This method should only be called during element drawing.
1772 pub fn with_content_mask<R>(
1773 &mut self,
1774 mask: Option<ContentMask<Pixels>>,
1775 f: impl FnOnce(&mut Self) -> R,
1776 ) -> R {
1777 debug_assert!(
1778 matches!(
1779 self.window.draw_phase,
1780 DrawPhase::Prepaint | DrawPhase::Paint
1781 ),
1782 "this method can only be called during request_layout, prepaint, or paint"
1783 );
1784 if let Some(mask) = mask {
1785 let mask = mask.intersect(&self.content_mask());
1786 self.window_mut().content_mask_stack.push(mask);
1787 let result = f(self);
1788 self.window_mut().content_mask_stack.pop();
1789 result
1790 } else {
1791 f(self)
1792 }
1793 }
1794
1795 /// Updates the global element offset relative to the current offset. This is used to implement
1796 /// scrolling. This method should only be called during the prepaint phase of element drawing.
1797 pub fn with_element_offset<R>(
1798 &mut self,
1799 offset: Point<Pixels>,
1800 f: impl FnOnce(&mut Self) -> R,
1801 ) -> R {
1802 debug_assert_eq!(
1803 self.window.draw_phase,
1804 DrawPhase::Prepaint,
1805 "this method can only be called during request_layout, or prepaint"
1806 );
1807
1808 if offset.is_zero() {
1809 return f(self);
1810 };
1811
1812 let abs_offset = self.element_offset() + offset;
1813 self.with_absolute_element_offset(abs_offset, f)
1814 }
1815
1816 /// Updates the global element offset based on the given offset. This is used to implement
1817 /// drag handles and other manual painting of elements. This method should only be called during
1818 /// the prepaint phase of element drawing.
1819 pub fn with_absolute_element_offset<R>(
1820 &mut self,
1821 offset: Point<Pixels>,
1822 f: impl FnOnce(&mut Self) -> R,
1823 ) -> R {
1824 debug_assert_eq!(
1825 self.window.draw_phase,
1826 DrawPhase::Prepaint,
1827 "this method can only be called during request_layout, or prepaint"
1828 );
1829 self.window_mut().element_offset_stack.push(offset);
1830 let result = f(self);
1831 self.window_mut().element_offset_stack.pop();
1832 result
1833 }
1834
1835 /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
1836 /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
1837 /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
1838 /// element offset and prepaint again. See [`List`] for an example. This method should only be
1839 /// called during the prepaint phase of element drawing.
1840 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
1841 debug_assert_eq!(
1842 self.window.draw_phase,
1843 DrawPhase::Prepaint,
1844 "this method can only be called during prepaint"
1845 );
1846 let index = self.prepaint_index();
1847 let result = f(self);
1848 if result.is_err() {
1849 self.window
1850 .next_frame
1851 .hitboxes
1852 .truncate(index.hitboxes_index);
1853 self.window
1854 .next_frame
1855 .tooltip_requests
1856 .truncate(index.tooltips_index);
1857 self.window
1858 .next_frame
1859 .deferred_draws
1860 .truncate(index.deferred_draws_index);
1861 self.window
1862 .next_frame
1863 .dispatch_tree
1864 .truncate(index.dispatch_tree_index);
1865 self.window
1866 .next_frame
1867 .accessed_element_states
1868 .truncate(index.accessed_element_states_index);
1869 self.window
1870 .text_system
1871 .truncate_layouts(index.line_layout_index);
1872 }
1873 result
1874 }
1875
1876 /// When you call this method during [`prepaint`], containing elements will attempt to
1877 /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
1878 /// [`prepaint`] again with a new set of bounds. See [`List`] for an example of an element
1879 /// that supports this method being called on the elements it contains. This method should only be
1880 /// called during the prepaint phase of element drawing.
1881 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
1882 debug_assert_eq!(
1883 self.window.draw_phase,
1884 DrawPhase::Prepaint,
1885 "this method can only be called during prepaint"
1886 );
1887 self.window.requested_autoscroll = Some(bounds);
1888 }
1889
1890 /// This method can be called from a containing element such as [`List`] to support the autoscroll behavior
1891 /// described in [`request_autoscroll`].
1892 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
1893 debug_assert_eq!(
1894 self.window.draw_phase,
1895 DrawPhase::Prepaint,
1896 "this method can only be called during prepaint"
1897 );
1898 self.window.requested_autoscroll.take()
1899 }
1900
1901 /// Remove an asset from GPUI's cache
1902 pub fn remove_cached_asset<A: Asset + 'static>(
1903 &mut self,
1904 source: &A::Source,
1905 ) -> Option<A::Output> {
1906 self.asset_cache.remove::<A>(source)
1907 }
1908
1909 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1910 /// Your view will be re-drawn once the asset has finished loading.
1911 ///
1912 /// Note that the multiple calls to this method will only result in one `Asset::load` call.
1913 /// The results of that call will be cached, and returned on subsequent uses of this API.
1914 ///
1915 /// Use [Self::remove_cached_asset] to reload your asset.
1916 pub fn use_cached_asset<A: Asset + 'static>(
1917 &mut self,
1918 source: &A::Source,
1919 ) -> Option<A::Output> {
1920 self.asset_cache.get::<A>(source).or_else(|| {
1921 if let Some(asset) = self.use_asset::<A>(source) {
1922 self.asset_cache
1923 .insert::<A>(source.to_owned(), asset.clone());
1924 Some(asset)
1925 } else {
1926 None
1927 }
1928 })
1929 }
1930
1931 /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
1932 /// Your view will be re-drawn once the asset has finished loading.
1933 ///
1934 /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
1935 /// time.
1936 ///
1937 /// This asset will not be cached by default, see [Self::use_cached_asset]
1938 pub fn use_asset<A: Asset + 'static>(&mut self, source: &A::Source) -> Option<A::Output> {
1939 let asset_id = (TypeId::of::<A>(), hash(source));
1940 let mut is_first = false;
1941 let task = self
1942 .loading_assets
1943 .remove(&asset_id)
1944 .map(|boxed_task| *boxed_task.downcast::<Shared<Task<A::Output>>>().unwrap())
1945 .unwrap_or_else(|| {
1946 is_first = true;
1947 let future = A::load(source.clone(), self);
1948 let task = self.background_executor().spawn(future).shared();
1949 task
1950 });
1951
1952 task.clone().now_or_never().or_else(|| {
1953 if is_first {
1954 let parent_id = self.parent_view_id();
1955 self.spawn({
1956 let task = task.clone();
1957 |mut cx| async move {
1958 task.await;
1959
1960 cx.on_next_frame(move |cx| {
1961 if let Some(parent_id) = parent_id {
1962 cx.notify(parent_id)
1963 } else {
1964 cx.refresh()
1965 }
1966 });
1967 }
1968 })
1969 .detach();
1970 }
1971
1972 self.loading_assets.insert(asset_id, Box::new(task));
1973
1974 None
1975 })
1976 }
1977
1978 /// Obtain the current element offset. This method should only be called during the
1979 /// prepaint phase of element drawing.
1980 pub fn element_offset(&self) -> Point<Pixels> {
1981 debug_assert_eq!(
1982 self.window.draw_phase,
1983 DrawPhase::Prepaint,
1984 "this method can only be called during prepaint"
1985 );
1986 self.window()
1987 .element_offset_stack
1988 .last()
1989 .copied()
1990 .unwrap_or_default()
1991 }
1992
1993 /// Obtain the current content mask. This method should only be called during element drawing.
1994 pub fn content_mask(&self) -> ContentMask<Pixels> {
1995 debug_assert!(
1996 matches!(
1997 self.window.draw_phase,
1998 DrawPhase::Prepaint | DrawPhase::Paint
1999 ),
2000 "this method can only be called during prepaint, or paint"
2001 );
2002 self.window()
2003 .content_mask_stack
2004 .last()
2005 .cloned()
2006 .unwrap_or_else(|| ContentMask {
2007 bounds: Bounds {
2008 origin: Point::default(),
2009 size: self.window().viewport_size,
2010 },
2011 })
2012 }
2013
2014 /// Provide elements in the called function with a new namespace in which their identiers must be unique.
2015 /// This can be used within a custom element to distinguish multiple sets of child elements.
2016 pub fn with_element_namespace<R>(
2017 &mut self,
2018 element_id: impl Into<ElementId>,
2019 f: impl FnOnce(&mut Self) -> R,
2020 ) -> R {
2021 self.window.element_id_stack.push(element_id.into());
2022 let result = f(self);
2023 self.window.element_id_stack.pop();
2024 result
2025 }
2026
2027 /// Updates or initializes state for an element with the given id that lives across multiple
2028 /// frames. If an element with this ID existed in the rendered frame, its state will be passed
2029 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2030 /// when drawing the next frame. This method should only be called as part of element drawing.
2031 pub fn with_element_state<S, R>(
2032 &mut self,
2033 global_id: &GlobalElementId,
2034 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2035 ) -> R
2036 where
2037 S: 'static,
2038 {
2039 debug_assert!(
2040 matches!(
2041 self.window.draw_phase,
2042 DrawPhase::Prepaint | DrawPhase::Paint
2043 ),
2044 "this method can only be called during request_layout, prepaint, or paint"
2045 );
2046
2047 let key = (GlobalElementId(global_id.0.clone()), TypeId::of::<S>());
2048 self.window
2049 .next_frame
2050 .accessed_element_states
2051 .push((GlobalElementId(key.0.clone()), TypeId::of::<S>()));
2052
2053 if let Some(any) = self
2054 .window
2055 .next_frame
2056 .element_states
2057 .remove(&key)
2058 .or_else(|| self.window.rendered_frame.element_states.remove(&key))
2059 {
2060 let ElementStateBox {
2061 inner,
2062 #[cfg(debug_assertions)]
2063 type_name,
2064 } = any;
2065 // Using the extra inner option to avoid needing to reallocate a new box.
2066 let mut state_box = inner
2067 .downcast::<Option<S>>()
2068 .map_err(|_| {
2069 #[cfg(debug_assertions)]
2070 {
2071 anyhow::anyhow!(
2072 "invalid element state type for id, requested {:?}, actual: {:?}",
2073 std::any::type_name::<S>(),
2074 type_name
2075 )
2076 }
2077
2078 #[cfg(not(debug_assertions))]
2079 {
2080 anyhow::anyhow!(
2081 "invalid element state type for id, requested {:?}",
2082 std::any::type_name::<S>(),
2083 )
2084 }
2085 })
2086 .unwrap();
2087
2088 let state = state_box.take().expect(
2089 "reentrant call to with_element_state for the same state type and element id",
2090 );
2091 let (result, state) = f(Some(state), self);
2092 state_box.replace(state);
2093 self.window.next_frame.element_states.insert(
2094 key,
2095 ElementStateBox {
2096 inner: state_box,
2097 #[cfg(debug_assertions)]
2098 type_name,
2099 },
2100 );
2101 result
2102 } else {
2103 let (result, state) = f(None, self);
2104 self.window.next_frame.element_states.insert(
2105 key,
2106 ElementStateBox {
2107 inner: Box::new(Some(state)),
2108 #[cfg(debug_assertions)]
2109 type_name: std::any::type_name::<S>(),
2110 },
2111 );
2112 result
2113 }
2114 }
2115
2116 /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
2117 /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
2118 /// when the element is guaranteed to have an id.
2119 pub fn with_optional_element_state<S, R>(
2120 &mut self,
2121 global_id: Option<&GlobalElementId>,
2122 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
2123 ) -> R
2124 where
2125 S: 'static,
2126 {
2127 debug_assert!(
2128 matches!(
2129 self.window.draw_phase,
2130 DrawPhase::Prepaint | DrawPhase::Paint
2131 ),
2132 "this method can only be called during request_layout, prepaint, or paint"
2133 );
2134
2135 if let Some(global_id) = global_id {
2136 self.with_element_state(global_id, |state, cx| {
2137 let (result, state) = f(Some(state), cx);
2138 let state =
2139 state.expect("you must return some state when you pass some element id");
2140 (result, state)
2141 })
2142 } else {
2143 let (result, state) = f(None, self);
2144 debug_assert!(
2145 state.is_none(),
2146 "you must not return an element state when passing None for the global id"
2147 );
2148 result
2149 }
2150 }
2151
2152 /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
2153 /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
2154 /// with higher values being drawn on top.
2155 ///
2156 /// This method should only be called as part of the prepaint phase of element drawing.
2157 pub fn defer_draw(
2158 &mut self,
2159 element: AnyElement,
2160 absolute_offset: Point<Pixels>,
2161 priority: usize,
2162 ) {
2163 let window = &mut self.window;
2164 debug_assert_eq!(
2165 window.draw_phase,
2166 DrawPhase::Prepaint,
2167 "this method can only be called during request_layout or prepaint"
2168 );
2169 let parent_node = window.next_frame.dispatch_tree.active_node_id().unwrap();
2170 window.next_frame.deferred_draws.push(DeferredDraw {
2171 parent_node,
2172 element_id_stack: window.element_id_stack.clone(),
2173 text_style_stack: window.text_style_stack.clone(),
2174 priority,
2175 element: Some(element),
2176 absolute_offset,
2177 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
2178 paint_range: PaintIndex::default()..PaintIndex::default(),
2179 });
2180 }
2181
2182 /// Creates a new painting layer for the specified bounds. A "layer" is a batch
2183 /// of geometry that are non-overlapping and have the same draw order. This is typically used
2184 /// for performance reasons.
2185 ///
2186 /// This method should only be called as part of the paint phase of element drawing.
2187 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
2188 debug_assert_eq!(
2189 self.window.draw_phase,
2190 DrawPhase::Paint,
2191 "this method can only be called during paint"
2192 );
2193
2194 let scale_factor = self.scale_factor();
2195 let content_mask = self.content_mask();
2196 let clipped_bounds = bounds.intersect(&content_mask.bounds);
2197 if !clipped_bounds.is_empty() {
2198 self.window
2199 .next_frame
2200 .scene
2201 .push_layer(clipped_bounds.scale(scale_factor));
2202 }
2203
2204 let result = f(self);
2205
2206 if !clipped_bounds.is_empty() {
2207 self.window.next_frame.scene.pop_layer();
2208 }
2209
2210 result
2211 }
2212
2213 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
2214 ///
2215 /// This method should only be called as part of the paint phase of element drawing.
2216 pub fn paint_shadows(
2217 &mut self,
2218 bounds: Bounds<Pixels>,
2219 corner_radii: Corners<Pixels>,
2220 shadows: &[BoxShadow],
2221 ) {
2222 debug_assert_eq!(
2223 self.window.draw_phase,
2224 DrawPhase::Paint,
2225 "this method can only be called during paint"
2226 );
2227
2228 let scale_factor = self.scale_factor();
2229 let content_mask = self.content_mask();
2230 for shadow in shadows {
2231 let mut shadow_bounds = bounds;
2232 shadow_bounds.origin += shadow.offset;
2233 shadow_bounds.dilate(shadow.spread_radius);
2234 self.window.next_frame.scene.insert_primitive(Shadow {
2235 order: 0,
2236 blur_radius: shadow.blur_radius.scale(scale_factor),
2237 bounds: shadow_bounds.scale(scale_factor),
2238 content_mask: content_mask.scale(scale_factor),
2239 corner_radii: corner_radii.scale(scale_factor),
2240 color: shadow.color,
2241 });
2242 }
2243 }
2244
2245 /// Paint one or more quads into the scene for the next frame at the current stacking context.
2246 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
2247 /// see [`fill`](crate::fill), [`outline`](crate::outline), and [`quad`](crate::quad) to construct this type.
2248 ///
2249 /// This method should only be called as part of the paint phase of element drawing.
2250 pub fn paint_quad(&mut self, quad: PaintQuad) {
2251 debug_assert_eq!(
2252 self.window.draw_phase,
2253 DrawPhase::Paint,
2254 "this method can only be called during paint"
2255 );
2256
2257 let scale_factor = self.scale_factor();
2258 let content_mask = self.content_mask();
2259 self.window.next_frame.scene.insert_primitive(Quad {
2260 order: 0,
2261 pad: 0,
2262 bounds: quad.bounds.scale(scale_factor),
2263 content_mask: content_mask.scale(scale_factor),
2264 background: quad.background,
2265 border_color: quad.border_color,
2266 corner_radii: quad.corner_radii.scale(scale_factor),
2267 border_widths: quad.border_widths.scale(scale_factor),
2268 });
2269 }
2270
2271 /// Paint the given `Path` into the scene for the next frame at the current z-index.
2272 ///
2273 /// This method should only be called as part of the paint phase of element drawing.
2274 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
2275 debug_assert_eq!(
2276 self.window.draw_phase,
2277 DrawPhase::Paint,
2278 "this method can only be called during paint"
2279 );
2280
2281 let scale_factor = self.scale_factor();
2282 let content_mask = self.content_mask();
2283 path.content_mask = content_mask;
2284 path.color = color.into();
2285 self.window
2286 .next_frame
2287 .scene
2288 .insert_primitive(path.scale(scale_factor));
2289 }
2290
2291 /// Paint an underline into the scene for the next frame at the current z-index.
2292 ///
2293 /// This method should only be called as part of the paint phase of element drawing.
2294 pub fn paint_underline(
2295 &mut self,
2296 origin: Point<Pixels>,
2297 width: Pixels,
2298 style: &UnderlineStyle,
2299 ) {
2300 debug_assert_eq!(
2301 self.window.draw_phase,
2302 DrawPhase::Paint,
2303 "this method can only be called during paint"
2304 );
2305
2306 let scale_factor = self.scale_factor();
2307 let height = if style.wavy {
2308 style.thickness * 3.
2309 } else {
2310 style.thickness
2311 };
2312 let bounds = Bounds {
2313 origin,
2314 size: size(width, height),
2315 };
2316 let content_mask = self.content_mask();
2317
2318 self.window.next_frame.scene.insert_primitive(Underline {
2319 order: 0,
2320 pad: 0,
2321 bounds: bounds.scale(scale_factor),
2322 content_mask: content_mask.scale(scale_factor),
2323 color: style.color.unwrap_or_default(),
2324 thickness: style.thickness.scale(scale_factor),
2325 wavy: style.wavy,
2326 });
2327 }
2328
2329 /// Paint a strikethrough into the scene for the next frame at the current z-index.
2330 ///
2331 /// This method should only be called as part of the paint phase of element drawing.
2332 pub fn paint_strikethrough(
2333 &mut self,
2334 origin: Point<Pixels>,
2335 width: Pixels,
2336 style: &StrikethroughStyle,
2337 ) {
2338 debug_assert_eq!(
2339 self.window.draw_phase,
2340 DrawPhase::Paint,
2341 "this method can only be called during paint"
2342 );
2343
2344 let scale_factor = self.scale_factor();
2345 let height = style.thickness;
2346 let bounds = Bounds {
2347 origin,
2348 size: size(width, height),
2349 };
2350 let content_mask = self.content_mask();
2351
2352 self.window.next_frame.scene.insert_primitive(Underline {
2353 order: 0,
2354 pad: 0,
2355 bounds: bounds.scale(scale_factor),
2356 content_mask: content_mask.scale(scale_factor),
2357 thickness: style.thickness.scale(scale_factor),
2358 color: style.color.unwrap_or_default(),
2359 wavy: false,
2360 });
2361 }
2362
2363 /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
2364 ///
2365 /// The y component of the origin is the baseline of the glyph.
2366 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2367 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2368 /// This method is only useful if you need to paint a single glyph that has already been shaped.
2369 ///
2370 /// This method should only be called as part of the paint phase of element drawing.
2371 pub fn paint_glyph(
2372 &mut self,
2373 origin: Point<Pixels>,
2374 font_id: FontId,
2375 glyph_id: GlyphId,
2376 font_size: Pixels,
2377 color: Hsla,
2378 ) -> Result<()> {
2379 debug_assert_eq!(
2380 self.window.draw_phase,
2381 DrawPhase::Paint,
2382 "this method can only be called during paint"
2383 );
2384
2385 let scale_factor = self.scale_factor();
2386 let glyph_origin = origin.scale(scale_factor);
2387 let subpixel_variant = Point {
2388 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2389 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
2390 };
2391 let params = RenderGlyphParams {
2392 font_id,
2393 glyph_id,
2394 font_size,
2395 subpixel_variant,
2396 scale_factor,
2397 is_emoji: false,
2398 };
2399
2400 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
2401 if !raster_bounds.is_zero() {
2402 let tile = self
2403 .window
2404 .sprite_atlas
2405 .get_or_insert_with(¶ms.clone().into(), &mut || {
2406 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
2407 Ok(Some((size, Cow::Owned(bytes))))
2408 })?
2409 .expect("Callback above only errors or returns Some");
2410 let bounds = Bounds {
2411 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2412 size: tile.bounds.size.map(Into::into),
2413 };
2414 let content_mask = self.content_mask().scale(scale_factor);
2415 self.window
2416 .next_frame
2417 .scene
2418 .insert_primitive(MonochromeSprite {
2419 order: 0,
2420 pad: 0,
2421 bounds,
2422 content_mask,
2423 color,
2424 tile,
2425 transformation: TransformationMatrix::unit(),
2426 });
2427 }
2428 Ok(())
2429 }
2430
2431 /// Paints an emoji glyph into the scene for the next frame at the current z-index.
2432 ///
2433 /// The y component of the origin is the baseline of the glyph.
2434 /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
2435 /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
2436 /// This method is only useful if you need to paint a single emoji that has already been shaped.
2437 ///
2438 /// This method should only be called as part of the paint phase of element drawing.
2439 pub fn paint_emoji(
2440 &mut self,
2441 origin: Point<Pixels>,
2442 font_id: FontId,
2443 glyph_id: GlyphId,
2444 font_size: Pixels,
2445 ) -> Result<()> {
2446 debug_assert_eq!(
2447 self.window.draw_phase,
2448 DrawPhase::Paint,
2449 "this method can only be called during paint"
2450 );
2451
2452 let scale_factor = self.scale_factor();
2453 let glyph_origin = origin.scale(scale_factor);
2454 let params = RenderGlyphParams {
2455 font_id,
2456 glyph_id,
2457 font_size,
2458 // We don't render emojis with subpixel variants.
2459 subpixel_variant: Default::default(),
2460 scale_factor,
2461 is_emoji: true,
2462 };
2463
2464 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
2465 if !raster_bounds.is_zero() {
2466 let tile = self
2467 .window
2468 .sprite_atlas
2469 .get_or_insert_with(¶ms.clone().into(), &mut || {
2470 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
2471 Ok(Some((size, Cow::Owned(bytes))))
2472 })?
2473 .expect("Callback above only errors or returns Some");
2474
2475 let bounds = Bounds {
2476 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
2477 size: tile.bounds.size.map(Into::into),
2478 };
2479 let content_mask = self.content_mask().scale(scale_factor);
2480
2481 self.window
2482 .next_frame
2483 .scene
2484 .insert_primitive(PolychromeSprite {
2485 order: 0,
2486 grayscale: false,
2487 bounds,
2488 corner_radii: Default::default(),
2489 content_mask,
2490 tile,
2491 });
2492 }
2493 Ok(())
2494 }
2495
2496 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
2497 ///
2498 /// This method should only be called as part of the paint phase of element drawing.
2499 pub fn paint_svg(
2500 &mut self,
2501 bounds: Bounds<Pixels>,
2502 path: SharedString,
2503 transformation: TransformationMatrix,
2504 color: Hsla,
2505 ) -> Result<()> {
2506 debug_assert_eq!(
2507 self.window.draw_phase,
2508 DrawPhase::Paint,
2509 "this method can only be called during paint"
2510 );
2511
2512 let scale_factor = self.scale_factor();
2513 let bounds = bounds.scale(scale_factor);
2514 // Render the SVG at twice the size to get a higher quality result.
2515 let params = RenderSvgParams {
2516 path,
2517 size: bounds
2518 .size
2519 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
2520 };
2521
2522 let Some(tile) =
2523 self.window
2524 .sprite_atlas
2525 .get_or_insert_with(¶ms.clone().into(), &mut || {
2526 let Some(bytes) = self.svg_renderer.render(¶ms)? else {
2527 return Ok(None);
2528 };
2529 Ok(Some((params.size, Cow::Owned(bytes))))
2530 })?
2531 else {
2532 return Ok(());
2533 };
2534 let content_mask = self.content_mask().scale(scale_factor);
2535
2536 self.window
2537 .next_frame
2538 .scene
2539 .insert_primitive(MonochromeSprite {
2540 order: 0,
2541 pad: 0,
2542 bounds,
2543 content_mask,
2544 color,
2545 tile,
2546 transformation,
2547 });
2548
2549 Ok(())
2550 }
2551
2552 /// Paint an image into the scene for the next frame at the current z-index.
2553 ///
2554 /// This method should only be called as part of the paint phase of element drawing.
2555 pub fn paint_image(
2556 &mut self,
2557 bounds: Bounds<Pixels>,
2558 corner_radii: Corners<Pixels>,
2559 data: Arc<ImageData>,
2560 grayscale: bool,
2561 ) -> Result<()> {
2562 debug_assert_eq!(
2563 self.window.draw_phase,
2564 DrawPhase::Paint,
2565 "this method can only be called during paint"
2566 );
2567
2568 let scale_factor = self.scale_factor();
2569 let bounds = bounds.scale(scale_factor);
2570 let params = RenderImageParams { image_id: data.id };
2571
2572 let tile = self
2573 .window
2574 .sprite_atlas
2575 .get_or_insert_with(¶ms.clone().into(), &mut || {
2576 Ok(Some((data.size(), Cow::Borrowed(data.as_bytes()))))
2577 })?
2578 .expect("Callback above only returns Some");
2579 let content_mask = self.content_mask().scale(scale_factor);
2580 let corner_radii = corner_radii.scale(scale_factor);
2581
2582 self.window
2583 .next_frame
2584 .scene
2585 .insert_primitive(PolychromeSprite {
2586 order: 0,
2587 grayscale,
2588 bounds,
2589 content_mask,
2590 corner_radii,
2591 tile,
2592 });
2593 Ok(())
2594 }
2595
2596 /// Paint a surface into the scene for the next frame at the current z-index.
2597 ///
2598 /// This method should only be called as part of the paint phase of element drawing.
2599 #[cfg(target_os = "macos")]
2600 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
2601 debug_assert_eq!(
2602 self.window.draw_phase,
2603 DrawPhase::Paint,
2604 "this method can only be called during paint"
2605 );
2606
2607 let scale_factor = self.scale_factor();
2608 let bounds = bounds.scale(scale_factor);
2609 let content_mask = self.content_mask().scale(scale_factor);
2610 self.window
2611 .next_frame
2612 .scene
2613 .insert_primitive(crate::Surface {
2614 order: 0,
2615 bounds,
2616 content_mask,
2617 image_buffer,
2618 });
2619 }
2620
2621 #[must_use]
2622 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
2623 /// layout is being requested, along with the layout ids of any children. This method is called during
2624 /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
2625 ///
2626 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2627 pub fn request_layout(
2628 &mut self,
2629 style: Style,
2630 children: impl IntoIterator<Item = LayoutId>,
2631 ) -> LayoutId {
2632 debug_assert_eq!(
2633 self.window.draw_phase,
2634 DrawPhase::Prepaint,
2635 "this method can only be called during request_layout, or prepaint"
2636 );
2637
2638 self.app.layout_id_buffer.clear();
2639 self.app.layout_id_buffer.extend(children);
2640 let rem_size = self.rem_size();
2641
2642 self.window.layout_engine.as_mut().unwrap().request_layout(
2643 style,
2644 rem_size,
2645 &self.app.layout_id_buffer,
2646 )
2647 }
2648
2649 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
2650 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
2651 /// determine the element's size. One place this is used internally is when measuring text.
2652 ///
2653 /// The given closure is invoked at layout time with the known dimensions and available space and
2654 /// returns a `Size`.
2655 ///
2656 /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
2657 pub fn request_measured_layout<
2658 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
2659 + 'static,
2660 >(
2661 &mut self,
2662 style: Style,
2663 measure: F,
2664 ) -> LayoutId {
2665 debug_assert_eq!(
2666 self.window.draw_phase,
2667 DrawPhase::Prepaint,
2668 "this method can only be called during request_layout, or prepaint"
2669 );
2670
2671 let rem_size = self.rem_size();
2672 self.window
2673 .layout_engine
2674 .as_mut()
2675 .unwrap()
2676 .request_measured_layout(style, rem_size, measure)
2677 }
2678
2679 /// Compute the layout for the given id within the given available space.
2680 /// This method is called for its side effect, typically by the framework prior to painting.
2681 /// After calling it, you can request the bounds of the given layout node id or any descendant.
2682 ///
2683 /// This method should only be called as part of the prepaint phase of element drawing.
2684 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
2685 debug_assert_eq!(
2686 self.window.draw_phase,
2687 DrawPhase::Prepaint,
2688 "this method can only be called during request_layout, or prepaint"
2689 );
2690
2691 let mut layout_engine = self.window.layout_engine.take().unwrap();
2692 layout_engine.compute_layout(layout_id, available_space, self);
2693 self.window.layout_engine = Some(layout_engine);
2694 }
2695
2696 /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
2697 /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
2698 ///
2699 /// This method should only be called as part of element drawing.
2700 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
2701 debug_assert_eq!(
2702 self.window.draw_phase,
2703 DrawPhase::Prepaint,
2704 "this method can only be called during request_layout, prepaint, or paint"
2705 );
2706
2707 let mut bounds = self
2708 .window
2709 .layout_engine
2710 .as_mut()
2711 .unwrap()
2712 .layout_bounds(layout_id)
2713 .map(Into::into);
2714 bounds.origin += self.element_offset();
2715 bounds
2716 }
2717
2718 /// This method should be called during `prepaint`. You can use
2719 /// the returned [Hitbox] during `paint` or in an event handler
2720 /// to determine whether the inserted hitbox was the topmost.
2721 ///
2722 /// This method should only be called as part of the prepaint phase of element drawing.
2723 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, opaque: bool) -> Hitbox {
2724 debug_assert_eq!(
2725 self.window.draw_phase,
2726 DrawPhase::Prepaint,
2727 "this method can only be called during prepaint"
2728 );
2729
2730 let content_mask = self.content_mask();
2731 let window = &mut self.window;
2732 let id = window.next_hitbox_id;
2733 window.next_hitbox_id.0 += 1;
2734 let hitbox = Hitbox {
2735 id,
2736 bounds,
2737 content_mask,
2738 opaque,
2739 };
2740 window.next_frame.hitboxes.push(hitbox.clone());
2741 hitbox
2742 }
2743
2744 /// Sets the key context for the current element. This context will be used to translate
2745 /// keybindings into actions.
2746 ///
2747 /// This method should only be called as part of the paint phase of element drawing.
2748 pub fn set_key_context(&mut self, context: KeyContext) {
2749 debug_assert_eq!(
2750 self.window.draw_phase,
2751 DrawPhase::Paint,
2752 "this method can only be called during paint"
2753 );
2754 self.window
2755 .next_frame
2756 .dispatch_tree
2757 .set_key_context(context);
2758 }
2759
2760 /// Sets the focus handle for the current element. This handle will be used to manage focus state
2761 /// and keyboard event dispatch for the element.
2762 ///
2763 /// This method should only be called as part of the paint phase of element drawing.
2764 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle) {
2765 debug_assert_eq!(
2766 self.window.draw_phase,
2767 DrawPhase::Paint,
2768 "this method can only be called during paint"
2769 );
2770 self.window
2771 .next_frame
2772 .dispatch_tree
2773 .set_focus_id(focus_handle.id);
2774 }
2775
2776 /// Sets the view id for the current element, which will be used to manage view caching.
2777 ///
2778 /// This method should only be called as part of element prepaint. We plan on removing this
2779 /// method eventually when we solve some issues that require us to construct editor elements
2780 /// directly instead of always using editors via views.
2781 pub fn set_view_id(&mut self, view_id: EntityId) {
2782 debug_assert_eq!(
2783 self.window.draw_phase,
2784 DrawPhase::Prepaint,
2785 "this method can only be called during prepaint"
2786 );
2787 self.window.next_frame.dispatch_tree.set_view_id(view_id);
2788 }
2789
2790 /// Get the last view id for the current element
2791 pub fn parent_view_id(&mut self) -> Option<EntityId> {
2792 self.window.next_frame.dispatch_tree.parent_view_id()
2793 }
2794
2795 /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
2796 /// platform to receive textual input with proper integration with concerns such
2797 /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
2798 /// rendered.
2799 ///
2800 /// This method should only be called as part of the paint phase of element drawing.
2801 ///
2802 /// [element_input_handler]: crate::ElementInputHandler
2803 pub fn handle_input(&mut self, focus_handle: &FocusHandle, input_handler: impl InputHandler) {
2804 debug_assert_eq!(
2805 self.window.draw_phase,
2806 DrawPhase::Paint,
2807 "this method can only be called during paint"
2808 );
2809
2810 if focus_handle.is_focused(self) {
2811 let cx = self.to_async();
2812 self.window
2813 .next_frame
2814 .input_handlers
2815 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
2816 }
2817 }
2818
2819 /// Register a mouse event listener on the window for the next frame. The type of event
2820 /// is determined by the first parameter of the given listener. When the next frame is rendered
2821 /// the listener will be cleared.
2822 ///
2823 /// This method should only be called as part of the paint phase of element drawing.
2824 pub fn on_mouse_event<Event: MouseEvent>(
2825 &mut self,
2826 mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
2827 ) {
2828 debug_assert_eq!(
2829 self.window.draw_phase,
2830 DrawPhase::Paint,
2831 "this method can only be called during paint"
2832 );
2833
2834 self.window.next_frame.mouse_listeners.push(Some(Box::new(
2835 move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
2836 if let Some(event) = event.downcast_ref() {
2837 handler(event, phase, cx)
2838 }
2839 },
2840 )));
2841 }
2842
2843 /// Register a key event listener on the window for the next frame. The type of event
2844 /// is determined by the first parameter of the given listener. When the next frame is rendered
2845 /// the listener will be cleared.
2846 ///
2847 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2848 /// a specific need to register a global listener.
2849 ///
2850 /// This method should only be called as part of the paint phase of element drawing.
2851 pub fn on_key_event<Event: KeyEvent>(
2852 &mut self,
2853 listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
2854 ) {
2855 debug_assert_eq!(
2856 self.window.draw_phase,
2857 DrawPhase::Paint,
2858 "this method can only be called during paint"
2859 );
2860
2861 self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
2862 move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
2863 if let Some(event) = event.downcast_ref::<Event>() {
2864 listener(event, phase, cx)
2865 }
2866 },
2867 ));
2868 }
2869
2870 /// Register a modifiers changed event listener on the window for the next frame.
2871 ///
2872 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
2873 /// a specific need to register a global listener.
2874 ///
2875 /// This method should only be called as part of the paint phase of element drawing.
2876 pub fn on_modifiers_changed(
2877 &mut self,
2878 listener: impl Fn(&ModifiersChangedEvent, &mut WindowContext) + 'static,
2879 ) {
2880 debug_assert_eq!(
2881 self.window.draw_phase,
2882 DrawPhase::Paint,
2883 "this method can only be called during paint"
2884 );
2885
2886 self.window
2887 .next_frame
2888 .dispatch_tree
2889 .on_modifiers_changed(Rc::new(
2890 move |event: &ModifiersChangedEvent, cx: &mut WindowContext<'_>| {
2891 listener(event, cx)
2892 },
2893 ));
2894 }
2895
2896 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2897 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
2898 /// Returns a subscription and persists until the subscription is dropped.
2899 pub fn on_focus_in(
2900 &mut self,
2901 handle: &FocusHandle,
2902 mut listener: impl FnMut(&mut WindowContext) + 'static,
2903 ) -> Subscription {
2904 let focus_id = handle.id;
2905 let (subscription, activate) =
2906 self.window.new_focus_listener(Box::new(move |event, cx| {
2907 if event.is_focus_in(focus_id) {
2908 listener(cx);
2909 }
2910 true
2911 }));
2912 self.app.defer(move |_| activate());
2913 subscription
2914 }
2915
2916 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2917 /// Returns a subscription and persists until the subscription is dropped.
2918 pub fn on_focus_out(
2919 &mut self,
2920 handle: &FocusHandle,
2921 mut listener: impl FnMut(FocusOutEvent, &mut WindowContext) + 'static,
2922 ) -> Subscription {
2923 let focus_id = handle.id;
2924 let (subscription, activate) =
2925 self.window.new_focus_listener(Box::new(move |event, cx| {
2926 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
2927 if event.is_focus_out(focus_id) {
2928 let event = FocusOutEvent {
2929 blurred: WeakFocusHandle {
2930 id: blurred_id,
2931 handles: Arc::downgrade(&cx.window.focus_handles),
2932 },
2933 };
2934 listener(event, cx)
2935 }
2936 }
2937 true
2938 }));
2939 self.app.defer(move |_| activate());
2940 subscription
2941 }
2942
2943 fn reset_cursor_style(&self) {
2944 // Set the cursor only if we're the active window.
2945 if self.is_window_active() {
2946 let style = self
2947 .window
2948 .rendered_frame
2949 .cursor_styles
2950 .iter()
2951 .rev()
2952 .find(|request| request.hitbox_id.is_hovered(self))
2953 .map(|request| request.style)
2954 .unwrap_or(CursorStyle::Arrow);
2955 self.platform.set_cursor_style(style);
2956 }
2957 }
2958
2959 /// Dispatch a given keystroke as though the user had typed it.
2960 /// You can create a keystroke with Keystroke::parse("").
2961 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke) -> bool {
2962 let keystroke = keystroke.with_simulated_ime();
2963 let result = self.dispatch_event(PlatformInput::KeyDown(KeyDownEvent {
2964 keystroke: keystroke.clone(),
2965 is_held: false,
2966 }));
2967 if !result.propagate {
2968 return true;
2969 }
2970
2971 if let Some(input) = keystroke.ime_key {
2972 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
2973 input_handler.dispatch_input(&input, self);
2974 self.window.platform_window.set_input_handler(input_handler);
2975 return true;
2976 }
2977 }
2978
2979 false
2980 }
2981
2982 /// Represent this action as a key binding string, to display in the UI.
2983 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
2984 self.bindings_for_action(action)
2985 .into_iter()
2986 .next()
2987 .map(|binding| {
2988 binding
2989 .keystrokes()
2990 .iter()
2991 .map(ToString::to_string)
2992 .collect::<Vec<_>>()
2993 .join(" ")
2994 })
2995 .unwrap_or_else(|| action.name().to_string())
2996 }
2997
2998 /// Dispatch a mouse or keyboard event on the window.
2999 #[profiling::function]
3000 pub fn dispatch_event(&mut self, event: PlatformInput) -> DispatchEventResult {
3001 self.window.last_input_timestamp.set(Instant::now());
3002 // Handlers may set this to false by calling `stop_propagation`.
3003 self.app.propagate_event = true;
3004 // Handlers may set this to true by calling `prevent_default`.
3005 self.window.default_prevented = false;
3006
3007 let event = match event {
3008 // Track the mouse position with our own state, since accessing the platform
3009 // API for the mouse position can only occur on the main thread.
3010 PlatformInput::MouseMove(mouse_move) => {
3011 self.window.mouse_position = mouse_move.position;
3012 self.window.modifiers = mouse_move.modifiers;
3013 PlatformInput::MouseMove(mouse_move)
3014 }
3015 PlatformInput::MouseDown(mouse_down) => {
3016 self.window.mouse_position = mouse_down.position;
3017 self.window.modifiers = mouse_down.modifiers;
3018 PlatformInput::MouseDown(mouse_down)
3019 }
3020 PlatformInput::MouseUp(mouse_up) => {
3021 self.window.mouse_position = mouse_up.position;
3022 self.window.modifiers = mouse_up.modifiers;
3023 PlatformInput::MouseUp(mouse_up)
3024 }
3025 PlatformInput::MouseExited(mouse_exited) => {
3026 self.window.modifiers = mouse_exited.modifiers;
3027 PlatformInput::MouseExited(mouse_exited)
3028 }
3029 PlatformInput::ModifiersChanged(modifiers_changed) => {
3030 self.window.modifiers = modifiers_changed.modifiers;
3031 PlatformInput::ModifiersChanged(modifiers_changed)
3032 }
3033 PlatformInput::ScrollWheel(scroll_wheel) => {
3034 self.window.mouse_position = scroll_wheel.position;
3035 self.window.modifiers = scroll_wheel.modifiers;
3036 PlatformInput::ScrollWheel(scroll_wheel)
3037 }
3038 // Translate dragging and dropping of external files from the operating system
3039 // to internal drag and drop events.
3040 PlatformInput::FileDrop(file_drop) => match file_drop {
3041 FileDropEvent::Entered { position, paths } => {
3042 self.window.mouse_position = position;
3043 if self.active_drag.is_none() {
3044 self.active_drag = Some(AnyDrag {
3045 value: Box::new(paths.clone()),
3046 view: self.new_view(|_| paths).into(),
3047 cursor_offset: position,
3048 });
3049 }
3050 PlatformInput::MouseMove(MouseMoveEvent {
3051 position,
3052 pressed_button: Some(MouseButton::Left),
3053 modifiers: Modifiers::default(),
3054 })
3055 }
3056 FileDropEvent::Pending { position } => {
3057 self.window.mouse_position = position;
3058 PlatformInput::MouseMove(MouseMoveEvent {
3059 position,
3060 pressed_button: Some(MouseButton::Left),
3061 modifiers: Modifiers::default(),
3062 })
3063 }
3064 FileDropEvent::Submit { position } => {
3065 self.activate(true);
3066 self.window.mouse_position = position;
3067 PlatformInput::MouseUp(MouseUpEvent {
3068 button: MouseButton::Left,
3069 position,
3070 modifiers: Modifiers::default(),
3071 click_count: 1,
3072 })
3073 }
3074 FileDropEvent::Exited => {
3075 self.active_drag.take();
3076 PlatformInput::FileDrop(FileDropEvent::Exited)
3077 }
3078 },
3079 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
3080 };
3081
3082 if let Some(any_mouse_event) = event.mouse_event() {
3083 self.dispatch_mouse_event(any_mouse_event);
3084 } else if let Some(any_key_event) = event.keyboard_event() {
3085 self.dispatch_key_event(any_key_event);
3086 }
3087
3088 DispatchEventResult {
3089 propagate: self.app.propagate_event,
3090 default_prevented: self.window.default_prevented,
3091 }
3092 }
3093
3094 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
3095 let hit_test = self.window.rendered_frame.hit_test(self.mouse_position());
3096 if hit_test != self.window.mouse_hit_test {
3097 self.window.mouse_hit_test = hit_test;
3098 self.reset_cursor_style();
3099 }
3100
3101 let mut mouse_listeners = mem::take(&mut self.window.rendered_frame.mouse_listeners);
3102
3103 // Capture phase, events bubble from back to front. Handlers for this phase are used for
3104 // special purposes, such as detecting events outside of a given Bounds.
3105 for listener in &mut mouse_listeners {
3106 let listener = listener.as_mut().unwrap();
3107 listener(event, DispatchPhase::Capture, self);
3108 if !self.app.propagate_event {
3109 break;
3110 }
3111 }
3112
3113 // Bubble phase, where most normal handlers do their work.
3114 if self.app.propagate_event {
3115 for listener in mouse_listeners.iter_mut().rev() {
3116 let listener = listener.as_mut().unwrap();
3117 listener(event, DispatchPhase::Bubble, self);
3118 if !self.app.propagate_event {
3119 break;
3120 }
3121 }
3122 }
3123
3124 self.window.rendered_frame.mouse_listeners = mouse_listeners;
3125
3126 if self.has_active_drag() {
3127 if event.is::<MouseMoveEvent>() {
3128 // If this was a mouse move event, redraw the window so that the
3129 // active drag can follow the mouse cursor.
3130 self.refresh();
3131 } else if event.is::<MouseUpEvent>() {
3132 // If this was a mouse up event, cancel the active drag and redraw
3133 // the window.
3134 self.active_drag = None;
3135 self.refresh();
3136 }
3137 }
3138 }
3139
3140 fn dispatch_key_event(&mut self, event: &dyn Any) {
3141 if self.window.dirty.get() {
3142 self.draw();
3143 }
3144
3145 let node_id = self
3146 .window
3147 .focus
3148 .and_then(|focus_id| {
3149 self.window
3150 .rendered_frame
3151 .dispatch_tree
3152 .focusable_node_id(focus_id)
3153 })
3154 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3155
3156 let dispatch_path = self
3157 .window
3158 .rendered_frame
3159 .dispatch_tree
3160 .dispatch_path(node_id);
3161
3162 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3163 let KeymatchResult { bindings, pending } = self
3164 .window
3165 .rendered_frame
3166 .dispatch_tree
3167 .dispatch_key(&key_down_event.keystroke, &dispatch_path);
3168
3169 if pending {
3170 let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3171 if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus
3172 {
3173 currently_pending = PendingInput::default();
3174 }
3175 currently_pending.focus = self.window.focus;
3176 currently_pending
3177 .keystrokes
3178 .push(key_down_event.keystroke.clone());
3179 for binding in bindings {
3180 currently_pending.bindings.push(binding);
3181 }
3182
3183 currently_pending.timer = Some(self.spawn(|mut cx| async move {
3184 cx.background_executor.timer(Duration::from_secs(1)).await;
3185 cx.update(move |cx| {
3186 cx.clear_pending_keystrokes();
3187 let Some(currently_pending) = cx.window.pending_input.take() else {
3188 return;
3189 };
3190 cx.pending_input_changed();
3191 cx.replay_pending_input(currently_pending);
3192 })
3193 .log_err();
3194 }));
3195
3196 self.window.pending_input = Some(currently_pending);
3197 self.pending_input_changed();
3198
3199 self.propagate_event = false;
3200
3201 return;
3202 } else if let Some(currently_pending) = self.window.pending_input.take() {
3203 self.pending_input_changed();
3204 if bindings
3205 .iter()
3206 .all(|binding| !currently_pending.used_by_binding(binding))
3207 {
3208 self.replay_pending_input(currently_pending)
3209 }
3210 }
3211
3212 if !bindings.is_empty() {
3213 self.clear_pending_keystrokes();
3214 }
3215
3216 self.propagate_event = true;
3217 for binding in bindings {
3218 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3219 if !self.propagate_event {
3220 self.dispatch_keystroke_observers(event, Some(binding.action));
3221 return;
3222 }
3223 }
3224 }
3225
3226 self.dispatch_key_down_up_event(event, &dispatch_path);
3227 if !self.propagate_event {
3228 return;
3229 }
3230
3231 self.dispatch_modifiers_changed_event(event, &dispatch_path);
3232 if !self.propagate_event {
3233 return;
3234 }
3235
3236 self.dispatch_keystroke_observers(event, None);
3237 }
3238
3239 fn pending_input_changed(&mut self) {
3240 self.window
3241 .pending_input_observers
3242 .clone()
3243 .retain(&(), |callback| callback(self));
3244 }
3245
3246 fn dispatch_key_down_up_event(
3247 &mut self,
3248 event: &dyn Any,
3249 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3250 ) {
3251 // Capture phase
3252 for node_id in dispatch_path {
3253 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3254
3255 for key_listener in node.key_listeners.clone() {
3256 key_listener(event, DispatchPhase::Capture, self);
3257 if !self.propagate_event {
3258 return;
3259 }
3260 }
3261 }
3262
3263 // Bubble phase
3264 for node_id in dispatch_path.iter().rev() {
3265 // Handle low level key events
3266 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3267 for key_listener in node.key_listeners.clone() {
3268 key_listener(event, DispatchPhase::Bubble, self);
3269 if !self.propagate_event {
3270 return;
3271 }
3272 }
3273 }
3274 }
3275
3276 fn dispatch_modifiers_changed_event(
3277 &mut self,
3278 event: &dyn Any,
3279 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3280 ) {
3281 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3282 return;
3283 };
3284 for node_id in dispatch_path.iter().rev() {
3285 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3286 for listener in node.modifiers_changed_listeners.clone() {
3287 listener(event, self);
3288 if !self.propagate_event {
3289 return;
3290 }
3291 }
3292 }
3293 }
3294
3295 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3296 pub fn has_pending_keystrokes(&self) -> bool {
3297 self.window
3298 .rendered_frame
3299 .dispatch_tree
3300 .has_pending_keystrokes()
3301 }
3302
3303 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3304 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3305 self.window
3306 .pending_input
3307 .as_ref()
3308 .map(|pending_input| pending_input.keystrokes.as_slice())
3309 }
3310
3311 fn replay_pending_input(&mut self, currently_pending: PendingInput) {
3312 let node_id = self
3313 .window
3314 .focus
3315 .and_then(|focus_id| {
3316 self.window
3317 .rendered_frame
3318 .dispatch_tree
3319 .focusable_node_id(focus_id)
3320 })
3321 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3322
3323 if self.window.focus != currently_pending.focus {
3324 return;
3325 }
3326
3327 let input = currently_pending.input();
3328
3329 self.propagate_event = true;
3330 for binding in currently_pending.bindings {
3331 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3332 if !self.propagate_event {
3333 return;
3334 }
3335 }
3336
3337 let dispatch_path = self
3338 .window
3339 .rendered_frame
3340 .dispatch_tree
3341 .dispatch_path(node_id);
3342
3343 for keystroke in currently_pending.keystrokes {
3344 let event = KeyDownEvent {
3345 keystroke,
3346 is_held: false,
3347 };
3348
3349 self.dispatch_key_down_up_event(&event, &dispatch_path);
3350 if !self.propagate_event {
3351 return;
3352 }
3353 }
3354
3355 if !input.is_empty() {
3356 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3357 input_handler.dispatch_input(&input, self);
3358 self.window.platform_window.set_input_handler(input_handler)
3359 }
3360 }
3361 }
3362
3363 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3364 let dispatch_path = self
3365 .window
3366 .rendered_frame
3367 .dispatch_tree
3368 .dispatch_path(node_id);
3369
3370 // Capture phase for global actions.
3371 self.propagate_event = true;
3372 if let Some(mut global_listeners) = self
3373 .global_action_listeners
3374 .remove(&action.as_any().type_id())
3375 {
3376 for listener in &global_listeners {
3377 listener(action.as_any(), DispatchPhase::Capture, self);
3378 if !self.propagate_event {
3379 break;
3380 }
3381 }
3382
3383 global_listeners.extend(
3384 self.global_action_listeners
3385 .remove(&action.as_any().type_id())
3386 .unwrap_or_default(),
3387 );
3388
3389 self.global_action_listeners
3390 .insert(action.as_any().type_id(), global_listeners);
3391 }
3392
3393 if !self.propagate_event {
3394 return;
3395 }
3396
3397 // Capture phase for window actions.
3398 for node_id in &dispatch_path {
3399 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3400 for DispatchActionListener {
3401 action_type,
3402 listener,
3403 } in node.action_listeners.clone()
3404 {
3405 let any_action = action.as_any();
3406 if action_type == any_action.type_id() {
3407 listener(any_action, DispatchPhase::Capture, self);
3408
3409 if !self.propagate_event {
3410 return;
3411 }
3412 }
3413 }
3414 }
3415
3416 // Bubble phase for window actions.
3417 for node_id in dispatch_path.iter().rev() {
3418 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3419 for DispatchActionListener {
3420 action_type,
3421 listener,
3422 } in node.action_listeners.clone()
3423 {
3424 let any_action = action.as_any();
3425 if action_type == any_action.type_id() {
3426 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3427 listener(any_action, DispatchPhase::Bubble, self);
3428
3429 if !self.propagate_event {
3430 return;
3431 }
3432 }
3433 }
3434 }
3435
3436 // Bubble phase for global actions.
3437 if let Some(mut global_listeners) = self
3438 .global_action_listeners
3439 .remove(&action.as_any().type_id())
3440 {
3441 for listener in global_listeners.iter().rev() {
3442 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3443
3444 listener(action.as_any(), DispatchPhase::Bubble, self);
3445 if !self.propagate_event {
3446 break;
3447 }
3448 }
3449
3450 global_listeners.extend(
3451 self.global_action_listeners
3452 .remove(&action.as_any().type_id())
3453 .unwrap_or_default(),
3454 );
3455
3456 self.global_action_listeners
3457 .insert(action.as_any().type_id(), global_listeners);
3458 }
3459 }
3460
3461 /// Register the given handler to be invoked whenever the global of the given type
3462 /// is updated.
3463 pub fn observe_global<G: Global>(
3464 &mut self,
3465 f: impl Fn(&mut WindowContext<'_>) + 'static,
3466 ) -> Subscription {
3467 let window_handle = self.window.handle;
3468 let (subscription, activate) = self.global_observers.insert(
3469 TypeId::of::<G>(),
3470 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3471 );
3472 self.app.defer(move |_| activate());
3473 subscription
3474 }
3475
3476 /// Focus the current window and bring it to the foreground at the platform level.
3477 pub fn activate_window(&self) {
3478 self.window.platform_window.activate();
3479 }
3480
3481 /// Minimize the current window at the platform level.
3482 pub fn minimize_window(&self) {
3483 self.window.platform_window.minimize();
3484 }
3485
3486 /// Toggle full screen status on the current window at the platform level.
3487 pub fn toggle_fullscreen(&self) {
3488 self.window.platform_window.toggle_fullscreen();
3489 }
3490
3491 /// Present a platform dialog.
3492 /// The provided message will be presented, along with buttons for each answer.
3493 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3494 pub fn prompt(
3495 &mut self,
3496 level: PromptLevel,
3497 message: &str,
3498 detail: Option<&str>,
3499 answers: &[&str],
3500 ) -> oneshot::Receiver<usize> {
3501 let prompt_builder = self.app.prompt_builder.take();
3502 let Some(prompt_builder) = prompt_builder else {
3503 unreachable!("Re-entrant window prompting is not supported by GPUI");
3504 };
3505
3506 let receiver = match &prompt_builder {
3507 PromptBuilder::Default => self
3508 .window
3509 .platform_window
3510 .prompt(level, message, detail, answers)
3511 .unwrap_or_else(|| {
3512 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3513 }),
3514 PromptBuilder::Custom(_) => {
3515 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3516 }
3517 };
3518
3519 self.app.prompt_builder = Some(prompt_builder);
3520
3521 receiver
3522 }
3523
3524 fn build_custom_prompt(
3525 &mut self,
3526 prompt_builder: &PromptBuilder,
3527 level: PromptLevel,
3528 message: &str,
3529 detail: Option<&str>,
3530 answers: &[&str],
3531 ) -> oneshot::Receiver<usize> {
3532 let (sender, receiver) = oneshot::channel();
3533 let handle = PromptHandle::new(sender);
3534 let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3535 self.window.prompt = Some(handle);
3536 receiver
3537 }
3538
3539 /// Returns all available actions for the focused element.
3540 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3541 let node_id = self
3542 .window
3543 .focus
3544 .and_then(|focus_id| {
3545 self.window
3546 .rendered_frame
3547 .dispatch_tree
3548 .focusable_node_id(focus_id)
3549 })
3550 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3551
3552 let mut actions = self
3553 .window
3554 .rendered_frame
3555 .dispatch_tree
3556 .available_actions(node_id);
3557 for action_type in self.global_action_listeners.keys() {
3558 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3559 let action = self.actions.build_action_type(action_type).ok();
3560 if let Some(action) = action {
3561 actions.insert(ix, action);
3562 }
3563 }
3564 }
3565 actions
3566 }
3567
3568 /// Returns key bindings that invoke the given action on the currently focused element.
3569 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3570 self.window
3571 .rendered_frame
3572 .dispatch_tree
3573 .bindings_for_action(
3574 action,
3575 &self.window.rendered_frame.dispatch_tree.context_stack,
3576 )
3577 }
3578
3579 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3580 pub fn bindings_for_action_in(
3581 &self,
3582 action: &dyn Action,
3583 focus_handle: &FocusHandle,
3584 ) -> Vec<KeyBinding> {
3585 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3586
3587 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3588 return vec![];
3589 };
3590 let context_stack: Vec<_> = dispatch_tree
3591 .dispatch_path(node_id)
3592 .into_iter()
3593 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3594 .collect();
3595 dispatch_tree.bindings_for_action(action, &context_stack)
3596 }
3597
3598 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3599 pub fn listener_for<V: Render, E>(
3600 &self,
3601 view: &View<V>,
3602 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3603 ) -> impl Fn(&E, &mut WindowContext) + 'static {
3604 let view = view.downgrade();
3605 move |e: &E, cx: &mut WindowContext| {
3606 view.update(cx, |view, cx| f(view, e, cx)).ok();
3607 }
3608 }
3609
3610 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3611 pub fn handler_for<V: Render>(
3612 &self,
3613 view: &View<V>,
3614 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3615 ) -> impl Fn(&mut WindowContext) {
3616 let view = view.downgrade();
3617 move |cx: &mut WindowContext| {
3618 view.update(cx, |view, cx| f(view, cx)).ok();
3619 }
3620 }
3621
3622 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3623 /// If the callback returns false, the window won't be closed.
3624 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3625 let mut this = self.to_async();
3626 self.window
3627 .platform_window
3628 .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3629 }
3630
3631 /// Register an action listener on the window for the next frame. The type of action
3632 /// is determined by the first parameter of the given listener. When the next frame is rendered
3633 /// the listener will be cleared.
3634 ///
3635 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3636 /// a specific need to register a global listener.
3637 pub fn on_action(
3638 &mut self,
3639 action_type: TypeId,
3640 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3641 ) {
3642 self.window
3643 .next_frame
3644 .dispatch_tree
3645 .on_action(action_type, Rc::new(listener));
3646 }
3647}
3648
3649#[cfg(target_os = "windows")]
3650impl WindowContext<'_> {
3651 /// Returns the raw HWND handle for the window.
3652 pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3653 self.window.platform_window.get_raw_handle()
3654 }
3655}
3656
3657impl Context for WindowContext<'_> {
3658 type Result<T> = T;
3659
3660 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3661 where
3662 T: 'static,
3663 {
3664 let slot = self.app.entities.reserve();
3665 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3666 self.entities.insert(slot, model)
3667 }
3668
3669 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3670 self.app.reserve_model()
3671 }
3672
3673 fn insert_model<T: 'static>(
3674 &mut self,
3675 reservation: crate::Reservation<T>,
3676 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3677 ) -> Self::Result<Model<T>> {
3678 self.app.insert_model(reservation, build_model)
3679 }
3680
3681 fn update_model<T: 'static, R>(
3682 &mut self,
3683 model: &Model<T>,
3684 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3685 ) -> R {
3686 let mut entity = self.entities.lease(model);
3687 let result = update(
3688 &mut *entity,
3689 &mut ModelContext::new(&mut *self.app, model.downgrade()),
3690 );
3691 self.entities.end_lease(entity);
3692 result
3693 }
3694
3695 fn read_model<T, R>(
3696 &self,
3697 handle: &Model<T>,
3698 read: impl FnOnce(&T, &AppContext) -> R,
3699 ) -> Self::Result<R>
3700 where
3701 T: 'static,
3702 {
3703 let entity = self.entities.read(handle);
3704 read(entity, &*self.app)
3705 }
3706
3707 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3708 where
3709 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3710 {
3711 if window == self.window.handle {
3712 let root_view = self.window.root_view.clone().unwrap();
3713 Ok(update(root_view, self))
3714 } else {
3715 window.update(self.app, update)
3716 }
3717 }
3718
3719 fn read_window<T, R>(
3720 &self,
3721 window: &WindowHandle<T>,
3722 read: impl FnOnce(View<T>, &AppContext) -> R,
3723 ) -> Result<R>
3724 where
3725 T: 'static,
3726 {
3727 if window.any_handle == self.window.handle {
3728 let root_view = self
3729 .window
3730 .root_view
3731 .clone()
3732 .unwrap()
3733 .downcast::<T>()
3734 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3735 Ok(read(root_view, self))
3736 } else {
3737 self.app.read_window(window, read)
3738 }
3739 }
3740}
3741
3742impl VisualContext for WindowContext<'_> {
3743 fn new_view<V>(
3744 &mut self,
3745 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3746 ) -> Self::Result<View<V>>
3747 where
3748 V: 'static + Render,
3749 {
3750 let slot = self.app.entities.reserve();
3751 let view = View {
3752 model: slot.clone(),
3753 };
3754 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3755 let entity = build_view_state(&mut cx);
3756 cx.entities.insert(slot, entity);
3757
3758 // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3759 fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3760 cx.new_view_observers.clone().retain(&tid, |observer| {
3761 let any_view = view.clone();
3762 (observer)(any_view, cx);
3763 true
3764 });
3765 }
3766 notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3767
3768 view
3769 }
3770
3771 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3772 fn update_view<T: 'static, R>(
3773 &mut self,
3774 view: &View<T>,
3775 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3776 ) -> Self::Result<R> {
3777 let mut lease = self.app.entities.lease(&view.model);
3778 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3779 let result = update(&mut *lease, &mut cx);
3780 cx.app.entities.end_lease(lease);
3781 result
3782 }
3783
3784 fn replace_root_view<V>(
3785 &mut self,
3786 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3787 ) -> Self::Result<View<V>>
3788 where
3789 V: 'static + Render,
3790 {
3791 let view = self.new_view(build_view);
3792 self.window.root_view = Some(view.clone().into());
3793 self.refresh();
3794 view
3795 }
3796
3797 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3798 self.update_view(view, |view, cx| {
3799 view.focus_handle(cx).clone().focus(cx);
3800 })
3801 }
3802
3803 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3804 where
3805 V: ManagedView,
3806 {
3807 self.update_view(view, |_, cx| cx.emit(DismissEvent))
3808 }
3809}
3810
3811impl<'a> std::ops::Deref for WindowContext<'a> {
3812 type Target = AppContext;
3813
3814 fn deref(&self) -> &Self::Target {
3815 self.app
3816 }
3817}
3818
3819impl<'a> std::ops::DerefMut for WindowContext<'a> {
3820 fn deref_mut(&mut self) -> &mut Self::Target {
3821 self.app
3822 }
3823}
3824
3825impl<'a> Borrow<AppContext> for WindowContext<'a> {
3826 fn borrow(&self) -> &AppContext {
3827 self.app
3828 }
3829}
3830
3831impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3832 fn borrow_mut(&mut self) -> &mut AppContext {
3833 self.app
3834 }
3835}
3836
3837/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3838pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3839 #[doc(hidden)]
3840 fn app_mut(&mut self) -> &mut AppContext {
3841 self.borrow_mut()
3842 }
3843
3844 #[doc(hidden)]
3845 fn app(&self) -> &AppContext {
3846 self.borrow()
3847 }
3848
3849 #[doc(hidden)]
3850 fn window(&self) -> &Window {
3851 self.borrow()
3852 }
3853
3854 #[doc(hidden)]
3855 fn window_mut(&mut self) -> &mut Window {
3856 self.borrow_mut()
3857 }
3858}
3859
3860impl Borrow<Window> for WindowContext<'_> {
3861 fn borrow(&self) -> &Window {
3862 self.window
3863 }
3864}
3865
3866impl BorrowMut<Window> for WindowContext<'_> {
3867 fn borrow_mut(&mut self) -> &mut Window {
3868 self.window
3869 }
3870}
3871
3872impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
3873
3874/// Provides access to application state that is specialized for a particular [`View`].
3875/// Allows you to interact with focus, emit events, etc.
3876/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
3877/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
3878pub struct ViewContext<'a, V> {
3879 window_cx: WindowContext<'a>,
3880 view: &'a View<V>,
3881}
3882
3883impl<V> Borrow<AppContext> for ViewContext<'_, V> {
3884 fn borrow(&self) -> &AppContext {
3885 &*self.window_cx.app
3886 }
3887}
3888
3889impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
3890 fn borrow_mut(&mut self) -> &mut AppContext {
3891 &mut *self.window_cx.app
3892 }
3893}
3894
3895impl<V> Borrow<Window> for ViewContext<'_, V> {
3896 fn borrow(&self) -> &Window {
3897 &*self.window_cx.window
3898 }
3899}
3900
3901impl<V> BorrowMut<Window> for ViewContext<'_, V> {
3902 fn borrow_mut(&mut self) -> &mut Window {
3903 &mut *self.window_cx.window
3904 }
3905}
3906
3907impl<'a, V: 'static> ViewContext<'a, V> {
3908 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
3909 Self {
3910 window_cx: WindowContext::new(app, window),
3911 view,
3912 }
3913 }
3914
3915 /// Get the entity_id of this view.
3916 pub fn entity_id(&self) -> EntityId {
3917 self.view.entity_id()
3918 }
3919
3920 /// Get the view pointer underlying this context.
3921 pub fn view(&self) -> &View<V> {
3922 self.view
3923 }
3924
3925 /// Get the model underlying this view.
3926 pub fn model(&self) -> &Model<V> {
3927 &self.view.model
3928 }
3929
3930 /// Access the underlying window context.
3931 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
3932 &mut self.window_cx
3933 }
3934
3935 /// Sets a given callback to be run on the next frame.
3936 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
3937 where
3938 V: 'static,
3939 {
3940 let view = self.view().clone();
3941 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
3942 }
3943
3944 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
3945 /// that are currently on the stack to be returned to the app.
3946 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
3947 let view = self.view().downgrade();
3948 self.window_cx.defer(move |cx| {
3949 view.update(cx, f).ok();
3950 });
3951 }
3952
3953 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
3954 pub fn observe<V2, E>(
3955 &mut self,
3956 entity: &E,
3957 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
3958 ) -> Subscription
3959 where
3960 V2: 'static,
3961 V: 'static,
3962 E: Entity<V2>,
3963 {
3964 let view = self.view().downgrade();
3965 let entity_id = entity.entity_id();
3966 let entity = entity.downgrade();
3967 let window_handle = self.window.handle;
3968 self.app.new_observer(
3969 entity_id,
3970 Box::new(move |cx| {
3971 window_handle
3972 .update(cx, |_, cx| {
3973 if let Some(handle) = E::upgrade_from(&entity) {
3974 view.update(cx, |this, cx| on_notify(this, handle, cx))
3975 .is_ok()
3976 } else {
3977 false
3978 }
3979 })
3980 .unwrap_or(false)
3981 }),
3982 )
3983 }
3984
3985 /// Subscribe to events emitted by another model or view.
3986 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
3987 /// The callback will be invoked with a reference to the current view, a handle to the emitting entity (either a [`View`] or [`Model`]), the event, and a view context for the current view.
3988 pub fn subscribe<V2, E, Evt>(
3989 &mut self,
3990 entity: &E,
3991 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
3992 ) -> Subscription
3993 where
3994 V2: EventEmitter<Evt>,
3995 E: Entity<V2>,
3996 Evt: 'static,
3997 {
3998 let view = self.view().downgrade();
3999 let entity_id = entity.entity_id();
4000 let handle = entity.downgrade();
4001 let window_handle = self.window.handle;
4002 self.app.new_subscription(
4003 entity_id,
4004 (
4005 TypeId::of::<Evt>(),
4006 Box::new(move |event, cx| {
4007 window_handle
4008 .update(cx, |_, cx| {
4009 if let Some(handle) = E::upgrade_from(&handle) {
4010 let event = event.downcast_ref().expect("invalid event type");
4011 view.update(cx, |this, cx| on_event(this, handle, event, cx))
4012 .is_ok()
4013 } else {
4014 false
4015 }
4016 })
4017 .unwrap_or(false)
4018 }),
4019 ),
4020 )
4021 }
4022
4023 /// Register a callback to be invoked when the view is released.
4024 ///
4025 /// The callback receives a handle to the view's window. This handle may be
4026 /// invalid, if the window was closed before the view was released.
4027 pub fn on_release(
4028 &mut self,
4029 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
4030 ) -> Subscription {
4031 let window_handle = self.window.handle;
4032 let (subscription, activate) = self.app.release_listeners.insert(
4033 self.view.model.entity_id,
4034 Box::new(move |this, cx| {
4035 let this = this.downcast_mut().expect("invalid entity type");
4036 on_release(this, window_handle, cx)
4037 }),
4038 );
4039 activate();
4040 subscription
4041 }
4042
4043 /// Register a callback to be invoked when the given Model or View is released.
4044 pub fn observe_release<V2, E>(
4045 &mut self,
4046 entity: &E,
4047 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
4048 ) -> Subscription
4049 where
4050 V: 'static,
4051 V2: 'static,
4052 E: Entity<V2>,
4053 {
4054 let view = self.view().downgrade();
4055 let entity_id = entity.entity_id();
4056 let window_handle = self.window.handle;
4057 let (subscription, activate) = self.app.release_listeners.insert(
4058 entity_id,
4059 Box::new(move |entity, cx| {
4060 let entity = entity.downcast_mut().expect("invalid entity type");
4061 let _ = window_handle.update(cx, |_, cx| {
4062 view.update(cx, |this, cx| on_release(this, entity, cx))
4063 });
4064 }),
4065 );
4066 activate();
4067 subscription
4068 }
4069
4070 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
4071 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
4072 pub fn notify(&mut self) {
4073 self.window_cx.notify(self.view.entity_id());
4074 }
4075
4076 /// Register a callback to be invoked when the window is resized.
4077 pub fn observe_window_bounds(
4078 &mut self,
4079 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4080 ) -> Subscription {
4081 let view = self.view.downgrade();
4082 let (subscription, activate) = self.window.bounds_observers.insert(
4083 (),
4084 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4085 );
4086 activate();
4087 subscription
4088 }
4089
4090 /// Register a callback to be invoked when the window is activated or deactivated.
4091 pub fn observe_window_activation(
4092 &mut self,
4093 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4094 ) -> Subscription {
4095 let view = self.view.downgrade();
4096 let (subscription, activate) = self.window.activation_observers.insert(
4097 (),
4098 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4099 );
4100 activate();
4101 subscription
4102 }
4103
4104 /// Registers a callback to be invoked when the window appearance changes.
4105 pub fn observe_window_appearance(
4106 &mut self,
4107 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4108 ) -> Subscription {
4109 let view = self.view.downgrade();
4110 let (subscription, activate) = self.window.appearance_observers.insert(
4111 (),
4112 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4113 );
4114 activate();
4115 subscription
4116 }
4117
4118 /// Register a callback to be invoked when the window's pending input changes.
4119 pub fn observe_pending_input(
4120 &mut self,
4121 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4122 ) -> Subscription {
4123 let view = self.view.downgrade();
4124 let (subscription, activate) = self.window.pending_input_observers.insert(
4125 (),
4126 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4127 );
4128 activate();
4129 subscription
4130 }
4131
4132 /// Register a listener to be called when the given focus handle receives focus.
4133 /// Returns a subscription and persists until the subscription is dropped.
4134 pub fn on_focus(
4135 &mut self,
4136 handle: &FocusHandle,
4137 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4138 ) -> Subscription {
4139 let view = self.view.downgrade();
4140 let focus_id = handle.id;
4141 let (subscription, activate) =
4142 self.window.new_focus_listener(Box::new(move |event, cx| {
4143 view.update(cx, |view, cx| {
4144 if event.previous_focus_path.last() != Some(&focus_id)
4145 && event.current_focus_path.last() == Some(&focus_id)
4146 {
4147 listener(view, cx)
4148 }
4149 })
4150 .is_ok()
4151 }));
4152 self.app.defer(|_| activate());
4153 subscription
4154 }
4155
4156 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4157 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4158 /// Returns a subscription and persists until the subscription is dropped.
4159 pub fn on_focus_in(
4160 &mut self,
4161 handle: &FocusHandle,
4162 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4163 ) -> Subscription {
4164 let view = self.view.downgrade();
4165 let focus_id = handle.id;
4166 let (subscription, activate) =
4167 self.window.new_focus_listener(Box::new(move |event, cx| {
4168 view.update(cx, |view, cx| {
4169 if event.is_focus_in(focus_id) {
4170 listener(view, cx)
4171 }
4172 })
4173 .is_ok()
4174 }));
4175 self.app.defer(move |_| activate());
4176 subscription
4177 }
4178
4179 /// Register a listener to be called when the given focus handle loses focus.
4180 /// Returns a subscription and persists until the subscription is dropped.
4181 pub fn on_blur(
4182 &mut self,
4183 handle: &FocusHandle,
4184 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4185 ) -> Subscription {
4186 let view = self.view.downgrade();
4187 let focus_id = handle.id;
4188 let (subscription, activate) =
4189 self.window.new_focus_listener(Box::new(move |event, cx| {
4190 view.update(cx, |view, cx| {
4191 if event.previous_focus_path.last() == Some(&focus_id)
4192 && event.current_focus_path.last() != Some(&focus_id)
4193 {
4194 listener(view, cx)
4195 }
4196 })
4197 .is_ok()
4198 }));
4199 self.app.defer(move |_| activate());
4200 subscription
4201 }
4202
4203 /// Register a listener to be called when nothing in the window has focus.
4204 /// This typically happens when the node that was focused is removed from the tree,
4205 /// and this callback lets you chose a default place to restore the users focus.
4206 /// Returns a subscription and persists until the subscription is dropped.
4207 pub fn on_focus_lost(
4208 &mut self,
4209 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4210 ) -> Subscription {
4211 let view = self.view.downgrade();
4212 let (subscription, activate) = self.window.focus_lost_listeners.insert(
4213 (),
4214 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4215 );
4216 activate();
4217 subscription
4218 }
4219
4220 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4221 /// Returns a subscription and persists until the subscription is dropped.
4222 pub fn on_focus_out(
4223 &mut self,
4224 handle: &FocusHandle,
4225 mut listener: impl FnMut(&mut V, FocusOutEvent, &mut ViewContext<V>) + 'static,
4226 ) -> Subscription {
4227 let view = self.view.downgrade();
4228 let focus_id = handle.id;
4229 let (subscription, activate) =
4230 self.window.new_focus_listener(Box::new(move |event, cx| {
4231 view.update(cx, |view, cx| {
4232 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
4233 if event.is_focus_out(focus_id) {
4234 let event = FocusOutEvent {
4235 blurred: WeakFocusHandle {
4236 id: blurred_id,
4237 handles: Arc::downgrade(&cx.window.focus_handles),
4238 },
4239 };
4240 listener(view, event, cx)
4241 }
4242 }
4243 })
4244 .is_ok()
4245 }));
4246 self.app.defer(move |_| activate());
4247 subscription
4248 }
4249
4250 /// Schedule a future to be run asynchronously.
4251 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4252 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4253 /// The returned future will be polled on the main thread.
4254 pub fn spawn<Fut, R>(
4255 &mut self,
4256 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4257 ) -> Task<R>
4258 where
4259 R: 'static,
4260 Fut: Future<Output = R> + 'static,
4261 {
4262 let view = self.view().downgrade();
4263 self.window_cx.spawn(|cx| f(view, cx))
4264 }
4265
4266 /// Register a callback to be invoked when the given global state changes.
4267 pub fn observe_global<G: Global>(
4268 &mut self,
4269 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4270 ) -> Subscription {
4271 let window_handle = self.window.handle;
4272 let view = self.view().downgrade();
4273 let (subscription, activate) = self.global_observers.insert(
4274 TypeId::of::<G>(),
4275 Box::new(move |cx| {
4276 window_handle
4277 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4278 .unwrap_or(false)
4279 }),
4280 );
4281 self.app.defer(move |_| activate());
4282 subscription
4283 }
4284
4285 /// Register a callback to be invoked when the given Action type is dispatched to the window.
4286 pub fn on_action(
4287 &mut self,
4288 action_type: TypeId,
4289 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4290 ) {
4291 let handle = self.view().clone();
4292 self.window_cx
4293 .on_action(action_type, move |action, phase, cx| {
4294 handle.update(cx, |view, cx| {
4295 listener(view, action, phase, cx);
4296 })
4297 });
4298 }
4299
4300 /// Emit an event to be handled by any other views that have subscribed via [ViewContext::subscribe].
4301 pub fn emit<Evt>(&mut self, event: Evt)
4302 where
4303 Evt: 'static,
4304 V: EventEmitter<Evt>,
4305 {
4306 let emitter = self.view.model.entity_id;
4307 self.app.push_effect(Effect::Emit {
4308 emitter,
4309 event_type: TypeId::of::<Evt>(),
4310 event: Box::new(event),
4311 });
4312 }
4313
4314 /// Move focus to the current view, assuming it implements [`FocusableView`].
4315 pub fn focus_self(&mut self)
4316 where
4317 V: FocusableView,
4318 {
4319 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4320 }
4321
4322 /// Convenience method for accessing view state in an event callback.
4323 ///
4324 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4325 /// but it's often useful to be able to access view state in these
4326 /// callbacks. This method provides a convenient way to do so.
4327 pub fn listener<E>(
4328 &self,
4329 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4330 ) -> impl Fn(&E, &mut WindowContext) + 'static {
4331 let view = self.view().downgrade();
4332 move |e: &E, cx: &mut WindowContext| {
4333 view.update(cx, |view, cx| f(view, e, cx)).ok();
4334 }
4335 }
4336}
4337
4338impl<V> Context for ViewContext<'_, V> {
4339 type Result<U> = U;
4340
4341 fn new_model<T: 'static>(
4342 &mut self,
4343 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4344 ) -> Model<T> {
4345 self.window_cx.new_model(build_model)
4346 }
4347
4348 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4349 self.window_cx.reserve_model()
4350 }
4351
4352 fn insert_model<T: 'static>(
4353 &mut self,
4354 reservation: crate::Reservation<T>,
4355 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4356 ) -> Self::Result<Model<T>> {
4357 self.window_cx.insert_model(reservation, build_model)
4358 }
4359
4360 fn update_model<T: 'static, R>(
4361 &mut self,
4362 model: &Model<T>,
4363 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4364 ) -> R {
4365 self.window_cx.update_model(model, update)
4366 }
4367
4368 fn read_model<T, R>(
4369 &self,
4370 handle: &Model<T>,
4371 read: impl FnOnce(&T, &AppContext) -> R,
4372 ) -> Self::Result<R>
4373 where
4374 T: 'static,
4375 {
4376 self.window_cx.read_model(handle, read)
4377 }
4378
4379 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4380 where
4381 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4382 {
4383 self.window_cx.update_window(window, update)
4384 }
4385
4386 fn read_window<T, R>(
4387 &self,
4388 window: &WindowHandle<T>,
4389 read: impl FnOnce(View<T>, &AppContext) -> R,
4390 ) -> Result<R>
4391 where
4392 T: 'static,
4393 {
4394 self.window_cx.read_window(window, read)
4395 }
4396}
4397
4398impl<V: 'static> VisualContext for ViewContext<'_, V> {
4399 fn new_view<W: Render + 'static>(
4400 &mut self,
4401 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4402 ) -> Self::Result<View<W>> {
4403 self.window_cx.new_view(build_view_state)
4404 }
4405
4406 fn update_view<V2: 'static, R>(
4407 &mut self,
4408 view: &View<V2>,
4409 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4410 ) -> Self::Result<R> {
4411 self.window_cx.update_view(view, update)
4412 }
4413
4414 fn replace_root_view<W>(
4415 &mut self,
4416 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4417 ) -> Self::Result<View<W>>
4418 where
4419 W: 'static + Render,
4420 {
4421 self.window_cx.replace_root_view(build_view)
4422 }
4423
4424 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4425 self.window_cx.focus_view(view)
4426 }
4427
4428 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4429 self.window_cx.dismiss_view(view)
4430 }
4431}
4432
4433impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4434 type Target = WindowContext<'a>;
4435
4436 fn deref(&self) -> &Self::Target {
4437 &self.window_cx
4438 }
4439}
4440
4441impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4442 fn deref_mut(&mut self) -> &mut Self::Target {
4443 &mut self.window_cx
4444 }
4445}
4446
4447// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4448slotmap::new_key_type! {
4449 /// A unique identifier for a window.
4450 pub struct WindowId;
4451}
4452
4453impl WindowId {
4454 /// Converts this window ID to a `u64`.
4455 pub fn as_u64(&self) -> u64 {
4456 self.0.as_ffi()
4457 }
4458}
4459
4460/// A handle to a window with a specific root view type.
4461/// Note that this does not keep the window alive on its own.
4462#[derive(Deref, DerefMut)]
4463pub struct WindowHandle<V> {
4464 #[deref]
4465 #[deref_mut]
4466 pub(crate) any_handle: AnyWindowHandle,
4467 state_type: PhantomData<V>,
4468}
4469
4470impl<V: 'static + Render> WindowHandle<V> {
4471 /// Creates a new handle from a window ID.
4472 /// This does not check if the root type of the window is `V`.
4473 pub fn new(id: WindowId) -> Self {
4474 WindowHandle {
4475 any_handle: AnyWindowHandle {
4476 id,
4477 state_type: TypeId::of::<V>(),
4478 },
4479 state_type: PhantomData,
4480 }
4481 }
4482
4483 /// Get the root view out of this window.
4484 ///
4485 /// This will fail if the window is closed or if the root view's type does not match `V`.
4486 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4487 where
4488 C: Context,
4489 {
4490 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4491 root_view
4492 .downcast::<V>()
4493 .map_err(|_| anyhow!("the type of the window's root view has changed"))
4494 }))
4495 }
4496
4497 /// Updates the root view of this window.
4498 ///
4499 /// This will fail if the window has been closed or if the root view's type does not match
4500 pub fn update<C, R>(
4501 &self,
4502 cx: &mut C,
4503 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4504 ) -> Result<R>
4505 where
4506 C: Context,
4507 {
4508 cx.update_window(self.any_handle, |root_view, cx| {
4509 let view = root_view
4510 .downcast::<V>()
4511 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4512 Ok(cx.update_view(&view, update))
4513 })?
4514 }
4515
4516 /// Read the root view out of this window.
4517 ///
4518 /// This will fail if the window is closed or if the root view's type does not match `V`.
4519 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4520 let x = cx
4521 .windows
4522 .get(self.id)
4523 .and_then(|window| {
4524 window
4525 .as_ref()
4526 .and_then(|window| window.root_view.clone())
4527 .map(|root_view| root_view.downcast::<V>())
4528 })
4529 .ok_or_else(|| anyhow!("window not found"))?
4530 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4531
4532 Ok(x.read(cx))
4533 }
4534
4535 /// Read the root view out of this window, with a callback
4536 ///
4537 /// This will fail if the window is closed or if the root view's type does not match `V`.
4538 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4539 where
4540 C: Context,
4541 {
4542 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4543 }
4544
4545 /// Read the root view pointer off of this window.
4546 ///
4547 /// This will fail if the window is closed or if the root view's type does not match `V`.
4548 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4549 where
4550 C: Context,
4551 {
4552 cx.read_window(self, |root_view, _cx| root_view.clone())
4553 }
4554
4555 /// Check if this window is 'active'.
4556 ///
4557 /// Will return `None` if the window is closed or currently
4558 /// borrowed.
4559 pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4560 cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4561 .ok()
4562 }
4563}
4564
4565impl<V> Copy for WindowHandle<V> {}
4566
4567impl<V> Clone for WindowHandle<V> {
4568 fn clone(&self) -> Self {
4569 *self
4570 }
4571}
4572
4573impl<V> PartialEq for WindowHandle<V> {
4574 fn eq(&self, other: &Self) -> bool {
4575 self.any_handle == other.any_handle
4576 }
4577}
4578
4579impl<V> Eq for WindowHandle<V> {}
4580
4581impl<V> Hash for WindowHandle<V> {
4582 fn hash<H: Hasher>(&self, state: &mut H) {
4583 self.any_handle.hash(state);
4584 }
4585}
4586
4587impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4588 fn from(val: WindowHandle<V>) -> Self {
4589 val.any_handle
4590 }
4591}
4592
4593unsafe impl<V> Send for WindowHandle<V> {}
4594unsafe impl<V> Sync for WindowHandle<V> {}
4595
4596/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4597#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4598pub struct AnyWindowHandle {
4599 pub(crate) id: WindowId,
4600 state_type: TypeId,
4601}
4602
4603impl AnyWindowHandle {
4604 /// Get the ID of this window.
4605 pub fn window_id(&self) -> WindowId {
4606 self.id
4607 }
4608
4609 /// Attempt to convert this handle to a window handle with a specific root view type.
4610 /// If the types do not match, this will return `None`.
4611 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4612 if TypeId::of::<T>() == self.state_type {
4613 Some(WindowHandle {
4614 any_handle: *self,
4615 state_type: PhantomData,
4616 })
4617 } else {
4618 None
4619 }
4620 }
4621
4622 /// Updates the state of the root view of this window.
4623 ///
4624 /// This will fail if the window has been closed.
4625 pub fn update<C, R>(
4626 self,
4627 cx: &mut C,
4628 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4629 ) -> Result<R>
4630 where
4631 C: Context,
4632 {
4633 cx.update_window(self, update)
4634 }
4635
4636 /// Read the state of the root view of this window.
4637 ///
4638 /// This will fail if the window has been closed.
4639 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4640 where
4641 C: Context,
4642 T: 'static,
4643 {
4644 let view = self
4645 .downcast::<T>()
4646 .context("the type of the window's root view has changed")?;
4647
4648 cx.read_window(&view, read)
4649 }
4650}
4651
4652/// An identifier for an [`Element`](crate::Element).
4653///
4654/// Can be constructed with a string, a number, or both, as well
4655/// as other internal representations.
4656#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4657pub enum ElementId {
4658 /// The ID of a View element
4659 View(EntityId),
4660 /// An integer ID.
4661 Integer(usize),
4662 /// A string based ID.
4663 Name(SharedString),
4664 /// A UUID.
4665 Uuid(Uuid),
4666 /// An ID that's equated with a focus handle.
4667 FocusHandle(FocusId),
4668 /// A combination of a name and an integer.
4669 NamedInteger(SharedString, usize),
4670}
4671
4672impl Display for ElementId {
4673 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4674 match self {
4675 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4676 ElementId::Integer(ix) => write!(f, "{}", ix)?,
4677 ElementId::Name(name) => write!(f, "{}", name)?,
4678 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4679 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4680 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4681 }
4682
4683 Ok(())
4684 }
4685}
4686
4687impl TryInto<SharedString> for ElementId {
4688 type Error = anyhow::Error;
4689
4690 fn try_into(self) -> anyhow::Result<SharedString> {
4691 if let ElementId::Name(name) = self {
4692 Ok(name)
4693 } else {
4694 Err(anyhow!("element id is not string"))
4695 }
4696 }
4697}
4698
4699impl From<usize> for ElementId {
4700 fn from(id: usize) -> Self {
4701 ElementId::Integer(id)
4702 }
4703}
4704
4705impl From<i32> for ElementId {
4706 fn from(id: i32) -> Self {
4707 Self::Integer(id as usize)
4708 }
4709}
4710
4711impl From<SharedString> for ElementId {
4712 fn from(name: SharedString) -> Self {
4713 ElementId::Name(name)
4714 }
4715}
4716
4717impl From<&'static str> for ElementId {
4718 fn from(name: &'static str) -> Self {
4719 ElementId::Name(name.into())
4720 }
4721}
4722
4723impl<'a> From<&'a FocusHandle> for ElementId {
4724 fn from(handle: &'a FocusHandle) -> Self {
4725 ElementId::FocusHandle(handle.id)
4726 }
4727}
4728
4729impl From<(&'static str, EntityId)> for ElementId {
4730 fn from((name, id): (&'static str, EntityId)) -> Self {
4731 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4732 }
4733}
4734
4735impl From<(&'static str, usize)> for ElementId {
4736 fn from((name, id): (&'static str, usize)) -> Self {
4737 ElementId::NamedInteger(name.into(), id)
4738 }
4739}
4740
4741impl From<(&'static str, u64)> for ElementId {
4742 fn from((name, id): (&'static str, u64)) -> Self {
4743 ElementId::NamedInteger(name.into(), id as usize)
4744 }
4745}
4746
4747impl From<Uuid> for ElementId {
4748 fn from(value: Uuid) -> Self {
4749 Self::Uuid(value)
4750 }
4751}
4752
4753impl From<(&'static str, u32)> for ElementId {
4754 fn from((name, id): (&'static str, u32)) -> Self {
4755 ElementId::NamedInteger(name.into(), id as usize)
4756 }
4757}
4758
4759/// A rectangle to be rendered in the window at the given position and size.
4760/// Passed as an argument [`WindowContext::paint_quad`].
4761#[derive(Clone)]
4762pub struct PaintQuad {
4763 /// The bounds of the quad within the window.
4764 pub bounds: Bounds<Pixels>,
4765 /// The radii of the quad's corners.
4766 pub corner_radii: Corners<Pixels>,
4767 /// The background color of the quad.
4768 pub background: Hsla,
4769 /// The widths of the quad's borders.
4770 pub border_widths: Edges<Pixels>,
4771 /// The color of the quad's borders.
4772 pub border_color: Hsla,
4773}
4774
4775impl PaintQuad {
4776 /// Sets the corner radii of the quad.
4777 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4778 PaintQuad {
4779 corner_radii: corner_radii.into(),
4780 ..self
4781 }
4782 }
4783
4784 /// Sets the border widths of the quad.
4785 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4786 PaintQuad {
4787 border_widths: border_widths.into(),
4788 ..self
4789 }
4790 }
4791
4792 /// Sets the border color of the quad.
4793 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4794 PaintQuad {
4795 border_color: border_color.into(),
4796 ..self
4797 }
4798 }
4799
4800 /// Sets the background color of the quad.
4801 pub fn background(self, background: impl Into<Hsla>) -> Self {
4802 PaintQuad {
4803 background: background.into(),
4804 ..self
4805 }
4806 }
4807}
4808
4809/// Creates a quad with the given parameters.
4810pub fn quad(
4811 bounds: Bounds<Pixels>,
4812 corner_radii: impl Into<Corners<Pixels>>,
4813 background: impl Into<Hsla>,
4814 border_widths: impl Into<Edges<Pixels>>,
4815 border_color: impl Into<Hsla>,
4816) -> PaintQuad {
4817 PaintQuad {
4818 bounds,
4819 corner_radii: corner_radii.into(),
4820 background: background.into(),
4821 border_widths: border_widths.into(),
4822 border_color: border_color.into(),
4823 }
4824}
4825
4826/// Creates a filled quad with the given bounds and background color.
4827pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4828 PaintQuad {
4829 bounds: bounds.into(),
4830 corner_radii: (0.).into(),
4831 background: background.into(),
4832 border_widths: (0.).into(),
4833 border_color: transparent_black(),
4834 }
4835}
4836
4837/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4838pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4839 PaintQuad {
4840 bounds: bounds.into(),
4841 corner_radii: (0.).into(),
4842 background: transparent_black(),
4843 border_widths: (1.).into(),
4844 border_color: border_color.into(),
4845 }
4846}