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