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