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