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