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