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