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