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