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