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