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 if event.modifiers.number_of_modifiers() == 0 {
3247 let key = match self.window.pending_modifier.modifiers {
3248 modifiers if modifiers.shift => Some("shift"),
3249 modifiers if modifiers.control => Some("control"),
3250 modifiers if modifiers.alt => Some("alt"),
3251 modifiers if modifiers.platform => Some("platform"),
3252 modifiers if modifiers.function => Some("function"),
3253 _ => None,
3254 };
3255 if let Some(key) = key {
3256 keystroke = Some(Keystroke {
3257 key: key.to_string(),
3258 ime_key: None,
3259 modifiers: Modifiers::default(),
3260 });
3261 }
3262 }
3263 }
3264 if self.window.pending_modifier.modifiers.number_of_modifiers() == 0
3265 && event.modifiers.number_of_modifiers() == 1
3266 {
3267 self.window.pending_modifier.saw_keystroke = false
3268 }
3269 self.window.pending_modifier.modifiers = event.modifiers
3270 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
3271 self.window.pending_modifier.saw_keystroke = true;
3272 keystroke = Some(key_down_event.keystroke.clone());
3273 }
3274
3275 let Some(keystroke) = keystroke else {
3276 self.finish_dispatch_key_event(event, dispatch_path);
3277 return;
3278 };
3279
3280 let mut currently_pending = self.window.pending_input.take().unwrap_or_default();
3281 if currently_pending.focus.is_some() && currently_pending.focus != self.window.focus {
3282 currently_pending = PendingInput::default();
3283 }
3284
3285 let match_result = self.window.rendered_frame.dispatch_tree.dispatch_key(
3286 currently_pending.keystrokes,
3287 keystroke,
3288 &dispatch_path,
3289 );
3290 if !match_result.to_replay.is_empty() {
3291 self.replay_pending_input(match_result.to_replay)
3292 }
3293
3294 if !match_result.pending.is_empty() {
3295 currently_pending.keystrokes = match_result.pending;
3296 currently_pending.focus = self.window.focus;
3297 currently_pending.timer = Some(self.spawn(|mut cx| async move {
3298 cx.background_executor.timer(Duration::from_secs(1)).await;
3299 cx.update(move |cx| {
3300 let Some(currently_pending) = cx
3301 .window
3302 .pending_input
3303 .take()
3304 .filter(|pending| pending.focus == cx.window.focus)
3305 else {
3306 return;
3307 };
3308
3309 let dispatch_path = cx
3310 .window
3311 .rendered_frame
3312 .dispatch_tree
3313 .dispatch_path(node_id);
3314
3315 let to_replay = cx
3316 .window
3317 .rendered_frame
3318 .dispatch_tree
3319 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
3320
3321 cx.replay_pending_input(to_replay)
3322 })
3323 .log_err();
3324 }));
3325 self.window.pending_input = Some(currently_pending);
3326 self.pending_input_changed();
3327 self.propagate_event = false;
3328 return;
3329 }
3330
3331 self.pending_input_changed();
3332 self.propagate_event = true;
3333 for binding in match_result.bindings {
3334 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3335 if !self.propagate_event {
3336 self.dispatch_keystroke_observers(event, Some(binding.action));
3337 return;
3338 }
3339 }
3340
3341 self.finish_dispatch_key_event(event, dispatch_path)
3342 }
3343
3344 fn finish_dispatch_key_event(
3345 &mut self,
3346 event: &dyn Any,
3347 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
3348 ) {
3349 self.dispatch_key_down_up_event(event, &dispatch_path);
3350 if !self.propagate_event {
3351 return;
3352 }
3353
3354 self.dispatch_modifiers_changed_event(event, &dispatch_path);
3355 if !self.propagate_event {
3356 return;
3357 }
3358
3359 self.dispatch_keystroke_observers(event, None);
3360 }
3361
3362 fn pending_input_changed(&mut self) {
3363 self.window
3364 .pending_input_observers
3365 .clone()
3366 .retain(&(), |callback| callback(self));
3367 }
3368
3369 fn dispatch_key_down_up_event(
3370 &mut self,
3371 event: &dyn Any,
3372 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3373 ) {
3374 // Capture phase
3375 for node_id in dispatch_path {
3376 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3377
3378 for key_listener in node.key_listeners.clone() {
3379 key_listener(event, DispatchPhase::Capture, self);
3380 if !self.propagate_event {
3381 return;
3382 }
3383 }
3384 }
3385
3386 // Bubble phase
3387 for node_id in dispatch_path.iter().rev() {
3388 // Handle low level key events
3389 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3390 for key_listener in node.key_listeners.clone() {
3391 key_listener(event, DispatchPhase::Bubble, self);
3392 if !self.propagate_event {
3393 return;
3394 }
3395 }
3396 }
3397 }
3398
3399 fn dispatch_modifiers_changed_event(
3400 &mut self,
3401 event: &dyn Any,
3402 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
3403 ) {
3404 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
3405 return;
3406 };
3407 for node_id in dispatch_path.iter().rev() {
3408 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3409 for listener in node.modifiers_changed_listeners.clone() {
3410 listener(event, self);
3411 if !self.propagate_event {
3412 return;
3413 }
3414 }
3415 }
3416 }
3417
3418 /// Determine whether a potential multi-stroke key binding is in progress on this window.
3419 pub fn has_pending_keystrokes(&self) -> bool {
3420 self.window.pending_input.is_some()
3421 }
3422
3423 pub(crate) fn clear_pending_keystrokes(&mut self) {
3424 self.window.pending_input.take();
3425 }
3426
3427 /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
3428 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
3429 self.window
3430 .pending_input
3431 .as_ref()
3432 .map(|pending_input| pending_input.keystrokes.as_slice())
3433 }
3434
3435 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>) {
3436 let node_id = self
3437 .window
3438 .focus
3439 .and_then(|focus_id| {
3440 self.window
3441 .rendered_frame
3442 .dispatch_tree
3443 .focusable_node_id(focus_id)
3444 })
3445 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3446
3447 let dispatch_path = self
3448 .window
3449 .rendered_frame
3450 .dispatch_tree
3451 .dispatch_path(node_id);
3452
3453 'replay: for replay in replays {
3454 let event = KeyDownEvent {
3455 keystroke: replay.keystroke.clone(),
3456 is_held: false,
3457 };
3458
3459 self.propagate_event = true;
3460 for binding in replay.bindings {
3461 self.dispatch_action_on_node(node_id, binding.action.as_ref());
3462 if !self.propagate_event {
3463 self.dispatch_keystroke_observers(&event, Some(binding.action));
3464 continue 'replay;
3465 }
3466 }
3467
3468 self.dispatch_key_down_up_event(&event, &dispatch_path);
3469 if !self.propagate_event {
3470 continue 'replay;
3471 }
3472 if let Some(input) = replay.keystroke.ime_key.as_ref().cloned() {
3473 if let Some(mut input_handler) = self.window.platform_window.take_input_handler() {
3474 input_handler.dispatch_input(&input, self);
3475 self.window.platform_window.set_input_handler(input_handler)
3476 }
3477 }
3478 }
3479 }
3480
3481 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: &dyn Action) {
3482 let dispatch_path = self
3483 .window
3484 .rendered_frame
3485 .dispatch_tree
3486 .dispatch_path(node_id);
3487
3488 // Capture phase for global actions.
3489 self.propagate_event = true;
3490 if let Some(mut global_listeners) = self
3491 .global_action_listeners
3492 .remove(&action.as_any().type_id())
3493 {
3494 for listener in &global_listeners {
3495 listener(action.as_any(), DispatchPhase::Capture, self);
3496 if !self.propagate_event {
3497 break;
3498 }
3499 }
3500
3501 global_listeners.extend(
3502 self.global_action_listeners
3503 .remove(&action.as_any().type_id())
3504 .unwrap_or_default(),
3505 );
3506
3507 self.global_action_listeners
3508 .insert(action.as_any().type_id(), global_listeners);
3509 }
3510
3511 if !self.propagate_event {
3512 return;
3513 }
3514
3515 // Capture phase for window actions.
3516 for node_id in &dispatch_path {
3517 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3518 for DispatchActionListener {
3519 action_type,
3520 listener,
3521 } in node.action_listeners.clone()
3522 {
3523 let any_action = action.as_any();
3524 if action_type == any_action.type_id() {
3525 listener(any_action, DispatchPhase::Capture, self);
3526
3527 if !self.propagate_event {
3528 return;
3529 }
3530 }
3531 }
3532 }
3533
3534 // Bubble phase for window actions.
3535 for node_id in dispatch_path.iter().rev() {
3536 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
3537 for DispatchActionListener {
3538 action_type,
3539 listener,
3540 } in node.action_listeners.clone()
3541 {
3542 let any_action = action.as_any();
3543 if action_type == any_action.type_id() {
3544 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3545 listener(any_action, DispatchPhase::Bubble, self);
3546
3547 if !self.propagate_event {
3548 return;
3549 }
3550 }
3551 }
3552 }
3553
3554 // Bubble phase for global actions.
3555 if let Some(mut global_listeners) = self
3556 .global_action_listeners
3557 .remove(&action.as_any().type_id())
3558 {
3559 for listener in global_listeners.iter().rev() {
3560 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
3561
3562 listener(action.as_any(), DispatchPhase::Bubble, self);
3563 if !self.propagate_event {
3564 break;
3565 }
3566 }
3567
3568 global_listeners.extend(
3569 self.global_action_listeners
3570 .remove(&action.as_any().type_id())
3571 .unwrap_or_default(),
3572 );
3573
3574 self.global_action_listeners
3575 .insert(action.as_any().type_id(), global_listeners);
3576 }
3577 }
3578
3579 /// Register the given handler to be invoked whenever the global of the given type
3580 /// is updated.
3581 pub fn observe_global<G: Global>(
3582 &mut self,
3583 f: impl Fn(&mut WindowContext<'_>) + 'static,
3584 ) -> Subscription {
3585 let window_handle = self.window.handle;
3586 let (subscription, activate) = self.global_observers.insert(
3587 TypeId::of::<G>(),
3588 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
3589 );
3590 self.app.defer(move |_| activate());
3591 subscription
3592 }
3593
3594 /// Focus the current window and bring it to the foreground at the platform level.
3595 pub fn activate_window(&self) {
3596 self.window.platform_window.activate();
3597 }
3598
3599 /// Minimize the current window at the platform level.
3600 pub fn minimize_window(&self) {
3601 self.window.platform_window.minimize();
3602 }
3603
3604 /// Toggle full screen status on the current window at the platform level.
3605 pub fn toggle_fullscreen(&self) {
3606 self.window.platform_window.toggle_fullscreen();
3607 }
3608
3609 /// Updates the IME panel position suggestions for languages like japanese, chinese.
3610 pub fn invalidate_character_coordinates(&mut self) {
3611 self.on_next_frame(|cx| {
3612 if let Some(mut input_handler) = cx.window.platform_window.take_input_handler() {
3613 if let Some(bounds) = input_handler.selected_bounds(cx) {
3614 cx.window.platform_window.update_ime_position(bounds);
3615 }
3616 cx.window.platform_window.set_input_handler(input_handler);
3617 }
3618 });
3619 }
3620
3621 /// Present a platform dialog.
3622 /// The provided message will be presented, along with buttons for each answer.
3623 /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
3624 pub fn prompt(
3625 &mut self,
3626 level: PromptLevel,
3627 message: &str,
3628 detail: Option<&str>,
3629 answers: &[&str],
3630 ) -> oneshot::Receiver<usize> {
3631 let prompt_builder = self.app.prompt_builder.take();
3632 let Some(prompt_builder) = prompt_builder else {
3633 unreachable!("Re-entrant window prompting is not supported by GPUI");
3634 };
3635
3636 let receiver = match &prompt_builder {
3637 PromptBuilder::Default => self
3638 .window
3639 .platform_window
3640 .prompt(level, message, detail, answers)
3641 .unwrap_or_else(|| {
3642 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3643 }),
3644 PromptBuilder::Custom(_) => {
3645 self.build_custom_prompt(&prompt_builder, level, message, detail, answers)
3646 }
3647 };
3648
3649 self.app.prompt_builder = Some(prompt_builder);
3650
3651 receiver
3652 }
3653
3654 fn build_custom_prompt(
3655 &mut self,
3656 prompt_builder: &PromptBuilder,
3657 level: PromptLevel,
3658 message: &str,
3659 detail: Option<&str>,
3660 answers: &[&str],
3661 ) -> oneshot::Receiver<usize> {
3662 let (sender, receiver) = oneshot::channel();
3663 let handle = PromptHandle::new(sender);
3664 let handle = (prompt_builder)(level, message, detail, answers, handle, self);
3665 self.window.prompt = Some(handle);
3666 receiver
3667 }
3668
3669 /// Returns all available actions for the focused element.
3670 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
3671 let node_id = self
3672 .window
3673 .focus
3674 .and_then(|focus_id| {
3675 self.window
3676 .rendered_frame
3677 .dispatch_tree
3678 .focusable_node_id(focus_id)
3679 })
3680 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
3681
3682 let mut actions = self
3683 .window
3684 .rendered_frame
3685 .dispatch_tree
3686 .available_actions(node_id);
3687 for action_type in self.global_action_listeners.keys() {
3688 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
3689 let action = self.actions.build_action_type(action_type).ok();
3690 if let Some(action) = action {
3691 actions.insert(ix, action);
3692 }
3693 }
3694 }
3695 actions
3696 }
3697
3698 /// Returns key bindings that invoke the given action on the currently focused element.
3699 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
3700 self.window
3701 .rendered_frame
3702 .dispatch_tree
3703 .bindings_for_action(
3704 action,
3705 &self.window.rendered_frame.dispatch_tree.context_stack,
3706 )
3707 }
3708
3709 /// Returns any bindings that would invoke the given action on the given focus handle if it were focused.
3710 pub fn bindings_for_action_in(
3711 &self,
3712 action: &dyn Action,
3713 focus_handle: &FocusHandle,
3714 ) -> Vec<KeyBinding> {
3715 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
3716
3717 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
3718 return vec![];
3719 };
3720 let context_stack: Vec<_> = dispatch_tree
3721 .dispatch_path(node_id)
3722 .into_iter()
3723 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
3724 .collect();
3725 dispatch_tree.bindings_for_action(action, &context_stack)
3726 }
3727
3728 /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
3729 pub fn listener_for<V: Render, E>(
3730 &self,
3731 view: &View<V>,
3732 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
3733 ) -> impl Fn(&E, &mut WindowContext) + 'static {
3734 let view = view.downgrade();
3735 move |e: &E, cx: &mut WindowContext| {
3736 view.update(cx, |view, cx| f(view, e, cx)).ok();
3737 }
3738 }
3739
3740 /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
3741 pub fn handler_for<V: Render>(
3742 &self,
3743 view: &View<V>,
3744 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
3745 ) -> impl Fn(&mut WindowContext) {
3746 let view = view.downgrade();
3747 move |cx: &mut WindowContext| {
3748 view.update(cx, |view, cx| f(view, cx)).ok();
3749 }
3750 }
3751
3752 /// Register a callback that can interrupt the closing of the current window based the returned boolean.
3753 /// If the callback returns false, the window won't be closed.
3754 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
3755 let mut this = self.to_async();
3756 self.window
3757 .platform_window
3758 .on_should_close(Box::new(move || this.update(|cx| f(cx)).unwrap_or(true)))
3759 }
3760
3761 /// Register an action listener on the window for the next frame. The type of action
3762 /// is determined by the first parameter of the given listener. When the next frame is rendered
3763 /// the listener will be cleared.
3764 ///
3765 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
3766 /// a specific need to register a global listener.
3767 pub fn on_action(
3768 &mut self,
3769 action_type: TypeId,
3770 listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
3771 ) {
3772 self.window
3773 .next_frame
3774 .dispatch_tree
3775 .on_action(action_type, Rc::new(listener));
3776 }
3777
3778 /// Read information about the GPU backing this window.
3779 /// Currently returns None on Mac and Windows.
3780 pub fn gpu_specs(&self) -> Option<GPUSpecs> {
3781 self.window.platform_window.gpu_specs()
3782 }
3783}
3784
3785#[cfg(target_os = "windows")]
3786impl WindowContext<'_> {
3787 /// Returns the raw HWND handle for the window.
3788 pub fn get_raw_handle(&self) -> windows::Win32::Foundation::HWND {
3789 self.window.platform_window.get_raw_handle()
3790 }
3791}
3792
3793impl Context for WindowContext<'_> {
3794 type Result<T> = T;
3795
3796 fn new_model<T>(&mut self, build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T) -> Model<T>
3797 where
3798 T: 'static,
3799 {
3800 let slot = self.app.entities.reserve();
3801 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
3802 self.entities.insert(slot, model)
3803 }
3804
3805 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
3806 self.app.reserve_model()
3807 }
3808
3809 fn insert_model<T: 'static>(
3810 &mut self,
3811 reservation: crate::Reservation<T>,
3812 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
3813 ) -> Self::Result<Model<T>> {
3814 self.app.insert_model(reservation, build_model)
3815 }
3816
3817 fn update_model<T: 'static, R>(
3818 &mut self,
3819 model: &Model<T>,
3820 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
3821 ) -> R {
3822 let mut entity = self.entities.lease(model);
3823 let result = update(
3824 &mut *entity,
3825 &mut ModelContext::new(&mut *self.app, model.downgrade()),
3826 );
3827 self.entities.end_lease(entity);
3828 result
3829 }
3830
3831 fn read_model<T, R>(
3832 &self,
3833 handle: &Model<T>,
3834 read: impl FnOnce(&T, &AppContext) -> R,
3835 ) -> Self::Result<R>
3836 where
3837 T: 'static,
3838 {
3839 let entity = self.entities.read(handle);
3840 read(entity, &*self.app)
3841 }
3842
3843 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
3844 where
3845 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
3846 {
3847 if window == self.window.handle {
3848 let root_view = self.window.root_view.clone().unwrap();
3849 Ok(update(root_view, self))
3850 } else {
3851 window.update(self.app, update)
3852 }
3853 }
3854
3855 fn read_window<T, R>(
3856 &self,
3857 window: &WindowHandle<T>,
3858 read: impl FnOnce(View<T>, &AppContext) -> R,
3859 ) -> Result<R>
3860 where
3861 T: 'static,
3862 {
3863 if window.any_handle == self.window.handle {
3864 let root_view = self
3865 .window
3866 .root_view
3867 .clone()
3868 .unwrap()
3869 .downcast::<T>()
3870 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
3871 Ok(read(root_view, self))
3872 } else {
3873 self.app.read_window(window, read)
3874 }
3875 }
3876}
3877
3878impl VisualContext for WindowContext<'_> {
3879 fn new_view<V>(
3880 &mut self,
3881 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3882 ) -> Self::Result<View<V>>
3883 where
3884 V: 'static + Render,
3885 {
3886 let slot = self.app.entities.reserve();
3887 let view = View {
3888 model: slot.clone(),
3889 };
3890 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
3891 let entity = build_view_state(&mut cx);
3892 cx.entities.insert(slot, entity);
3893
3894 // Non-generic part to avoid leaking SubscriberSet to invokers of `new_view`.
3895 fn notify_observers(cx: &mut WindowContext, tid: TypeId, view: AnyView) {
3896 cx.new_view_observers.clone().retain(&tid, |observer| {
3897 let any_view = view.clone();
3898 (observer)(any_view, cx);
3899 true
3900 });
3901 }
3902 notify_observers(self, TypeId::of::<V>(), AnyView::from(view.clone()));
3903
3904 view
3905 }
3906
3907 /// Updates the given view. Prefer calling [`View::update`] instead, which calls this method.
3908 fn update_view<T: 'static, R>(
3909 &mut self,
3910 view: &View<T>,
3911 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
3912 ) -> Self::Result<R> {
3913 let mut lease = self.app.entities.lease(&view.model);
3914 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, view);
3915 let result = update(&mut *lease, &mut cx);
3916 cx.app.entities.end_lease(lease);
3917 result
3918 }
3919
3920 fn replace_root_view<V>(
3921 &mut self,
3922 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
3923 ) -> Self::Result<View<V>>
3924 where
3925 V: 'static + Render,
3926 {
3927 let view = self.new_view(build_view);
3928 self.window.root_view = Some(view.clone().into());
3929 self.refresh();
3930 view
3931 }
3932
3933 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
3934 self.update_view(view, |view, cx| {
3935 view.focus_handle(cx).clone().focus(cx);
3936 })
3937 }
3938
3939 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
3940 where
3941 V: ManagedView,
3942 {
3943 self.update_view(view, |_, cx| cx.emit(DismissEvent))
3944 }
3945}
3946
3947impl<'a> std::ops::Deref for WindowContext<'a> {
3948 type Target = AppContext;
3949
3950 fn deref(&self) -> &Self::Target {
3951 self.app
3952 }
3953}
3954
3955impl<'a> std::ops::DerefMut for WindowContext<'a> {
3956 fn deref_mut(&mut self) -> &mut Self::Target {
3957 self.app
3958 }
3959}
3960
3961impl<'a> Borrow<AppContext> for WindowContext<'a> {
3962 fn borrow(&self) -> &AppContext {
3963 self.app
3964 }
3965}
3966
3967impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
3968 fn borrow_mut(&mut self) -> &mut AppContext {
3969 self.app
3970 }
3971}
3972
3973/// This trait contains functionality that is shared across [`ViewContext`] and [`WindowContext`]
3974pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
3975 #[doc(hidden)]
3976 fn app_mut(&mut self) -> &mut AppContext {
3977 self.borrow_mut()
3978 }
3979
3980 #[doc(hidden)]
3981 fn app(&self) -> &AppContext {
3982 self.borrow()
3983 }
3984
3985 #[doc(hidden)]
3986 fn window(&self) -> &Window {
3987 self.borrow()
3988 }
3989
3990 #[doc(hidden)]
3991 fn window_mut(&mut self) -> &mut Window {
3992 self.borrow_mut()
3993 }
3994}
3995
3996impl Borrow<Window> for WindowContext<'_> {
3997 fn borrow(&self) -> &Window {
3998 self.window
3999 }
4000}
4001
4002impl BorrowMut<Window> for WindowContext<'_> {
4003 fn borrow_mut(&mut self) -> &mut Window {
4004 self.window
4005 }
4006}
4007
4008impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
4009
4010/// Provides access to application state that is specialized for a particular [`View`].
4011/// Allows you to interact with focus, emit events, etc.
4012/// ViewContext also derefs to [`WindowContext`], giving you access to all of its methods as well.
4013/// When you call [`View::update`], you're passed a `&mut V` and an `&mut ViewContext<V>`.
4014pub struct ViewContext<'a, V> {
4015 window_cx: WindowContext<'a>,
4016 view: &'a View<V>,
4017}
4018
4019impl<V> Borrow<AppContext> for ViewContext<'_, V> {
4020 fn borrow(&self) -> &AppContext {
4021 &*self.window_cx.app
4022 }
4023}
4024
4025impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
4026 fn borrow_mut(&mut self) -> &mut AppContext {
4027 &mut *self.window_cx.app
4028 }
4029}
4030
4031impl<V> Borrow<Window> for ViewContext<'_, V> {
4032 fn borrow(&self) -> &Window {
4033 &*self.window_cx.window
4034 }
4035}
4036
4037impl<V> BorrowMut<Window> for ViewContext<'_, V> {
4038 fn borrow_mut(&mut self) -> &mut Window {
4039 &mut *self.window_cx.window
4040 }
4041}
4042
4043impl<'a, V: 'static> ViewContext<'a, V> {
4044 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
4045 Self {
4046 window_cx: WindowContext::new(app, window),
4047 view,
4048 }
4049 }
4050
4051 /// Get the entity_id of this view.
4052 pub fn entity_id(&self) -> EntityId {
4053 self.view.entity_id()
4054 }
4055
4056 /// Get the view pointer underlying this context.
4057 pub fn view(&self) -> &View<V> {
4058 self.view
4059 }
4060
4061 /// Get the model underlying this view.
4062 pub fn model(&self) -> &Model<V> {
4063 &self.view.model
4064 }
4065
4066 /// Access the underlying window context.
4067 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
4068 &mut self.window_cx
4069 }
4070
4071 /// Sets a given callback to be run on the next frame.
4072 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
4073 where
4074 V: 'static,
4075 {
4076 let view = self.view().clone();
4077 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
4078 }
4079
4080 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
4081 /// that are currently on the stack to be returned to the app.
4082 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
4083 let view = self.view().downgrade();
4084 self.window_cx.defer(move |cx| {
4085 view.update(cx, f).ok();
4086 });
4087 }
4088
4089 /// Observe another model or view for changes to its state, as tracked by [`ModelContext::notify`].
4090 pub fn observe<V2, E>(
4091 &mut self,
4092 entity: &E,
4093 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
4094 ) -> Subscription
4095 where
4096 V2: 'static,
4097 V: 'static,
4098 E: Entity<V2>,
4099 {
4100 let view = self.view().downgrade();
4101 let entity_id = entity.entity_id();
4102 let entity = entity.downgrade();
4103 let window_handle = self.window.handle;
4104 self.app.new_observer(
4105 entity_id,
4106 Box::new(move |cx| {
4107 window_handle
4108 .update(cx, |_, cx| {
4109 if let Some(handle) = E::upgrade_from(&entity) {
4110 view.update(cx, |this, cx| on_notify(this, handle, cx))
4111 .is_ok()
4112 } else {
4113 false
4114 }
4115 })
4116 .unwrap_or(false)
4117 }),
4118 )
4119 }
4120
4121 /// Subscribe to events emitted by another model or view.
4122 /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
4123 /// 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.
4124 pub fn subscribe<V2, E, Evt>(
4125 &mut self,
4126 entity: &E,
4127 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
4128 ) -> Subscription
4129 where
4130 V2: EventEmitter<Evt>,
4131 E: Entity<V2>,
4132 Evt: 'static,
4133 {
4134 let view = self.view().downgrade();
4135 let entity_id = entity.entity_id();
4136 let handle = entity.downgrade();
4137 let window_handle = self.window.handle;
4138 self.app.new_subscription(
4139 entity_id,
4140 (
4141 TypeId::of::<Evt>(),
4142 Box::new(move |event, cx| {
4143 window_handle
4144 .update(cx, |_, cx| {
4145 if let Some(handle) = E::upgrade_from(&handle) {
4146 let event = event.downcast_ref().expect("invalid event type");
4147 view.update(cx, |this, cx| on_event(this, handle, event, cx))
4148 .is_ok()
4149 } else {
4150 false
4151 }
4152 })
4153 .unwrap_or(false)
4154 }),
4155 ),
4156 )
4157 }
4158
4159 /// Register a callback to be invoked when the view is released.
4160 ///
4161 /// The callback receives a handle to the view's window. This handle may be
4162 /// invalid, if the window was closed before the view was released.
4163 pub fn on_release(
4164 &mut self,
4165 on_release: impl FnOnce(&mut V, AnyWindowHandle, &mut AppContext) + 'static,
4166 ) -> Subscription {
4167 let window_handle = self.window.handle;
4168 let (subscription, activate) = self.app.release_listeners.insert(
4169 self.view.model.entity_id,
4170 Box::new(move |this, cx| {
4171 let this = this.downcast_mut().expect("invalid entity type");
4172 on_release(this, window_handle, cx)
4173 }),
4174 );
4175 activate();
4176 subscription
4177 }
4178
4179 /// Register a callback to be invoked when the given Model or View is released.
4180 pub fn observe_release<V2, E>(
4181 &mut self,
4182 entity: &E,
4183 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
4184 ) -> Subscription
4185 where
4186 V: 'static,
4187 V2: 'static,
4188 E: Entity<V2>,
4189 {
4190 let view = self.view().downgrade();
4191 let entity_id = entity.entity_id();
4192 let window_handle = self.window.handle;
4193 let (subscription, activate) = self.app.release_listeners.insert(
4194 entity_id,
4195 Box::new(move |entity, cx| {
4196 let entity = entity.downcast_mut().expect("invalid entity type");
4197 let _ = window_handle.update(cx, |_, cx| {
4198 view.update(cx, |this, cx| on_release(this, entity, cx))
4199 });
4200 }),
4201 );
4202 activate();
4203 subscription
4204 }
4205
4206 /// Indicate that this view has changed, which will invoke any observers and also mark the window as dirty.
4207 /// If this view or any of its ancestors are *cached*, notifying it will cause it or its ancestors to be redrawn.
4208 pub fn notify(&mut self) {
4209 self.window_cx.notify(self.view.entity_id());
4210 }
4211
4212 /// Register a callback to be invoked when the window is resized.
4213 pub fn observe_window_bounds(
4214 &mut self,
4215 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4216 ) -> Subscription {
4217 let view = self.view.downgrade();
4218 let (subscription, activate) = self.window.bounds_observers.insert(
4219 (),
4220 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4221 );
4222 activate();
4223 subscription
4224 }
4225
4226 /// Register a callback to be invoked when the window is activated or deactivated.
4227 pub fn observe_window_activation(
4228 &mut self,
4229 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4230 ) -> Subscription {
4231 let view = self.view.downgrade();
4232 let (subscription, activate) = self.window.activation_observers.insert(
4233 (),
4234 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4235 );
4236 activate();
4237 subscription
4238 }
4239
4240 /// Registers a callback to be invoked when the window appearance changes.
4241 pub fn observe_window_appearance(
4242 &mut self,
4243 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4244 ) -> Subscription {
4245 let view = self.view.downgrade();
4246 let (subscription, activate) = self.window.appearance_observers.insert(
4247 (),
4248 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4249 );
4250 activate();
4251 subscription
4252 }
4253
4254 /// Register a callback to be invoked when the window's pending input changes.
4255 pub fn observe_pending_input(
4256 &mut self,
4257 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4258 ) -> Subscription {
4259 let view = self.view.downgrade();
4260 let (subscription, activate) = self.window.pending_input_observers.insert(
4261 (),
4262 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
4263 );
4264 activate();
4265 subscription
4266 }
4267
4268 /// Register a listener to be called when the given focus handle receives focus.
4269 /// Returns a subscription and persists until the subscription is dropped.
4270 pub fn on_focus(
4271 &mut self,
4272 handle: &FocusHandle,
4273 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4274 ) -> Subscription {
4275 let view = self.view.downgrade();
4276 let focus_id = handle.id;
4277 let (subscription, activate) =
4278 self.window.new_focus_listener(Box::new(move |event, cx| {
4279 view.update(cx, |view, cx| {
4280 if event.previous_focus_path.last() != Some(&focus_id)
4281 && event.current_focus_path.last() == Some(&focus_id)
4282 {
4283 listener(view, cx)
4284 }
4285 })
4286 .is_ok()
4287 }));
4288 self.app.defer(|_| activate());
4289 subscription
4290 }
4291
4292 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4293 /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4294 /// Returns a subscription and persists until the subscription is dropped.
4295 pub fn on_focus_in(
4296 &mut self,
4297 handle: &FocusHandle,
4298 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4299 ) -> Subscription {
4300 let view = self.view.downgrade();
4301 let focus_id = handle.id;
4302 let (subscription, activate) =
4303 self.window.new_focus_listener(Box::new(move |event, cx| {
4304 view.update(cx, |view, cx| {
4305 if event.is_focus_in(focus_id) {
4306 listener(view, cx)
4307 }
4308 })
4309 .is_ok()
4310 }));
4311 self.app.defer(move |_| activate());
4312 subscription
4313 }
4314
4315 /// Register a listener to be called when the given focus handle loses focus.
4316 /// Returns a subscription and persists until the subscription is dropped.
4317 pub fn on_blur(
4318 &mut self,
4319 handle: &FocusHandle,
4320 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4321 ) -> Subscription {
4322 let view = self.view.downgrade();
4323 let focus_id = handle.id;
4324 let (subscription, activate) =
4325 self.window.new_focus_listener(Box::new(move |event, cx| {
4326 view.update(cx, |view, cx| {
4327 if event.previous_focus_path.last() == Some(&focus_id)
4328 && event.current_focus_path.last() != Some(&focus_id)
4329 {
4330 listener(view, cx)
4331 }
4332 })
4333 .is_ok()
4334 }));
4335 self.app.defer(move |_| activate());
4336 subscription
4337 }
4338
4339 /// Register a listener to be called when nothing in the window has focus.
4340 /// This typically happens when the node that was focused is removed from the tree,
4341 /// and this callback lets you chose a default place to restore the users focus.
4342 /// Returns a subscription and persists until the subscription is dropped.
4343 pub fn on_focus_lost(
4344 &mut self,
4345 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
4346 ) -> Subscription {
4347 let view = self.view.downgrade();
4348 let (subscription, activate) = self.window.focus_lost_listeners.insert(
4349 (),
4350 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
4351 );
4352 activate();
4353 subscription
4354 }
4355
4356 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4357 /// Returns a subscription and persists until the subscription is dropped.
4358 pub fn on_focus_out(
4359 &mut self,
4360 handle: &FocusHandle,
4361 mut listener: impl FnMut(&mut V, FocusOutEvent, &mut ViewContext<V>) + 'static,
4362 ) -> Subscription {
4363 let view = self.view.downgrade();
4364 let focus_id = handle.id;
4365 let (subscription, activate) =
4366 self.window.new_focus_listener(Box::new(move |event, cx| {
4367 view.update(cx, |view, cx| {
4368 if let Some(blurred_id) = event.previous_focus_path.last().copied() {
4369 if event.is_focus_out(focus_id) {
4370 let event = FocusOutEvent {
4371 blurred: WeakFocusHandle {
4372 id: blurred_id,
4373 handles: Arc::downgrade(&cx.window.focus_handles),
4374 },
4375 };
4376 listener(view, event, cx)
4377 }
4378 }
4379 })
4380 .is_ok()
4381 }));
4382 self.app.defer(move |_| activate());
4383 subscription
4384 }
4385
4386 /// Schedule a future to be run asynchronously.
4387 /// The given callback is invoked with a [`WeakView<V>`] to avoid leaking the view for a long-running process.
4388 /// It's also given an [`AsyncWindowContext`], which can be used to access the state of the view across await points.
4389 /// The returned future will be polled on the main thread.
4390 pub fn spawn<Fut, R>(
4391 &mut self,
4392 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
4393 ) -> Task<R>
4394 where
4395 R: 'static,
4396 Fut: Future<Output = R> + 'static,
4397 {
4398 let view = self.view().downgrade();
4399 self.window_cx.spawn(|cx| f(view, cx))
4400 }
4401
4402 /// Register a callback to be invoked when the given global state changes.
4403 pub fn observe_global<G: Global>(
4404 &mut self,
4405 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
4406 ) -> Subscription {
4407 let window_handle = self.window.handle;
4408 let view = self.view().downgrade();
4409 let (subscription, activate) = self.global_observers.insert(
4410 TypeId::of::<G>(),
4411 Box::new(move |cx| {
4412 window_handle
4413 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
4414 .unwrap_or(false)
4415 }),
4416 );
4417 self.app.defer(move |_| activate());
4418 subscription
4419 }
4420
4421 /// Register a callback to be invoked when the given Action type is dispatched to the window.
4422 pub fn on_action(
4423 &mut self,
4424 action_type: TypeId,
4425 listener: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
4426 ) {
4427 let handle = self.view().clone();
4428 self.window_cx
4429 .on_action(action_type, move |action, phase, cx| {
4430 handle.update(cx, |view, cx| {
4431 listener(view, action, phase, cx);
4432 })
4433 });
4434 }
4435
4436 /// Emit an event to be handled by any other views that have subscribed via [ViewContext::subscribe].
4437 pub fn emit<Evt>(&mut self, event: Evt)
4438 where
4439 Evt: 'static,
4440 V: EventEmitter<Evt>,
4441 {
4442 let emitter = self.view.model.entity_id;
4443 self.app.push_effect(Effect::Emit {
4444 emitter,
4445 event_type: TypeId::of::<Evt>(),
4446 event: Box::new(event),
4447 });
4448 }
4449
4450 /// Move focus to the current view, assuming it implements [`FocusableView`].
4451 pub fn focus_self(&mut self)
4452 where
4453 V: FocusableView,
4454 {
4455 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
4456 }
4457
4458 /// Convenience method for accessing view state in an event callback.
4459 ///
4460 /// Many GPUI callbacks take the form of `Fn(&E, &mut WindowContext)`,
4461 /// but it's often useful to be able to access view state in these
4462 /// callbacks. This method provides a convenient way to do so.
4463 pub fn listener<E: ?Sized>(
4464 &self,
4465 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
4466 ) -> impl Fn(&E, &mut WindowContext) + 'static {
4467 let view = self.view().downgrade();
4468 move |e: &E, cx: &mut WindowContext| {
4469 view.update(cx, |view, cx| f(view, e, cx)).ok();
4470 }
4471 }
4472}
4473
4474impl<V> Context for ViewContext<'_, V> {
4475 type Result<U> = U;
4476
4477 fn new_model<T: 'static>(
4478 &mut self,
4479 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4480 ) -> Model<T> {
4481 self.window_cx.new_model(build_model)
4482 }
4483
4484 fn reserve_model<T: 'static>(&mut self) -> Self::Result<crate::Reservation<T>> {
4485 self.window_cx.reserve_model()
4486 }
4487
4488 fn insert_model<T: 'static>(
4489 &mut self,
4490 reservation: crate::Reservation<T>,
4491 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
4492 ) -> Self::Result<Model<T>> {
4493 self.window_cx.insert_model(reservation, build_model)
4494 }
4495
4496 fn update_model<T: 'static, R>(
4497 &mut self,
4498 model: &Model<T>,
4499 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
4500 ) -> R {
4501 self.window_cx.update_model(model, update)
4502 }
4503
4504 fn read_model<T, R>(
4505 &self,
4506 handle: &Model<T>,
4507 read: impl FnOnce(&T, &AppContext) -> R,
4508 ) -> Self::Result<R>
4509 where
4510 T: 'static,
4511 {
4512 self.window_cx.read_model(handle, read)
4513 }
4514
4515 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
4516 where
4517 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
4518 {
4519 self.window_cx.update_window(window, update)
4520 }
4521
4522 fn read_window<T, R>(
4523 &self,
4524 window: &WindowHandle<T>,
4525 read: impl FnOnce(View<T>, &AppContext) -> R,
4526 ) -> Result<R>
4527 where
4528 T: 'static,
4529 {
4530 self.window_cx.read_window(window, read)
4531 }
4532}
4533
4534impl<V: 'static> VisualContext for ViewContext<'_, V> {
4535 fn new_view<W: Render + 'static>(
4536 &mut self,
4537 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4538 ) -> Self::Result<View<W>> {
4539 self.window_cx.new_view(build_view_state)
4540 }
4541
4542 fn update_view<V2: 'static, R>(
4543 &mut self,
4544 view: &View<V2>,
4545 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
4546 ) -> Self::Result<R> {
4547 self.window_cx.update_view(view, update)
4548 }
4549
4550 fn replace_root_view<W>(
4551 &mut self,
4552 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
4553 ) -> Self::Result<View<W>>
4554 where
4555 W: 'static + Render,
4556 {
4557 self.window_cx.replace_root_view(build_view)
4558 }
4559
4560 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
4561 self.window_cx.focus_view(view)
4562 }
4563
4564 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
4565 self.window_cx.dismiss_view(view)
4566 }
4567}
4568
4569impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
4570 type Target = WindowContext<'a>;
4571
4572 fn deref(&self) -> &Self::Target {
4573 &self.window_cx
4574 }
4575}
4576
4577impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
4578 fn deref_mut(&mut self) -> &mut Self::Target {
4579 &mut self.window_cx
4580 }
4581}
4582
4583// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
4584slotmap::new_key_type! {
4585 /// A unique identifier for a window.
4586 pub struct WindowId;
4587}
4588
4589impl WindowId {
4590 /// Converts this window ID to a `u64`.
4591 pub fn as_u64(&self) -> u64 {
4592 self.0.as_ffi()
4593 }
4594}
4595
4596impl From<u64> for WindowId {
4597 fn from(value: u64) -> Self {
4598 WindowId(slotmap::KeyData::from_ffi(value))
4599 }
4600}
4601
4602/// A handle to a window with a specific root view type.
4603/// Note that this does not keep the window alive on its own.
4604#[derive(Deref, DerefMut)]
4605pub struct WindowHandle<V> {
4606 #[deref]
4607 #[deref_mut]
4608 pub(crate) any_handle: AnyWindowHandle,
4609 state_type: PhantomData<V>,
4610}
4611
4612impl<V: 'static + Render> WindowHandle<V> {
4613 /// Creates a new handle from a window ID.
4614 /// This does not check if the root type of the window is `V`.
4615 pub fn new(id: WindowId) -> Self {
4616 WindowHandle {
4617 any_handle: AnyWindowHandle {
4618 id,
4619 state_type: TypeId::of::<V>(),
4620 },
4621 state_type: PhantomData,
4622 }
4623 }
4624
4625 /// Get the root view out of this window.
4626 ///
4627 /// This will fail if the window is closed or if the root view's type does not match `V`.
4628 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
4629 where
4630 C: Context,
4631 {
4632 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
4633 root_view
4634 .downcast::<V>()
4635 .map_err(|_| anyhow!("the type of the window's root view has changed"))
4636 }))
4637 }
4638
4639 /// Updates the root view of this window.
4640 ///
4641 /// This will fail if the window has been closed or if the root view's type does not match
4642 pub fn update<C, R>(
4643 &self,
4644 cx: &mut C,
4645 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
4646 ) -> Result<R>
4647 where
4648 C: Context,
4649 {
4650 cx.update_window(self.any_handle, |root_view, cx| {
4651 let view = root_view
4652 .downcast::<V>()
4653 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4654 Ok(cx.update_view(&view, update))
4655 })?
4656 }
4657
4658 /// Read the root view out of this window.
4659 ///
4660 /// This will fail if the window is closed or if the root view's type does not match `V`.
4661 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
4662 let x = cx
4663 .windows
4664 .get(self.id)
4665 .and_then(|window| {
4666 window
4667 .as_ref()
4668 .and_then(|window| window.root_view.clone())
4669 .map(|root_view| root_view.downcast::<V>())
4670 })
4671 .ok_or_else(|| anyhow!("window not found"))?
4672 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
4673
4674 Ok(x.read(cx))
4675 }
4676
4677 /// Read the root view out of this window, with a callback
4678 ///
4679 /// This will fail if the window is closed or if the root view's type does not match `V`.
4680 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
4681 where
4682 C: Context,
4683 {
4684 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
4685 }
4686
4687 /// Read the root view pointer off of this window.
4688 ///
4689 /// This will fail if the window is closed or if the root view's type does not match `V`.
4690 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
4691 where
4692 C: Context,
4693 {
4694 cx.read_window(self, |root_view, _cx| root_view.clone())
4695 }
4696
4697 /// Check if this window is 'active'.
4698 ///
4699 /// Will return `None` if the window is closed or currently
4700 /// borrowed.
4701 pub fn is_active(&self, cx: &mut AppContext) -> Option<bool> {
4702 cx.update_window(self.any_handle, |_, cx| cx.is_window_active())
4703 .ok()
4704 }
4705}
4706
4707impl<V> Copy for WindowHandle<V> {}
4708
4709impl<V> Clone for WindowHandle<V> {
4710 fn clone(&self) -> Self {
4711 *self
4712 }
4713}
4714
4715impl<V> PartialEq for WindowHandle<V> {
4716 fn eq(&self, other: &Self) -> bool {
4717 self.any_handle == other.any_handle
4718 }
4719}
4720
4721impl<V> Eq for WindowHandle<V> {}
4722
4723impl<V> Hash for WindowHandle<V> {
4724 fn hash<H: Hasher>(&self, state: &mut H) {
4725 self.any_handle.hash(state);
4726 }
4727}
4728
4729impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
4730 fn from(val: WindowHandle<V>) -> Self {
4731 val.any_handle
4732 }
4733}
4734
4735unsafe impl<V> Send for WindowHandle<V> {}
4736unsafe impl<V> Sync for WindowHandle<V> {}
4737
4738/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
4739#[derive(Copy, Clone, PartialEq, Eq, Hash)]
4740pub struct AnyWindowHandle {
4741 pub(crate) id: WindowId,
4742 state_type: TypeId,
4743}
4744
4745impl AnyWindowHandle {
4746 /// Get the ID of this window.
4747 pub fn window_id(&self) -> WindowId {
4748 self.id
4749 }
4750
4751 /// Attempt to convert this handle to a window handle with a specific root view type.
4752 /// If the types do not match, this will return `None`.
4753 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
4754 if TypeId::of::<T>() == self.state_type {
4755 Some(WindowHandle {
4756 any_handle: *self,
4757 state_type: PhantomData,
4758 })
4759 } else {
4760 None
4761 }
4762 }
4763
4764 /// Updates the state of the root view of this window.
4765 ///
4766 /// This will fail if the window has been closed.
4767 pub fn update<C, R>(
4768 self,
4769 cx: &mut C,
4770 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
4771 ) -> Result<R>
4772 where
4773 C: Context,
4774 {
4775 cx.update_window(self, update)
4776 }
4777
4778 /// Read the state of the root view of this window.
4779 ///
4780 /// This will fail if the window has been closed.
4781 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
4782 where
4783 C: Context,
4784 T: 'static,
4785 {
4786 let view = self
4787 .downcast::<T>()
4788 .context("the type of the window's root view has changed")?;
4789
4790 cx.read_window(&view, read)
4791 }
4792}
4793
4794/// An identifier for an [`Element`](crate::Element).
4795///
4796/// Can be constructed with a string, a number, or both, as well
4797/// as other internal representations.
4798#[derive(Clone, Debug, Eq, PartialEq, Hash)]
4799pub enum ElementId {
4800 /// The ID of a View element
4801 View(EntityId),
4802 /// An integer ID.
4803 Integer(usize),
4804 /// A string based ID.
4805 Name(SharedString),
4806 /// A UUID.
4807 Uuid(Uuid),
4808 /// An ID that's equated with a focus handle.
4809 FocusHandle(FocusId),
4810 /// A combination of a name and an integer.
4811 NamedInteger(SharedString, usize),
4812}
4813
4814impl Display for ElementId {
4815 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4816 match self {
4817 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
4818 ElementId::Integer(ix) => write!(f, "{}", ix)?,
4819 ElementId::Name(name) => write!(f, "{}", name)?,
4820 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
4821 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
4822 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
4823 }
4824
4825 Ok(())
4826 }
4827}
4828
4829impl TryInto<SharedString> for ElementId {
4830 type Error = anyhow::Error;
4831
4832 fn try_into(self) -> anyhow::Result<SharedString> {
4833 if let ElementId::Name(name) = self {
4834 Ok(name)
4835 } else {
4836 Err(anyhow!("element id is not string"))
4837 }
4838 }
4839}
4840
4841impl From<usize> for ElementId {
4842 fn from(id: usize) -> Self {
4843 ElementId::Integer(id)
4844 }
4845}
4846
4847impl From<i32> for ElementId {
4848 fn from(id: i32) -> Self {
4849 Self::Integer(id as usize)
4850 }
4851}
4852
4853impl From<SharedString> for ElementId {
4854 fn from(name: SharedString) -> Self {
4855 ElementId::Name(name)
4856 }
4857}
4858
4859impl From<&'static str> for ElementId {
4860 fn from(name: &'static str) -> Self {
4861 ElementId::Name(name.into())
4862 }
4863}
4864
4865impl<'a> From<&'a FocusHandle> for ElementId {
4866 fn from(handle: &'a FocusHandle) -> Self {
4867 ElementId::FocusHandle(handle.id)
4868 }
4869}
4870
4871impl From<(&'static str, EntityId)> for ElementId {
4872 fn from((name, id): (&'static str, EntityId)) -> Self {
4873 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
4874 }
4875}
4876
4877impl From<(&'static str, usize)> for ElementId {
4878 fn from((name, id): (&'static str, usize)) -> Self {
4879 ElementId::NamedInteger(name.into(), id)
4880 }
4881}
4882
4883impl From<(&'static str, u64)> for ElementId {
4884 fn from((name, id): (&'static str, u64)) -> Self {
4885 ElementId::NamedInteger(name.into(), id as usize)
4886 }
4887}
4888
4889impl From<Uuid> for ElementId {
4890 fn from(value: Uuid) -> Self {
4891 Self::Uuid(value)
4892 }
4893}
4894
4895impl From<(&'static str, u32)> for ElementId {
4896 fn from((name, id): (&'static str, u32)) -> Self {
4897 ElementId::NamedInteger(name.into(), id as usize)
4898 }
4899}
4900
4901/// A rectangle to be rendered in the window at the given position and size.
4902/// Passed as an argument [`WindowContext::paint_quad`].
4903#[derive(Clone)]
4904pub struct PaintQuad {
4905 /// The bounds of the quad within the window.
4906 pub bounds: Bounds<Pixels>,
4907 /// The radii of the quad's corners.
4908 pub corner_radii: Corners<Pixels>,
4909 /// The background color of the quad.
4910 pub background: Hsla,
4911 /// The widths of the quad's borders.
4912 pub border_widths: Edges<Pixels>,
4913 /// The color of the quad's borders.
4914 pub border_color: Hsla,
4915}
4916
4917impl PaintQuad {
4918 /// Sets the corner radii of the quad.
4919 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
4920 PaintQuad {
4921 corner_radii: corner_radii.into(),
4922 ..self
4923 }
4924 }
4925
4926 /// Sets the border widths of the quad.
4927 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
4928 PaintQuad {
4929 border_widths: border_widths.into(),
4930 ..self
4931 }
4932 }
4933
4934 /// Sets the border color of the quad.
4935 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
4936 PaintQuad {
4937 border_color: border_color.into(),
4938 ..self
4939 }
4940 }
4941
4942 /// Sets the background color of the quad.
4943 pub fn background(self, background: impl Into<Hsla>) -> Self {
4944 PaintQuad {
4945 background: background.into(),
4946 ..self
4947 }
4948 }
4949}
4950
4951/// Creates a quad with the given parameters.
4952pub fn quad(
4953 bounds: Bounds<Pixels>,
4954 corner_radii: impl Into<Corners<Pixels>>,
4955 background: impl Into<Hsla>,
4956 border_widths: impl Into<Edges<Pixels>>,
4957 border_color: impl Into<Hsla>,
4958) -> PaintQuad {
4959 PaintQuad {
4960 bounds,
4961 corner_radii: corner_radii.into(),
4962 background: background.into(),
4963 border_widths: border_widths.into(),
4964 border_color: border_color.into(),
4965 }
4966}
4967
4968/// Creates a filled quad with the given bounds and background color.
4969pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
4970 PaintQuad {
4971 bounds: bounds.into(),
4972 corner_radii: (0.).into(),
4973 background: background.into(),
4974 border_widths: (0.).into(),
4975 border_color: transparent_black(),
4976 }
4977}
4978
4979/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
4980pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
4981 PaintQuad {
4982 bounds: bounds.into(),
4983 corner_radii: (0.).into(),
4984 background: transparent_black(),
4985 border_widths: (1.).into(),
4986 border_color: border_color.into(),
4987 }
4988}