1use crate::{
2 key_dispatch::DispatchActionListener, px, size, transparent_black, Action, AnyDrag, AnyView,
3 AppContext, AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners,
4 CursorStyle, DevicePixels, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
5 EntityId, EventEmitter, FileDropEvent, Flatten, FocusEvent, FontId, GlobalElementId, GlyphId,
6 Hsla, ImageData, InputEvent, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeystrokeEvent,
7 LayoutId, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseMoveEvent,
8 MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler,
9 PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams,
10 RenderImageParams, RenderSvgParams, ScaledPixels, Scene, SceneBuilder, Shadow, SharedString,
11 Size, Style, SubscriberSet, Subscription, Surface, TaffyLayoutEngine, Task, Underline,
12 UnderlineStyle, View, VisualContext, WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
13};
14use anyhow::{anyhow, Context as _, Result};
15use collections::FxHashMap;
16use derive_more::{Deref, DerefMut};
17use futures::{
18 channel::{mpsc, oneshot},
19 StreamExt,
20};
21use media::core_video::CVImageBuffer;
22use parking_lot::RwLock;
23use slotmap::SlotMap;
24use smallvec::SmallVec;
25use std::{
26 any::{Any, TypeId},
27 borrow::{Borrow, BorrowMut, Cow},
28 fmt::Debug,
29 future::Future,
30 hash::{Hash, Hasher},
31 marker::PhantomData,
32 mem,
33 rc::Rc,
34 sync::{
35 atomic::{AtomicUsize, Ordering::SeqCst},
36 Arc,
37 },
38};
39use util::ResultExt;
40
41const ACTIVE_DRAG_Z_INDEX: u8 = 1;
42
43/// A global stacking order, which is created by stacking successive z-index values.
44/// Each z-index will always be interpreted in the context of its parent z-index.
45#[derive(Deref, DerefMut, Clone, Debug, Ord, PartialOrd, PartialEq, Eq)]
46pub struct StackingOrder {
47 #[deref]
48 #[deref_mut]
49 z_indices: SmallVec<[u8; 64]>,
50}
51
52impl Default for StackingOrder {
53 fn default() -> Self {
54 StackingOrder {
55 z_indices: SmallVec::new(),
56 }
57 }
58}
59
60/// Represents the two different phases when dispatching events.
61#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
62pub enum DispatchPhase {
63 /// After the capture phase comes the bubble phase, in which mouse event listeners are
64 /// invoked front to back and keyboard event listeners are invoked from the focused element
65 /// to the root of the element tree. This is the phase you'll most commonly want to use when
66 /// registering event listeners.
67 #[default]
68 Bubble,
69 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
70 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
71 /// is used for special purposes such as clearing the "pressed" state for click events. If
72 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
73 /// outside of the immediate region may rely on detecting non-local events during this phase.
74 Capture,
75}
76
77impl DispatchPhase {
78 pub fn bubble(self) -> bool {
79 self == DispatchPhase::Bubble
80 }
81
82 pub fn capture(self) -> bool {
83 self == DispatchPhase::Capture
84 }
85}
86
87type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
88type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
89type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
90type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
91
92slotmap::new_key_type! { pub struct FocusId; }
93
94impl FocusId {
95 /// Obtains whether the element associated with this handle is currently focused.
96 pub fn is_focused(&self, cx: &WindowContext) -> bool {
97 cx.window.focus == Some(*self)
98 }
99
100 /// Obtains whether the element associated with this handle contains the focused
101 /// element or is itself focused.
102 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
103 cx.focused()
104 .map_or(false, |focused| self.contains(focused.id, cx))
105 }
106
107 /// Obtains whether the element associated with this handle is contained within the
108 /// focused element or is itself focused.
109 pub fn within_focused(&self, cx: &WindowContext) -> bool {
110 let focused = cx.focused();
111 focused.map_or(false, |focused| focused.id.contains(*self, cx))
112 }
113
114 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
115 pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
116 cx.window
117 .rendered_frame
118 .dispatch_tree
119 .focus_contains(*self, other)
120 }
121}
122
123/// A handle which can be used to track and manipulate the focused element in a window.
124pub struct FocusHandle {
125 pub(crate) id: FocusId,
126 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
127}
128
129impl std::fmt::Debug for FocusHandle {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
132 }
133}
134
135impl FocusHandle {
136 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
137 let id = handles.write().insert(AtomicUsize::new(1));
138 Self {
139 id,
140 handles: handles.clone(),
141 }
142 }
143
144 pub(crate) fn for_id(
145 id: FocusId,
146 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
147 ) -> Option<Self> {
148 let lock = handles.read();
149 let ref_count = lock.get(id)?;
150 if ref_count.load(SeqCst) == 0 {
151 None
152 } else {
153 ref_count.fetch_add(1, SeqCst);
154 Some(Self {
155 id,
156 handles: handles.clone(),
157 })
158 }
159 }
160
161 /// Moves the focus to the element associated with this handle.
162 pub fn focus(&self, cx: &mut WindowContext) {
163 cx.focus(self)
164 }
165
166 /// Obtains whether the element associated with this handle is currently focused.
167 pub fn is_focused(&self, cx: &WindowContext) -> bool {
168 self.id.is_focused(cx)
169 }
170
171 /// Obtains whether the element associated with this handle contains the focused
172 /// element or is itself focused.
173 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
174 self.id.contains_focused(cx)
175 }
176
177 /// Obtains whether the element associated with this handle is contained within the
178 /// focused element or is itself focused.
179 pub fn within_focused(&self, cx: &WindowContext) -> bool {
180 self.id.within_focused(cx)
181 }
182
183 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
184 pub fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
185 self.id.contains(other.id, cx)
186 }
187}
188
189impl Clone for FocusHandle {
190 fn clone(&self) -> Self {
191 Self::for_id(self.id, &self.handles).unwrap()
192 }
193}
194
195impl PartialEq for FocusHandle {
196 fn eq(&self, other: &Self) -> bool {
197 self.id == other.id
198 }
199}
200
201impl Eq for FocusHandle {}
202
203impl Drop for FocusHandle {
204 fn drop(&mut self) {
205 self.handles
206 .read()
207 .get(self.id)
208 .unwrap()
209 .fetch_sub(1, SeqCst);
210 }
211}
212
213/// FocusableView allows users of your view to easily
214/// focus it (using cx.focus_view(view))
215pub trait FocusableView: 'static + Render {
216 fn focus_handle(&self, cx: &AppContext) -> FocusHandle;
217}
218
219/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
220/// where the lifecycle of the view is handled by another view.
221pub trait ManagedView: FocusableView + EventEmitter<DismissEvent> {}
222
223impl<M: FocusableView + EventEmitter<DismissEvent>> ManagedView for M {}
224
225pub struct DismissEvent;
226
227// Holds the state for a specific window.
228pub struct Window {
229 pub(crate) handle: AnyWindowHandle,
230 pub(crate) removed: bool,
231 pub(crate) platform_window: Box<dyn PlatformWindow>,
232 display_id: DisplayId,
233 sprite_atlas: Arc<dyn PlatformAtlas>,
234 rem_size: Pixels,
235 viewport_size: Size<Pixels>,
236 layout_engine: Option<TaffyLayoutEngine>,
237 pub(crate) root_view: Option<AnyView>,
238 pub(crate) element_id_stack: GlobalElementId,
239 pub(crate) rendered_frame: Frame,
240 pub(crate) next_frame: Frame,
241 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
242 pub(crate) focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
243 pub(crate) blur_listeners: SubscriberSet<(), AnyObserver>,
244 default_prevented: bool,
245 mouse_position: Point<Pixels>,
246 modifiers: Modifiers,
247 requested_cursor_style: Option<CursorStyle>,
248 scale_factor: f32,
249 bounds: WindowBounds,
250 bounds_observers: SubscriberSet<(), AnyObserver>,
251 active: bool,
252 pub(crate) dirty: bool,
253 pub(crate) drawing: bool,
254 activation_observers: SubscriberSet<(), AnyObserver>,
255 pub(crate) last_blur: Option<Option<FocusId>>,
256 pub(crate) focus: Option<FocusId>,
257}
258
259pub(crate) struct ElementStateBox {
260 inner: Box<dyn Any>,
261 #[cfg(debug_assertions)]
262 type_name: &'static str,
263}
264
265// #[derive(Default)]
266pub(crate) struct Frame {
267 pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
268 mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, AnyMouseListener)>>,
269 pub(crate) dispatch_tree: DispatchTree,
270 pub(crate) focus_listeners: Vec<AnyFocusListener>,
271 pub(crate) scene_builder: SceneBuilder,
272 pub(crate) depth_map: Vec<(StackingOrder, Bounds<Pixels>)>,
273 pub(crate) z_index_stack: StackingOrder,
274 content_mask_stack: Vec<ContentMask<Pixels>>,
275 element_offset_stack: Vec<Point<Pixels>>,
276}
277
278impl Frame {
279 fn new(dispatch_tree: DispatchTree) -> Self {
280 Frame {
281 element_states: FxHashMap::default(),
282 mouse_listeners: FxHashMap::default(),
283 dispatch_tree,
284 focus_listeners: Vec::new(),
285 scene_builder: SceneBuilder::default(),
286 z_index_stack: StackingOrder::default(),
287 depth_map: Default::default(),
288 content_mask_stack: Vec::new(),
289 element_offset_stack: Vec::new(),
290 }
291 }
292
293 fn clear(&mut self) {
294 self.element_states.clear();
295 self.mouse_listeners.values_mut().for_each(Vec::clear);
296 self.focus_listeners.clear();
297 self.dispatch_tree.clear();
298 self.depth_map.clear();
299 }
300}
301
302impl Window {
303 pub(crate) fn new(
304 handle: AnyWindowHandle,
305 options: WindowOptions,
306 cx: &mut AppContext,
307 ) -> Self {
308 let platform_window = cx.platform.open_window(
309 handle,
310 options,
311 Box::new({
312 let mut cx = cx.to_async();
313 move || handle.update(&mut cx, |_, cx| cx.draw())
314 }),
315 );
316 let display_id = platform_window.display().id();
317 let sprite_atlas = platform_window.sprite_atlas();
318 let mouse_position = platform_window.mouse_position();
319 let modifiers = platform_window.modifiers();
320 let content_size = platform_window.content_size();
321 let scale_factor = platform_window.scale_factor();
322 let bounds = platform_window.bounds();
323
324 platform_window.on_resize(Box::new({
325 let mut cx = cx.to_async();
326 move |_, _| {
327 handle
328 .update(&mut cx, |_, cx| cx.window_bounds_changed())
329 .log_err();
330 }
331 }));
332 platform_window.on_moved(Box::new({
333 let mut cx = cx.to_async();
334 move || {
335 handle
336 .update(&mut cx, |_, cx| cx.window_bounds_changed())
337 .log_err();
338 }
339 }));
340 platform_window.on_active_status_change(Box::new({
341 let mut cx = cx.to_async();
342 move |active| {
343 handle
344 .update(&mut cx, |_, cx| {
345 cx.window.active = active;
346 cx.window
347 .activation_observers
348 .clone()
349 .retain(&(), |callback| callback(cx));
350 })
351 .log_err();
352 }
353 }));
354
355 platform_window.on_input({
356 let mut cx = cx.to_async();
357 Box::new(move |event| {
358 handle
359 .update(&mut cx, |_, cx| cx.dispatch_event(event))
360 .log_err()
361 .unwrap_or(false)
362 })
363 });
364
365 Window {
366 handle,
367 removed: false,
368 platform_window,
369 display_id,
370 sprite_atlas,
371 rem_size: px(16.),
372 viewport_size: content_size,
373 layout_engine: Some(TaffyLayoutEngine::new()),
374 root_view: None,
375 element_id_stack: GlobalElementId::default(),
376 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
377 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
378 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
379 focus_listeners: SubscriberSet::new(),
380 blur_listeners: SubscriberSet::new(),
381 default_prevented: true,
382 mouse_position,
383 modifiers,
384 requested_cursor_style: None,
385 scale_factor,
386 bounds,
387 bounds_observers: SubscriberSet::new(),
388 active: false,
389 dirty: false,
390 drawing: false,
391 activation_observers: SubscriberSet::new(),
392 last_blur: None,
393 focus: None,
394 }
395 }
396}
397
398/// Indicates which region of the window is visible. Content falling outside of this mask will not be
399/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
400/// to leave room to support more complex shapes in the future.
401#[derive(Clone, Debug, Default, PartialEq, Eq)]
402#[repr(C)]
403pub struct ContentMask<P: Clone + Default + Debug> {
404 pub bounds: Bounds<P>,
405}
406
407impl ContentMask<Pixels> {
408 /// Scale the content mask's pixel units by the given scaling factor.
409 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
410 ContentMask {
411 bounds: self.bounds.scale(factor),
412 }
413 }
414
415 /// Intersect the content mask with the given content mask.
416 pub fn intersect(&self, other: &Self) -> Self {
417 let bounds = self.bounds.intersect(&other.bounds);
418 ContentMask { bounds }
419 }
420}
421
422/// Provides access to application state in the context of a single window. Derefs
423/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
424/// an `AppContext` and call any `AppContext` methods.
425pub struct WindowContext<'a> {
426 pub(crate) app: &'a mut AppContext,
427 pub(crate) window: &'a mut Window,
428}
429
430impl<'a> WindowContext<'a> {
431 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
432 Self { app, window }
433 }
434
435 /// Obtain a handle to the window that belongs to this context.
436 pub fn window_handle(&self) -> AnyWindowHandle {
437 self.window.handle
438 }
439
440 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
441 pub fn notify(&mut self) {
442 if !self.window.drawing {
443 self.window.dirty = true;
444 }
445 }
446
447 /// Close this window.
448 pub fn remove_window(&mut self) {
449 self.window.removed = true;
450 }
451
452 /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
453 /// for elements rendered within this window.
454 pub fn focus_handle(&mut self) -> FocusHandle {
455 FocusHandle::new(&self.window.focus_handles)
456 }
457
458 /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
459 pub fn focused(&self) -> Option<FocusHandle> {
460 self.window
461 .focus
462 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
463 }
464
465 /// Move focus to the element associated with the given `FocusHandle`.
466 pub fn focus(&mut self, handle: &FocusHandle) {
467 if self.window.focus == Some(handle.id) {
468 return;
469 }
470
471 let focus_id = handle.id;
472
473 if self.window.last_blur.is_none() {
474 self.window.last_blur = Some(self.window.focus);
475 }
476
477 self.window.focus = Some(focus_id);
478 self.window
479 .rendered_frame
480 .dispatch_tree
481 .clear_pending_keystrokes();
482 self.app.push_effect(Effect::FocusChanged {
483 window_handle: self.window.handle,
484 focused: Some(focus_id),
485 });
486 self.notify();
487 }
488
489 /// Remove focus from all elements within this context's window.
490 pub fn blur(&mut self) {
491 if self.window.last_blur.is_none() {
492 self.window.last_blur = Some(self.window.focus);
493 }
494
495 self.window.focus = None;
496 self.app.push_effect(Effect::FocusChanged {
497 window_handle: self.window.handle,
498 focused: None,
499 });
500 self.notify();
501 }
502
503 pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
504 let focus_handle = self.focused();
505
506 self.defer(move |cx| {
507 let node_id = focus_handle
508 .and_then(|handle| {
509 cx.window
510 .rendered_frame
511 .dispatch_tree
512 .focusable_node_id(handle.id)
513 })
514 .unwrap_or_else(|| cx.window.rendered_frame.dispatch_tree.root_node_id());
515
516 cx.propagate_event = true;
517 cx.dispatch_action_on_node(node_id, action);
518 })
519 }
520
521 pub(crate) fn dispatch_keystroke_observers(
522 &mut self,
523 event: &dyn Any,
524 action: Option<Box<dyn Action>>,
525 ) {
526 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
527 return;
528 };
529
530 self.keystroke_observers
531 .clone()
532 .retain(&(), move |callback| {
533 (callback)(
534 &KeystrokeEvent {
535 keystroke: key_down_event.keystroke.clone(),
536 action: action.as_ref().map(|action| action.boxed_clone()),
537 },
538 self,
539 );
540 true
541 });
542 }
543
544 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
545 /// that are currently on the stack to be returned to the app.
546 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
547 let handle = self.window.handle;
548 self.app.defer(move |cx| {
549 handle.update(cx, |_, cx| f(cx)).ok();
550 });
551 }
552
553 pub fn subscribe<Emitter, E, Evt>(
554 &mut self,
555 entity: &E,
556 mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
557 ) -> Subscription
558 where
559 Emitter: EventEmitter<Evt>,
560 E: Entity<Emitter>,
561 Evt: 'static,
562 {
563 let entity_id = entity.entity_id();
564 let entity = entity.downgrade();
565 let window_handle = self.window.handle;
566 let (subscription, activate) = self.app.event_listeners.insert(
567 entity_id,
568 (
569 TypeId::of::<Evt>(),
570 Box::new(move |event, cx| {
571 window_handle
572 .update(cx, |_, cx| {
573 if let Some(handle) = E::upgrade_from(&entity) {
574 let event = event.downcast_ref().expect("invalid event type");
575 on_event(handle, event, cx);
576 true
577 } else {
578 false
579 }
580 })
581 .unwrap_or(false)
582 }),
583 ),
584 );
585 self.app.defer(move |_| activate());
586 subscription
587 }
588
589 /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
590 /// await points in async code.
591 pub fn to_async(&self) -> AsyncWindowContext {
592 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
593 }
594
595 /// Schedule the given closure to be run directly after the current frame is rendered.
596 pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
597 let handle = self.window.handle;
598 let display_id = self.window.display_id;
599
600 if !self.frame_consumers.contains_key(&display_id) {
601 let (tx, mut rx) = mpsc::unbounded::<()>();
602 self.platform.set_display_link_output_callback(
603 display_id,
604 Box::new(move |_current_time, _output_time| _ = tx.unbounded_send(())),
605 );
606
607 let consumer_task = self.app.spawn(|cx| async move {
608 while rx.next().await.is_some() {
609 cx.update(|cx| {
610 for callback in cx
611 .next_frame_callbacks
612 .get_mut(&display_id)
613 .unwrap()
614 .drain(..)
615 .collect::<SmallVec<[_; 32]>>()
616 {
617 callback(cx);
618 }
619 })
620 .ok();
621
622 // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
623
624 cx.update(|cx| {
625 if cx.next_frame_callbacks.is_empty() {
626 cx.platform.stop_display_link(display_id);
627 }
628 })
629 .ok();
630 }
631 });
632 self.frame_consumers.insert(display_id, consumer_task);
633 }
634
635 if self.next_frame_callbacks.is_empty() {
636 self.platform.start_display_link(display_id);
637 }
638
639 self.next_frame_callbacks
640 .entry(display_id)
641 .or_default()
642 .push(Box::new(move |cx: &mut AppContext| {
643 cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
644 }));
645 }
646
647 /// Spawn the future returned by the given closure on the application thread pool.
648 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
649 /// use within your future.
650 pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
651 where
652 R: 'static,
653 Fut: Future<Output = R> + 'static,
654 {
655 self.app
656 .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
657 }
658
659 /// Update the global of the given type. The given closure is given simultaneous mutable
660 /// access both to the global and the context.
661 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
662 where
663 G: 'static,
664 {
665 let mut global = self.app.lease_global::<G>();
666 let result = f(&mut global, self);
667 self.app.end_global_lease(global);
668 result
669 }
670
671 #[must_use]
672 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
673 /// layout is being requested, along with the layout ids of any children. This method is called during
674 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
675 pub fn request_layout(
676 &mut self,
677 style: &Style,
678 children: impl IntoIterator<Item = LayoutId>,
679 ) -> LayoutId {
680 self.app.layout_id_buffer.clear();
681 self.app.layout_id_buffer.extend(children.into_iter());
682 let rem_size = self.rem_size();
683
684 self.window.layout_engine.as_mut().unwrap().request_layout(
685 style,
686 rem_size,
687 &self.app.layout_id_buffer,
688 )
689 }
690
691 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
692 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
693 /// determine the element's size. One place this is used internally is when measuring text.
694 ///
695 /// The given closure is invoked at layout time with the known dimensions and available space and
696 /// returns a `Size`.
697 pub fn request_measured_layout<
698 F: FnMut(Size<Option<Pixels>>, Size<AvailableSpace>, &mut WindowContext) -> Size<Pixels>
699 + 'static,
700 >(
701 &mut self,
702 style: Style,
703 measure: F,
704 ) -> LayoutId {
705 let rem_size = self.rem_size();
706 self.window
707 .layout_engine
708 .as_mut()
709 .unwrap()
710 .request_measured_layout(style, rem_size, measure)
711 }
712
713 pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
714 let mut layout_engine = self.window.layout_engine.take().unwrap();
715 layout_engine.compute_layout(layout_id, available_space, self);
716 self.window.layout_engine = Some(layout_engine);
717 }
718
719 /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
720 /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
721 /// in order to pass your element its `Bounds` automatically.
722 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
723 let mut bounds = self
724 .window
725 .layout_engine
726 .as_mut()
727 .unwrap()
728 .layout_bounds(layout_id)
729 .map(Into::into);
730 bounds.origin += self.element_offset();
731 bounds
732 }
733
734 fn window_bounds_changed(&mut self) {
735 self.window.scale_factor = self.window.platform_window.scale_factor();
736 self.window.viewport_size = self.window.platform_window.content_size();
737 self.window.bounds = self.window.platform_window.bounds();
738 self.window.display_id = self.window.platform_window.display().id();
739 self.notify();
740
741 self.window
742 .bounds_observers
743 .clone()
744 .retain(&(), |callback| callback(self));
745 }
746
747 pub fn window_bounds(&self) -> WindowBounds {
748 self.window.bounds
749 }
750
751 pub fn viewport_size(&self) -> Size<Pixels> {
752 self.window.viewport_size
753 }
754
755 pub fn is_window_active(&self) -> bool {
756 self.window.active
757 }
758
759 pub fn zoom_window(&self) {
760 self.window.platform_window.zoom();
761 }
762
763 pub fn set_window_title(&mut self, title: &str) {
764 self.window.platform_window.set_title(title);
765 }
766
767 pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
768 self.platform
769 .displays()
770 .into_iter()
771 .find(|display| display.id() == self.window.display_id)
772 }
773
774 pub fn show_character_palette(&self) {
775 self.window.platform_window.show_character_palette();
776 }
777
778 /// The scale factor of the display associated with the window. For example, it could
779 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
780 /// be rendered as two pixels on screen.
781 pub fn scale_factor(&self) -> f32 {
782 self.window.scale_factor
783 }
784
785 /// The size of an em for the base font of the application. Adjusting this value allows the
786 /// UI to scale, just like zooming a web page.
787 pub fn rem_size(&self) -> Pixels {
788 self.window.rem_size
789 }
790
791 /// Sets the size of an em for the base font of the application. Adjusting this value allows the
792 /// UI to scale, just like zooming a web page.
793 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
794 self.window.rem_size = rem_size.into();
795 }
796
797 /// The line height associated with the current text style.
798 pub fn line_height(&self) -> Pixels {
799 let rem_size = self.rem_size();
800 let text_style = self.text_style();
801 text_style
802 .line_height
803 .to_pixels(text_style.font_size.into(), rem_size)
804 }
805
806 /// Call to prevent the default action of an event. Currently only used to prevent
807 /// parent elements from becoming focused on mouse down.
808 pub fn prevent_default(&mut self) {
809 self.window.default_prevented = true;
810 }
811
812 /// Obtain whether default has been prevented for the event currently being dispatched.
813 pub fn default_prevented(&self) -> bool {
814 self.window.default_prevented
815 }
816
817 /// Register a mouse event listener on the window for the next frame. The type of event
818 /// is determined by the first parameter of the given listener. When the next frame is rendered
819 /// the listener will be cleared.
820 ///
821 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
822 /// a specific need to register a global listener.
823 pub fn on_mouse_event<Event: 'static>(
824 &mut self,
825 mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
826 ) {
827 let order = self.window.next_frame.z_index_stack.clone();
828 self.window
829 .next_frame
830 .mouse_listeners
831 .entry(TypeId::of::<Event>())
832 .or_default()
833 .push((
834 order,
835 Box::new(move |event: &dyn Any, phase, cx| {
836 handler(event.downcast_ref().unwrap(), phase, cx)
837 }),
838 ))
839 }
840
841 /// Register a key event listener on the window for the next frame. The type of event
842 /// is determined by the first parameter of the given listener. When the next frame is rendered
843 /// the listener will be cleared.
844 ///
845 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
846 /// a specific need to register a global listener.
847 pub fn on_key_event<Event: 'static>(
848 &mut self,
849 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
850 ) {
851 self.window
852 .next_frame
853 .dispatch_tree
854 .on_key_event(Rc::new(move |event, phase, cx| {
855 if let Some(event) = event.downcast_ref::<Event>() {
856 handler(event, phase, cx)
857 }
858 }));
859 }
860
861 /// Register an action listener on the window for the next frame. The type of action
862 /// is determined by the first parameter of the given listener. When the next frame is rendered
863 /// the listener will be cleared.
864 ///
865 /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
866 /// a specific need to register a global listener.
867 pub fn on_action(
868 &mut self,
869 action_type: TypeId,
870 handler: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
871 ) {
872 self.window.next_frame.dispatch_tree.on_action(
873 action_type,
874 Rc::new(move |action, phase, cx| handler(action, phase, cx)),
875 );
876 }
877
878 pub fn is_action_available(&self, action: &dyn Action) -> bool {
879 let target = self
880 .focused()
881 .and_then(|focused_handle| {
882 self.window
883 .rendered_frame
884 .dispatch_tree
885 .focusable_node_id(focused_handle.id)
886 })
887 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
888 self.window
889 .rendered_frame
890 .dispatch_tree
891 .is_action_available(action, target)
892 }
893
894 /// The position of the mouse relative to the window.
895 pub fn mouse_position(&self) -> Point<Pixels> {
896 self.window.mouse_position
897 }
898
899 /// The current state of the keyboard's modifiers
900 pub fn modifiers(&self) -> Modifiers {
901 self.window.modifiers
902 }
903
904 pub fn set_cursor_style(&mut self, style: CursorStyle) {
905 self.window.requested_cursor_style = Some(style)
906 }
907
908 /// Called during painting to invoke the given closure in a new stacking context. The given
909 /// z-index is interpreted relative to the previous call to `stack`.
910 pub fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
911 self.window.next_frame.z_index_stack.push(z_index);
912 let result = f(self);
913 self.window.next_frame.z_index_stack.pop();
914 result
915 }
916
917 /// Called during painting to track which z-index is on top at each pixel position
918 pub fn add_opaque_layer(&mut self, bounds: Bounds<Pixels>) {
919 let stacking_order = self.window.next_frame.z_index_stack.clone();
920 let depth_map = &mut self.window.next_frame.depth_map;
921 match depth_map.binary_search_by(|(level, _)| stacking_order.cmp(&level)) {
922 Ok(i) | Err(i) => depth_map.insert(i, (stacking_order, bounds)),
923 }
924 }
925
926 /// Returns true if the top-most opaque layer painted over this point was part of the
927 /// same layer as the given stacking order.
928 pub fn was_top_layer(&self, point: &Point<Pixels>, level: &StackingOrder) -> bool {
929 for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
930 if bounds.contains(point) {
931 return level.starts_with(stack) || stack.starts_with(level);
932 }
933 }
934
935 false
936 }
937
938 pub fn was_top_layer_under_active_drag(
939 &self,
940 point: &Point<Pixels>,
941 level: &StackingOrder,
942 ) -> bool {
943 for (stack, bounds) in self.window.rendered_frame.depth_map.iter() {
944 if stack.starts_with(&[ACTIVE_DRAG_Z_INDEX]) {
945 continue;
946 }
947 if bounds.contains(point) {
948 return level.starts_with(stack) || stack.starts_with(level);
949 }
950 }
951
952 false
953 }
954
955 /// Called during painting to get the current stacking order.
956 pub fn stacking_order(&self) -> &StackingOrder {
957 &self.window.next_frame.z_index_stack
958 }
959
960 /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
961 pub fn paint_shadows(
962 &mut self,
963 bounds: Bounds<Pixels>,
964 corner_radii: Corners<Pixels>,
965 shadows: &[BoxShadow],
966 ) {
967 let scale_factor = self.scale_factor();
968 let content_mask = self.content_mask();
969 let window = &mut *self.window;
970 for shadow in shadows {
971 let mut shadow_bounds = bounds;
972 shadow_bounds.origin += shadow.offset;
973 shadow_bounds.dilate(shadow.spread_radius);
974 window.next_frame.scene_builder.insert(
975 &window.next_frame.z_index_stack,
976 Shadow {
977 order: 0,
978 bounds: shadow_bounds.scale(scale_factor),
979 content_mask: content_mask.scale(scale_factor),
980 corner_radii: corner_radii.scale(scale_factor),
981 color: shadow.color,
982 blur_radius: shadow.blur_radius.scale(scale_factor),
983 },
984 );
985 }
986 }
987
988 /// Paint one or more quads into the scene for the next frame at the current stacking context.
989 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
990 /// see [`fill`], [`outline`], and [`quad`] to construct this type.
991 pub fn paint_quad(&mut self, quad: PaintQuad) {
992 let scale_factor = self.scale_factor();
993 let content_mask = self.content_mask();
994
995 let window = &mut *self.window;
996 window.next_frame.scene_builder.insert(
997 &window.next_frame.z_index_stack,
998 Quad {
999 order: 0,
1000 bounds: quad.bounds.scale(scale_factor),
1001 content_mask: content_mask.scale(scale_factor),
1002 background: quad.background,
1003 border_color: quad.border_color,
1004 corner_radii: quad.corner_radii.scale(scale_factor),
1005 border_widths: quad.border_widths.scale(scale_factor),
1006 },
1007 );
1008 }
1009
1010 /// Paint the given `Path` into the scene for the next frame at the current z-index.
1011 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
1012 let scale_factor = self.scale_factor();
1013 let content_mask = self.content_mask();
1014 path.content_mask = content_mask;
1015 path.color = color.into();
1016 let window = &mut *self.window;
1017 window
1018 .next_frame
1019 .scene_builder
1020 .insert(&window.next_frame.z_index_stack, path.scale(scale_factor));
1021 }
1022
1023 /// Paint an underline into the scene for the next frame at the current z-index.
1024 pub fn paint_underline(
1025 &mut self,
1026 origin: Point<Pixels>,
1027 width: Pixels,
1028 style: &UnderlineStyle,
1029 ) {
1030 let scale_factor = self.scale_factor();
1031 let height = if style.wavy {
1032 style.thickness * 3.
1033 } else {
1034 style.thickness
1035 };
1036 let bounds = Bounds {
1037 origin,
1038 size: size(width, height),
1039 };
1040 let content_mask = self.content_mask();
1041 let window = &mut *self.window;
1042 window.next_frame.scene_builder.insert(
1043 &window.next_frame.z_index_stack,
1044 Underline {
1045 order: 0,
1046 bounds: bounds.scale(scale_factor),
1047 content_mask: content_mask.scale(scale_factor),
1048 thickness: style.thickness.scale(scale_factor),
1049 color: style.color.unwrap_or_default(),
1050 wavy: style.wavy,
1051 },
1052 );
1053 }
1054
1055 /// Paint a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
1056 /// The y component of the origin is the baseline of the glyph.
1057 pub fn paint_glyph(
1058 &mut self,
1059 origin: Point<Pixels>,
1060 font_id: FontId,
1061 glyph_id: GlyphId,
1062 font_size: Pixels,
1063 color: Hsla,
1064 ) -> Result<()> {
1065 let scale_factor = self.scale_factor();
1066 let glyph_origin = origin.scale(scale_factor);
1067 let subpixel_variant = Point {
1068 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1069 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
1070 };
1071 let params = RenderGlyphParams {
1072 font_id,
1073 glyph_id,
1074 font_size,
1075 subpixel_variant,
1076 scale_factor,
1077 is_emoji: false,
1078 };
1079
1080 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1081 if !raster_bounds.is_zero() {
1082 let tile =
1083 self.window
1084 .sprite_atlas
1085 .get_or_insert_with(¶ms.clone().into(), &mut || {
1086 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1087 Ok((size, Cow::Owned(bytes)))
1088 })?;
1089 let bounds = Bounds {
1090 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1091 size: tile.bounds.size.map(Into::into),
1092 };
1093 let content_mask = self.content_mask().scale(scale_factor);
1094 let window = &mut *self.window;
1095 window.next_frame.scene_builder.insert(
1096 &window.next_frame.z_index_stack,
1097 MonochromeSprite {
1098 order: 0,
1099 bounds,
1100 content_mask,
1101 color,
1102 tile,
1103 },
1104 );
1105 }
1106 Ok(())
1107 }
1108
1109 /// Paint an emoji glyph into the scene for the next frame at the current z-index.
1110 /// The y component of the origin is the baseline of the glyph.
1111 pub fn paint_emoji(
1112 &mut self,
1113 origin: Point<Pixels>,
1114 font_id: FontId,
1115 glyph_id: GlyphId,
1116 font_size: Pixels,
1117 ) -> Result<()> {
1118 let scale_factor = self.scale_factor();
1119 let glyph_origin = origin.scale(scale_factor);
1120 let params = RenderGlyphParams {
1121 font_id,
1122 glyph_id,
1123 font_size,
1124 // We don't render emojis with subpixel variants.
1125 subpixel_variant: Default::default(),
1126 scale_factor,
1127 is_emoji: true,
1128 };
1129
1130 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
1131 if !raster_bounds.is_zero() {
1132 let tile =
1133 self.window
1134 .sprite_atlas
1135 .get_or_insert_with(¶ms.clone().into(), &mut || {
1136 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
1137 Ok((size, Cow::Owned(bytes)))
1138 })?;
1139 let bounds = Bounds {
1140 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
1141 size: tile.bounds.size.map(Into::into),
1142 };
1143 let content_mask = self.content_mask().scale(scale_factor);
1144 let window = &mut *self.window;
1145
1146 window.next_frame.scene_builder.insert(
1147 &window.next_frame.z_index_stack,
1148 PolychromeSprite {
1149 order: 0,
1150 bounds,
1151 corner_radii: Default::default(),
1152 content_mask,
1153 tile,
1154 grayscale: false,
1155 },
1156 );
1157 }
1158 Ok(())
1159 }
1160
1161 /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
1162 pub fn paint_svg(
1163 &mut self,
1164 bounds: Bounds<Pixels>,
1165 path: SharedString,
1166 color: Hsla,
1167 ) -> Result<()> {
1168 let scale_factor = self.scale_factor();
1169 let bounds = bounds.scale(scale_factor);
1170 // Render the SVG at twice the size to get a higher quality result.
1171 let params = RenderSvgParams {
1172 path,
1173 size: bounds
1174 .size
1175 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
1176 };
1177
1178 let tile =
1179 self.window
1180 .sprite_atlas
1181 .get_or_insert_with(¶ms.clone().into(), &mut || {
1182 let bytes = self.svg_renderer.render(¶ms)?;
1183 Ok((params.size, Cow::Owned(bytes)))
1184 })?;
1185 let content_mask = self.content_mask().scale(scale_factor);
1186
1187 let window = &mut *self.window;
1188 window.next_frame.scene_builder.insert(
1189 &window.next_frame.z_index_stack,
1190 MonochromeSprite {
1191 order: 0,
1192 bounds,
1193 content_mask,
1194 color,
1195 tile,
1196 },
1197 );
1198
1199 Ok(())
1200 }
1201
1202 /// Paint an image into the scene for the next frame at the current z-index.
1203 pub fn paint_image(
1204 &mut self,
1205 bounds: Bounds<Pixels>,
1206 corner_radii: Corners<Pixels>,
1207 data: Arc<ImageData>,
1208 grayscale: bool,
1209 ) -> Result<()> {
1210 let scale_factor = self.scale_factor();
1211 let bounds = bounds.scale(scale_factor);
1212 let params = RenderImageParams { image_id: data.id };
1213
1214 let tile = self
1215 .window
1216 .sprite_atlas
1217 .get_or_insert_with(¶ms.clone().into(), &mut || {
1218 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1219 })?;
1220 let content_mask = self.content_mask().scale(scale_factor);
1221 let corner_radii = corner_radii.scale(scale_factor);
1222
1223 let window = &mut *self.window;
1224 window.next_frame.scene_builder.insert(
1225 &window.next_frame.z_index_stack,
1226 PolychromeSprite {
1227 order: 0,
1228 bounds,
1229 content_mask,
1230 corner_radii,
1231 tile,
1232 grayscale,
1233 },
1234 );
1235 Ok(())
1236 }
1237
1238 /// Paint a surface into the scene for the next frame at the current z-index.
1239 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVImageBuffer) {
1240 let scale_factor = self.scale_factor();
1241 let bounds = bounds.scale(scale_factor);
1242 let content_mask = self.content_mask().scale(scale_factor);
1243 let window = &mut *self.window;
1244 window.next_frame.scene_builder.insert(
1245 &window.next_frame.z_index_stack,
1246 Surface {
1247 order: 0,
1248 bounds,
1249 content_mask,
1250 image_buffer,
1251 },
1252 );
1253 }
1254
1255 /// Draw pixels to the display for this window based on the contents of its scene.
1256 pub(crate) fn draw(&mut self) -> Scene {
1257 let t0 = std::time::Instant::now();
1258 self.window.dirty = false;
1259 self.window.drawing = true;
1260
1261 let window_was_focused = self
1262 .window
1263 .focus
1264 .and_then(|focus_id| {
1265 self.window
1266 .rendered_frame
1267 .dispatch_tree
1268 .focusable_node_id(focus_id)
1269 })
1270 .is_some();
1271 self.text_system().start_frame();
1272 self.window.platform_window.clear_input_handler();
1273 self.window.layout_engine.as_mut().unwrap().clear();
1274 self.window.next_frame.clear();
1275 let root_view = self.window.root_view.take().unwrap();
1276
1277 self.with_z_index(0, |cx| {
1278 cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
1279 for (action_type, action_listeners) in &cx.app.global_action_listeners {
1280 for action_listener in action_listeners.iter().cloned() {
1281 cx.window.next_frame.dispatch_tree.on_action(
1282 *action_type,
1283 Rc::new(move |action, phase, cx| action_listener(action, phase, cx)),
1284 )
1285 }
1286 }
1287
1288 let available_space = cx.window.viewport_size.map(Into::into);
1289 root_view.draw(Point::default(), available_space, cx);
1290 })
1291 });
1292
1293 if let Some(active_drag) = self.app.active_drag.take() {
1294 self.with_z_index(ACTIVE_DRAG_Z_INDEX, |cx| {
1295 let offset = cx.mouse_position() - active_drag.cursor_offset;
1296 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1297 active_drag.view.draw(offset, available_space, cx);
1298 });
1299 self.active_drag = Some(active_drag);
1300 } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1301 self.with_z_index(1, |cx| {
1302 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1303 active_tooltip
1304 .view
1305 .draw(active_tooltip.cursor_offset, available_space, cx);
1306 });
1307 }
1308
1309 let window_is_focused = self
1310 .window
1311 .focus
1312 .and_then(|focus_id| {
1313 self.window
1314 .next_frame
1315 .dispatch_tree
1316 .focusable_node_id(focus_id)
1317 })
1318 .is_some();
1319 if window_was_focused && !window_is_focused {
1320 self.window
1321 .blur_listeners
1322 .clone()
1323 .retain(&(), |listener| listener(self));
1324 }
1325
1326 self.window
1327 .next_frame
1328 .dispatch_tree
1329 .preserve_pending_keystrokes(
1330 &mut self.window.rendered_frame.dispatch_tree,
1331 self.window.focus,
1332 );
1333 self.window.root_view = Some(root_view);
1334
1335 let window = &mut self.window;
1336 mem::swap(&mut window.rendered_frame, &mut window.next_frame);
1337
1338 let scene = self.window.rendered_frame.scene_builder.build();
1339
1340 // Set the cursor only if we're the active window.
1341 let cursor_style = self
1342 .window
1343 .requested_cursor_style
1344 .take()
1345 .unwrap_or(CursorStyle::Arrow);
1346 if self.is_window_active() {
1347 self.platform.set_cursor_style(cursor_style);
1348 }
1349
1350 self.window.drawing = false;
1351 eprintln!("window draw: {:?}", t0.elapsed());
1352
1353 scene
1354 }
1355
1356 /// Dispatch a mouse or keyboard event on the window.
1357 pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1358 // Handlers may set this to false by calling `stop_propagation`.
1359 self.app.propagate_event = true;
1360 // Handlers may set this to true by calling `prevent_default`.
1361 self.window.default_prevented = false;
1362
1363 let event = match event {
1364 // Track the mouse position with our own state, since accessing the platform
1365 // API for the mouse position can only occur on the main thread.
1366 InputEvent::MouseMove(mouse_move) => {
1367 self.window.mouse_position = mouse_move.position;
1368 self.window.modifiers = mouse_move.modifiers;
1369 InputEvent::MouseMove(mouse_move)
1370 }
1371 InputEvent::MouseDown(mouse_down) => {
1372 self.window.mouse_position = mouse_down.position;
1373 self.window.modifiers = mouse_down.modifiers;
1374 InputEvent::MouseDown(mouse_down)
1375 }
1376 InputEvent::MouseUp(mouse_up) => {
1377 self.window.mouse_position = mouse_up.position;
1378 self.window.modifiers = mouse_up.modifiers;
1379 InputEvent::MouseUp(mouse_up)
1380 }
1381 InputEvent::MouseExited(mouse_exited) => {
1382 // todo!("Should we record that the mouse is outside of the window somehow? Or are these global pixels?")
1383 self.window.modifiers = mouse_exited.modifiers;
1384
1385 InputEvent::MouseExited(mouse_exited)
1386 }
1387 InputEvent::ModifiersChanged(modifiers_changed) => {
1388 self.window.modifiers = modifiers_changed.modifiers;
1389 InputEvent::ModifiersChanged(modifiers_changed)
1390 }
1391 InputEvent::ScrollWheel(scroll_wheel) => {
1392 self.window.mouse_position = scroll_wheel.position;
1393 self.window.modifiers = scroll_wheel.modifiers;
1394 InputEvent::ScrollWheel(scroll_wheel)
1395 }
1396 // Translate dragging and dropping of external files from the operating system
1397 // to internal drag and drop events.
1398 InputEvent::FileDrop(file_drop) => match file_drop {
1399 FileDropEvent::Entered { position, files } => {
1400 self.window.mouse_position = position;
1401 if self.active_drag.is_none() {
1402 self.active_drag = Some(AnyDrag {
1403 value: Box::new(files.clone()),
1404 view: self.build_view(|_| files).into(),
1405 cursor_offset: position,
1406 });
1407 }
1408 InputEvent::MouseMove(MouseMoveEvent {
1409 position,
1410 pressed_button: Some(MouseButton::Left),
1411 modifiers: Modifiers::default(),
1412 })
1413 }
1414 FileDropEvent::Pending { position } => {
1415 self.window.mouse_position = position;
1416 InputEvent::MouseMove(MouseMoveEvent {
1417 position,
1418 pressed_button: Some(MouseButton::Left),
1419 modifiers: Modifiers::default(),
1420 })
1421 }
1422 FileDropEvent::Submit { position } => {
1423 self.activate(true);
1424 self.window.mouse_position = position;
1425 InputEvent::MouseUp(MouseUpEvent {
1426 button: MouseButton::Left,
1427 position,
1428 modifiers: Modifiers::default(),
1429 click_count: 1,
1430 })
1431 }
1432 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1433 button: MouseButton::Left,
1434 position: Point::default(),
1435 modifiers: Modifiers::default(),
1436 click_count: 1,
1437 }),
1438 },
1439 InputEvent::KeyDown(_) | InputEvent::KeyUp(_) => event,
1440 };
1441
1442 if let Some(any_mouse_event) = event.mouse_event() {
1443 self.dispatch_mouse_event(any_mouse_event);
1444 } else if let Some(any_key_event) = event.keyboard_event() {
1445 self.dispatch_key_event(any_key_event);
1446 }
1447
1448 !self.app.propagate_event
1449 }
1450
1451 fn dispatch_mouse_event(&mut self, event: &dyn Any) {
1452 if let Some(mut handlers) = self
1453 .window
1454 .rendered_frame
1455 .mouse_listeners
1456 .remove(&event.type_id())
1457 {
1458 // Because handlers may add other handlers, we sort every time.
1459 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1460
1461 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1462 // special purposes, such as detecting events outside of a given Bounds.
1463 for (_, handler) in &mut handlers {
1464 handler(event, DispatchPhase::Capture, self);
1465 if !self.app.propagate_event {
1466 break;
1467 }
1468 }
1469
1470 // Bubble phase, where most normal handlers do their work.
1471 if self.app.propagate_event {
1472 for (_, handler) in handlers.iter_mut().rev() {
1473 handler(event, DispatchPhase::Bubble, self);
1474 if !self.app.propagate_event {
1475 break;
1476 }
1477 }
1478 }
1479
1480 if self.app.propagate_event && event.downcast_ref::<MouseUpEvent>().is_some() {
1481 self.active_drag = None;
1482 }
1483
1484 self.window
1485 .rendered_frame
1486 .mouse_listeners
1487 .insert(event.type_id(), handlers);
1488 }
1489 }
1490
1491 fn dispatch_key_event(&mut self, event: &dyn Any) {
1492 let node_id = self
1493 .window
1494 .focus
1495 .and_then(|focus_id| {
1496 self.window
1497 .rendered_frame
1498 .dispatch_tree
1499 .focusable_node_id(focus_id)
1500 })
1501 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1502
1503 let dispatch_path = self
1504 .window
1505 .rendered_frame
1506 .dispatch_tree
1507 .dispatch_path(node_id);
1508
1509 let mut actions: Vec<Box<dyn Action>> = Vec::new();
1510
1511 // Capture phase
1512 let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
1513 self.propagate_event = true;
1514
1515 for node_id in &dispatch_path {
1516 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1517
1518 if let Some(context) = node.context.clone() {
1519 context_stack.push(context);
1520 }
1521
1522 for key_listener in node.key_listeners.clone() {
1523 key_listener(event, DispatchPhase::Capture, self);
1524 if !self.propagate_event {
1525 return;
1526 }
1527 }
1528 }
1529
1530 // Bubble phase
1531 for node_id in dispatch_path.iter().rev() {
1532 // Handle low level key events
1533 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1534 for key_listener in node.key_listeners.clone() {
1535 key_listener(event, DispatchPhase::Bubble, self);
1536 if !self.propagate_event {
1537 return;
1538 }
1539 }
1540
1541 // Match keystrokes
1542 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1543 if node.context.is_some() {
1544 if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
1545 let mut new_actions = self
1546 .window
1547 .rendered_frame
1548 .dispatch_tree
1549 .dispatch_key(&key_down_event.keystroke, &context_stack);
1550 actions.append(&mut new_actions);
1551 }
1552
1553 context_stack.pop();
1554 }
1555 }
1556
1557 for action in actions {
1558 self.dispatch_action_on_node(node_id, action.boxed_clone());
1559 if !self.propagate_event {
1560 self.dispatch_keystroke_observers(event, Some(action));
1561 return;
1562 }
1563 }
1564 self.dispatch_keystroke_observers(event, None);
1565 }
1566
1567 pub fn has_pending_keystrokes(&self) -> bool {
1568 self.window
1569 .rendered_frame
1570 .dispatch_tree
1571 .has_pending_keystrokes()
1572 }
1573
1574 fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
1575 let dispatch_path = self
1576 .window
1577 .rendered_frame
1578 .dispatch_tree
1579 .dispatch_path(node_id);
1580
1581 // Capture phase
1582 for node_id in &dispatch_path {
1583 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1584 for DispatchActionListener {
1585 action_type,
1586 listener,
1587 } in node.action_listeners.clone()
1588 {
1589 let any_action = action.as_any();
1590 if action_type == any_action.type_id() {
1591 listener(any_action, DispatchPhase::Capture, self);
1592 if !self.propagate_event {
1593 return;
1594 }
1595 }
1596 }
1597 }
1598 // Bubble phase
1599 for node_id in dispatch_path.iter().rev() {
1600 let node = self.window.rendered_frame.dispatch_tree.node(*node_id);
1601 for DispatchActionListener {
1602 action_type,
1603 listener,
1604 } in node.action_listeners.clone()
1605 {
1606 let any_action = action.as_any();
1607 if action_type == any_action.type_id() {
1608 self.propagate_event = false; // Actions stop propagation by default during the bubble phase
1609 listener(any_action, DispatchPhase::Bubble, self);
1610 if !self.propagate_event {
1611 return;
1612 }
1613 }
1614 }
1615 }
1616 }
1617
1618 /// Register the given handler to be invoked whenever the global of the given type
1619 /// is updated.
1620 pub fn observe_global<G: 'static>(
1621 &mut self,
1622 f: impl Fn(&mut WindowContext<'_>) + 'static,
1623 ) -> Subscription {
1624 let window_handle = self.window.handle;
1625 let (subscription, activate) = self.global_observers.insert(
1626 TypeId::of::<G>(),
1627 Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1628 );
1629 self.app.defer(move |_| activate());
1630 subscription
1631 }
1632
1633 pub fn activate_window(&self) {
1634 self.window.platform_window.activate();
1635 }
1636
1637 pub fn minimize_window(&self) {
1638 self.window.platform_window.minimize();
1639 }
1640
1641 pub fn toggle_full_screen(&self) {
1642 self.window.platform_window.toggle_full_screen();
1643 }
1644
1645 pub fn prompt(
1646 &self,
1647 level: PromptLevel,
1648 msg: &str,
1649 answers: &[&str],
1650 ) -> oneshot::Receiver<usize> {
1651 self.window.platform_window.prompt(level, msg, answers)
1652 }
1653
1654 pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
1655 let node_id = self
1656 .window
1657 .focus
1658 .and_then(|focus_id| {
1659 self.window
1660 .rendered_frame
1661 .dispatch_tree
1662 .focusable_node_id(focus_id)
1663 })
1664 .unwrap_or_else(|| self.window.rendered_frame.dispatch_tree.root_node_id());
1665
1666 self.window
1667 .rendered_frame
1668 .dispatch_tree
1669 .available_actions(node_id)
1670 }
1671
1672 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
1673 self.window
1674 .rendered_frame
1675 .dispatch_tree
1676 .bindings_for_action(
1677 action,
1678 &self.window.rendered_frame.dispatch_tree.context_stack,
1679 )
1680 }
1681
1682 pub fn bindings_for_action_in(
1683 &self,
1684 action: &dyn Action,
1685 focus_handle: &FocusHandle,
1686 ) -> Vec<KeyBinding> {
1687 let dispatch_tree = &self.window.rendered_frame.dispatch_tree;
1688
1689 let Some(node_id) = dispatch_tree.focusable_node_id(focus_handle.id) else {
1690 return vec![];
1691 };
1692 let context_stack = dispatch_tree
1693 .dispatch_path(node_id)
1694 .into_iter()
1695 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
1696 .collect();
1697 dispatch_tree.bindings_for_action(action, &context_stack)
1698 }
1699
1700 pub fn listener_for<V: Render, E>(
1701 &self,
1702 view: &View<V>,
1703 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
1704 ) -> impl Fn(&E, &mut WindowContext) + 'static {
1705 let view = view.downgrade();
1706 move |e: &E, cx: &mut WindowContext| {
1707 view.update(cx, |view, cx| f(view, e, cx)).ok();
1708 }
1709 }
1710
1711 pub fn handler_for<V: Render>(
1712 &self,
1713 view: &View<V>,
1714 f: impl Fn(&mut V, &mut ViewContext<V>) + 'static,
1715 ) -> impl Fn(&mut WindowContext) {
1716 let view = view.downgrade();
1717 move |cx: &mut WindowContext| {
1718 view.update(cx, |view, cx| f(view, cx)).ok();
1719 }
1720 }
1721
1722 //========== ELEMENT RELATED FUNCTIONS ===========
1723 pub fn with_key_dispatch<R>(
1724 &mut self,
1725 context: Option<KeyContext>,
1726 focus_handle: Option<FocusHandle>,
1727 f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
1728 ) -> R {
1729 let window = &mut self.window;
1730 window.next_frame.dispatch_tree.push_node(context.clone());
1731 if let Some(focus_handle) = focus_handle.as_ref() {
1732 window
1733 .next_frame
1734 .dispatch_tree
1735 .make_focusable(focus_handle.id);
1736 }
1737 let result = f(focus_handle, self);
1738
1739 self.window.next_frame.dispatch_tree.pop_node();
1740
1741 result
1742 }
1743
1744 /// Register a focus listener for the next frame only. It will be cleared
1745 /// on the next frame render. You should use this method only from within elements,
1746 /// and we may want to enforce that better via a different context type.
1747 // todo!() Move this to `FrameContext` to emphasize its individuality?
1748 pub fn on_focus_changed(
1749 &mut self,
1750 listener: impl Fn(&FocusEvent, &mut WindowContext) + 'static,
1751 ) {
1752 self.window
1753 .next_frame
1754 .focus_listeners
1755 .push(Box::new(move |event, cx| {
1756 listener(event, cx);
1757 }));
1758 }
1759
1760 /// Set an input handler, such as [ElementInputHandler], which interfaces with the
1761 /// platform to receive textual input with proper integration with concerns such
1762 /// as IME interactions.
1763 pub fn handle_input(
1764 &mut self,
1765 focus_handle: &FocusHandle,
1766 input_handler: impl PlatformInputHandler,
1767 ) {
1768 if focus_handle.is_focused(self) {
1769 self.window
1770 .platform_window
1771 .set_input_handler(Box::new(input_handler));
1772 }
1773 }
1774
1775 pub fn on_window_should_close(&mut self, f: impl Fn(&mut WindowContext) -> bool + 'static) {
1776 let mut this = self.to_async();
1777 self.window
1778 .platform_window
1779 .on_should_close(Box::new(move || this.update(|_, cx| f(cx)).unwrap_or(true)))
1780 }
1781}
1782
1783impl Context for WindowContext<'_> {
1784 type Result<T> = T;
1785
1786 fn build_model<T>(
1787 &mut self,
1788 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1789 ) -> Model<T>
1790 where
1791 T: 'static,
1792 {
1793 let slot = self.app.entities.reserve();
1794 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1795 self.entities.insert(slot, model)
1796 }
1797
1798 fn update_model<T: 'static, R>(
1799 &mut self,
1800 model: &Model<T>,
1801 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1802 ) -> R {
1803 let mut entity = self.entities.lease(model);
1804 let result = update(
1805 &mut *entity,
1806 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1807 );
1808 self.entities.end_lease(entity);
1809 result
1810 }
1811
1812 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1813 where
1814 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1815 {
1816 if window == self.window.handle {
1817 let root_view = self.window.root_view.clone().unwrap();
1818 Ok(update(root_view, self))
1819 } else {
1820 window.update(self.app, update)
1821 }
1822 }
1823
1824 fn read_model<T, R>(
1825 &self,
1826 handle: &Model<T>,
1827 read: impl FnOnce(&T, &AppContext) -> R,
1828 ) -> Self::Result<R>
1829 where
1830 T: 'static,
1831 {
1832 let entity = self.entities.read(handle);
1833 read(&*entity, &*self.app)
1834 }
1835
1836 fn read_window<T, R>(
1837 &self,
1838 window: &WindowHandle<T>,
1839 read: impl FnOnce(View<T>, &AppContext) -> R,
1840 ) -> Result<R>
1841 where
1842 T: 'static,
1843 {
1844 if window.any_handle == self.window.handle {
1845 let root_view = self
1846 .window
1847 .root_view
1848 .clone()
1849 .unwrap()
1850 .downcast::<T>()
1851 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
1852 Ok(read(root_view, self))
1853 } else {
1854 self.app.read_window(window, read)
1855 }
1856 }
1857}
1858
1859impl VisualContext for WindowContext<'_> {
1860 fn build_view<V>(
1861 &mut self,
1862 build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1863 ) -> Self::Result<View<V>>
1864 where
1865 V: 'static + Render,
1866 {
1867 let slot = self.app.entities.reserve();
1868 let view = View {
1869 model: slot.clone(),
1870 };
1871 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1872 let entity = build_view_state(&mut cx);
1873 cx.entities.insert(slot, entity);
1874
1875 cx.new_view_observers
1876 .clone()
1877 .retain(&TypeId::of::<V>(), |observer| {
1878 let any_view = AnyView::from(view.clone());
1879 (observer)(any_view, self);
1880 true
1881 });
1882
1883 view
1884 }
1885
1886 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1887 fn update_view<T: 'static, R>(
1888 &mut self,
1889 view: &View<T>,
1890 update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1891 ) -> Self::Result<R> {
1892 let mut lease = self.app.entities.lease(&view.model);
1893 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1894 let result = update(&mut *lease, &mut cx);
1895 cx.app.entities.end_lease(lease);
1896 result
1897 }
1898
1899 fn replace_root_view<V>(
1900 &mut self,
1901 build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1902 ) -> Self::Result<View<V>>
1903 where
1904 V: 'static + Render,
1905 {
1906 let slot = self.app.entities.reserve();
1907 let view = View {
1908 model: slot.clone(),
1909 };
1910 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1911 let entity = build_view(&mut cx);
1912 self.entities.insert(slot, entity);
1913 self.window.root_view = Some(view.clone().into());
1914 view
1915 }
1916
1917 fn focus_view<V: crate::FocusableView>(&mut self, view: &View<V>) -> Self::Result<()> {
1918 self.update_view(view, |view, cx| {
1919 view.focus_handle(cx).clone().focus(cx);
1920 })
1921 }
1922
1923 fn dismiss_view<V>(&mut self, view: &View<V>) -> Self::Result<()>
1924 where
1925 V: ManagedView,
1926 {
1927 self.update_view(view, |_, cx| cx.emit(DismissEvent))
1928 }
1929}
1930
1931impl<'a> std::ops::Deref for WindowContext<'a> {
1932 type Target = AppContext;
1933
1934 fn deref(&self) -> &Self::Target {
1935 &self.app
1936 }
1937}
1938
1939impl<'a> std::ops::DerefMut for WindowContext<'a> {
1940 fn deref_mut(&mut self) -> &mut Self::Target {
1941 &mut self.app
1942 }
1943}
1944
1945impl<'a> Borrow<AppContext> for WindowContext<'a> {
1946 fn borrow(&self) -> &AppContext {
1947 &self.app
1948 }
1949}
1950
1951impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1952 fn borrow_mut(&mut self) -> &mut AppContext {
1953 &mut self.app
1954 }
1955}
1956
1957pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1958 fn app_mut(&mut self) -> &mut AppContext {
1959 self.borrow_mut()
1960 }
1961
1962 fn app(&self) -> &AppContext {
1963 self.borrow()
1964 }
1965
1966 fn window(&self) -> &Window {
1967 self.borrow()
1968 }
1969
1970 fn window_mut(&mut self) -> &mut Window {
1971 self.borrow_mut()
1972 }
1973
1974 /// Pushes the given element id onto the global stack and invokes the given closure
1975 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1976 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1977 /// used to associate state with identified elements across separate frames.
1978 fn with_element_id<R>(
1979 &mut self,
1980 id: Option<impl Into<ElementId>>,
1981 f: impl FnOnce(&mut Self) -> R,
1982 ) -> R {
1983 if let Some(id) = id.map(Into::into) {
1984 let window = self.window_mut();
1985 window.element_id_stack.push(id.into());
1986 let result = f(self);
1987 let window: &mut Window = self.borrow_mut();
1988 window.element_id_stack.pop();
1989 result
1990 } else {
1991 f(self)
1992 }
1993 }
1994
1995 /// Invoke the given function with the given content mask after intersecting it
1996 /// with the current mask.
1997 fn with_content_mask<R>(
1998 &mut self,
1999 mask: Option<ContentMask<Pixels>>,
2000 f: impl FnOnce(&mut Self) -> R,
2001 ) -> R {
2002 if let Some(mask) = mask {
2003 let mask = mask.intersect(&self.content_mask());
2004 self.window_mut().next_frame.content_mask_stack.push(mask);
2005 let result = f(self);
2006 self.window_mut().next_frame.content_mask_stack.pop();
2007 result
2008 } else {
2009 f(self)
2010 }
2011 }
2012
2013 /// Invoke the given function with the content mask reset to that
2014 /// of the window.
2015 fn break_content_mask<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
2016 let mask = ContentMask {
2017 bounds: Bounds {
2018 origin: Point::default(),
2019 size: self.window().viewport_size,
2020 },
2021 };
2022 self.window_mut().next_frame.content_mask_stack.push(mask);
2023 let result = f(self);
2024 self.window_mut().next_frame.content_mask_stack.pop();
2025 result
2026 }
2027
2028 /// Update the global element offset relative to the current offset. This is used to implement
2029 /// scrolling.
2030 fn with_element_offset<R>(
2031 &mut self,
2032 offset: Point<Pixels>,
2033 f: impl FnOnce(&mut Self) -> R,
2034 ) -> R {
2035 if offset.is_zero() {
2036 return f(self);
2037 };
2038
2039 let abs_offset = self.element_offset() + offset;
2040 self.with_absolute_element_offset(abs_offset, f)
2041 }
2042
2043 /// Update the global element offset based on the given offset. This is used to implement
2044 /// drag handles and other manual painting of elements.
2045 fn with_absolute_element_offset<R>(
2046 &mut self,
2047 offset: Point<Pixels>,
2048 f: impl FnOnce(&mut Self) -> R,
2049 ) -> R {
2050 self.window_mut()
2051 .next_frame
2052 .element_offset_stack
2053 .push(offset);
2054 let result = f(self);
2055 self.window_mut().next_frame.element_offset_stack.pop();
2056 result
2057 }
2058
2059 /// Obtain the current element offset.
2060 fn element_offset(&self) -> Point<Pixels> {
2061 self.window()
2062 .next_frame
2063 .element_offset_stack
2064 .last()
2065 .copied()
2066 .unwrap_or_default()
2067 }
2068
2069 /// Update or initialize state for an element with the given id that lives across multiple
2070 /// frames. If an element with this id existed in the rendered frame, its state will be passed
2071 /// to the given closure. The state returned by the closure will be stored so it can be referenced
2072 /// when drawing the next frame.
2073 fn with_element_state<S, R>(
2074 &mut self,
2075 id: ElementId,
2076 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
2077 ) -> R
2078 where
2079 S: 'static,
2080 {
2081 self.with_element_id(Some(id), |cx| {
2082 let global_id = cx.window().element_id_stack.clone();
2083
2084 if let Some(any) = cx
2085 .window_mut()
2086 .next_frame
2087 .element_states
2088 .remove(&global_id)
2089 .or_else(|| {
2090 cx.window_mut()
2091 .rendered_frame
2092 .element_states
2093 .remove(&global_id)
2094 })
2095 {
2096 let ElementStateBox {
2097 inner,
2098
2099 #[cfg(debug_assertions)]
2100 type_name
2101 } = any;
2102 // Using the extra inner option to avoid needing to reallocate a new box.
2103 let mut state_box = inner
2104 .downcast::<Option<S>>()
2105 .map_err(|_| {
2106 #[cfg(debug_assertions)]
2107 {
2108 anyhow!(
2109 "invalid element state type for id, requested_type {:?}, actual type: {:?}",
2110 std::any::type_name::<S>(),
2111 type_name
2112 )
2113 }
2114
2115 #[cfg(not(debug_assertions))]
2116 {
2117 anyhow!(
2118 "invalid element state type for id, requested_type {:?}",
2119 std::any::type_name::<S>(),
2120 )
2121 }
2122 })
2123 .unwrap();
2124
2125 // Actual: Option<AnyElement> <- View
2126 // Requested: () <- AnyElemet
2127 let state = state_box
2128 .take()
2129 .expect("element state is already on the stack");
2130 let (result, state) = f(Some(state), cx);
2131 state_box.replace(state);
2132 cx.window_mut()
2133 .next_frame
2134 .element_states
2135 .insert(global_id, ElementStateBox {
2136 inner: state_box,
2137
2138 #[cfg(debug_assertions)]
2139 type_name
2140 });
2141 result
2142 } else {
2143 let (result, state) = f(None, cx);
2144 cx.window_mut()
2145 .next_frame
2146 .element_states
2147 .insert(global_id,
2148 ElementStateBox {
2149 inner: Box::new(Some(state)),
2150
2151 #[cfg(debug_assertions)]
2152 type_name: std::any::type_name::<S>()
2153 }
2154
2155 );
2156 result
2157 }
2158 })
2159 }
2160
2161 /// Obtain the current content mask.
2162 fn content_mask(&self) -> ContentMask<Pixels> {
2163 self.window()
2164 .next_frame
2165 .content_mask_stack
2166 .last()
2167 .cloned()
2168 .unwrap_or_else(|| ContentMask {
2169 bounds: Bounds {
2170 origin: Point::default(),
2171 size: self.window().viewport_size,
2172 },
2173 })
2174 }
2175
2176 /// The size of an em for the base font of the application. Adjusting this value allows the
2177 /// UI to scale, just like zooming a web page.
2178 fn rem_size(&self) -> Pixels {
2179 self.window().rem_size
2180 }
2181}
2182
2183impl Borrow<Window> for WindowContext<'_> {
2184 fn borrow(&self) -> &Window {
2185 &self.window
2186 }
2187}
2188
2189impl BorrowMut<Window> for WindowContext<'_> {
2190 fn borrow_mut(&mut self) -> &mut Window {
2191 &mut self.window
2192 }
2193}
2194
2195impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
2196
2197pub struct ViewContext<'a, V> {
2198 window_cx: WindowContext<'a>,
2199 view: &'a View<V>,
2200}
2201
2202impl<V> Borrow<AppContext> for ViewContext<'_, V> {
2203 fn borrow(&self) -> &AppContext {
2204 &*self.window_cx.app
2205 }
2206}
2207
2208impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
2209 fn borrow_mut(&mut self) -> &mut AppContext {
2210 &mut *self.window_cx.app
2211 }
2212}
2213
2214impl<V> Borrow<Window> for ViewContext<'_, V> {
2215 fn borrow(&self) -> &Window {
2216 &*self.window_cx.window
2217 }
2218}
2219
2220impl<V> BorrowMut<Window> for ViewContext<'_, V> {
2221 fn borrow_mut(&mut self) -> &mut Window {
2222 &mut *self.window_cx.window
2223 }
2224}
2225
2226impl<'a, V: 'static> ViewContext<'a, V> {
2227 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
2228 Self {
2229 window_cx: WindowContext::new(app, window),
2230 view,
2231 }
2232 }
2233
2234 pub fn entity_id(&self) -> EntityId {
2235 self.view.entity_id()
2236 }
2237
2238 pub fn view(&self) -> &View<V> {
2239 self.view
2240 }
2241
2242 pub fn model(&self) -> &Model<V> {
2243 &self.view.model
2244 }
2245
2246 /// Access the underlying window context.
2247 pub fn window_context(&mut self) -> &mut WindowContext<'a> {
2248 &mut self.window_cx
2249 }
2250
2251 pub fn with_z_index<R>(&mut self, z_index: u8, f: impl FnOnce(&mut Self) -> R) -> R {
2252 self.window.next_frame.z_index_stack.push(z_index);
2253 let result = f(self);
2254 self.window.next_frame.z_index_stack.pop();
2255 result
2256 }
2257
2258 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
2259 where
2260 V: 'static,
2261 {
2262 let view = self.view().clone();
2263 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
2264 }
2265
2266 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
2267 /// that are currently on the stack to be returned to the app.
2268 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
2269 let view = self.view().downgrade();
2270 self.window_cx.defer(move |cx| {
2271 view.update(cx, f).ok();
2272 });
2273 }
2274
2275 pub fn observe<V2, E>(
2276 &mut self,
2277 entity: &E,
2278 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
2279 ) -> Subscription
2280 where
2281 V2: 'static,
2282 V: 'static,
2283 E: Entity<V2>,
2284 {
2285 let view = self.view().downgrade();
2286 let entity_id = entity.entity_id();
2287 let entity = entity.downgrade();
2288 let window_handle = self.window.handle;
2289 let (subscription, activate) = self.app.observers.insert(
2290 entity_id,
2291 Box::new(move |cx| {
2292 window_handle
2293 .update(cx, |_, cx| {
2294 if let Some(handle) = E::upgrade_from(&entity) {
2295 view.update(cx, |this, cx| on_notify(this, handle, cx))
2296 .is_ok()
2297 } else {
2298 false
2299 }
2300 })
2301 .unwrap_or(false)
2302 }),
2303 );
2304 self.app.defer(move |_| activate());
2305 subscription
2306 }
2307
2308 pub fn subscribe<V2, E, Evt>(
2309 &mut self,
2310 entity: &E,
2311 mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
2312 ) -> Subscription
2313 where
2314 V2: EventEmitter<Evt>,
2315 E: Entity<V2>,
2316 Evt: 'static,
2317 {
2318 let view = self.view().downgrade();
2319 let entity_id = entity.entity_id();
2320 let handle = entity.downgrade();
2321 let window_handle = self.window.handle;
2322 let (subscription, activate) = self.app.event_listeners.insert(
2323 entity_id,
2324 (
2325 TypeId::of::<Evt>(),
2326 Box::new(move |event, cx| {
2327 window_handle
2328 .update(cx, |_, cx| {
2329 if let Some(handle) = E::upgrade_from(&handle) {
2330 let event = event.downcast_ref().expect("invalid event type");
2331 view.update(cx, |this, cx| on_event(this, handle, event, cx))
2332 .is_ok()
2333 } else {
2334 false
2335 }
2336 })
2337 .unwrap_or(false)
2338 }),
2339 ),
2340 );
2341 self.app.defer(move |_| activate());
2342 subscription
2343 }
2344
2345 pub fn on_release(
2346 &mut self,
2347 on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
2348 ) -> Subscription {
2349 let window_handle = self.window.handle;
2350 let (subscription, activate) = self.app.release_listeners.insert(
2351 self.view.model.entity_id,
2352 Box::new(move |this, cx| {
2353 let this = this.downcast_mut().expect("invalid entity type");
2354 let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
2355 }),
2356 );
2357 activate();
2358 subscription
2359 }
2360
2361 pub fn observe_release<V2, E>(
2362 &mut self,
2363 entity: &E,
2364 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
2365 ) -> Subscription
2366 where
2367 V: 'static,
2368 V2: 'static,
2369 E: Entity<V2>,
2370 {
2371 let view = self.view().downgrade();
2372 let entity_id = entity.entity_id();
2373 let window_handle = self.window.handle;
2374 let (subscription, activate) = self.app.release_listeners.insert(
2375 entity_id,
2376 Box::new(move |entity, cx| {
2377 let entity = entity.downcast_mut().expect("invalid entity type");
2378 let _ = window_handle.update(cx, |_, cx| {
2379 view.update(cx, |this, cx| on_release(this, entity, cx))
2380 });
2381 }),
2382 );
2383 activate();
2384 subscription
2385 }
2386
2387 pub fn notify(&mut self) {
2388 if !self.window.drawing {
2389 self.window_cx.notify();
2390 self.window_cx.app.push_effect(Effect::Notify {
2391 emitter: self.view.model.entity_id,
2392 });
2393 }
2394 }
2395
2396 pub fn observe_window_bounds(
2397 &mut self,
2398 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2399 ) -> Subscription {
2400 let view = self.view.downgrade();
2401 let (subscription, activate) = self.window.bounds_observers.insert(
2402 (),
2403 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2404 );
2405 activate();
2406 subscription
2407 }
2408
2409 pub fn observe_window_activation(
2410 &mut self,
2411 mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2412 ) -> Subscription {
2413 let view = self.view.downgrade();
2414 let (subscription, activate) = self.window.activation_observers.insert(
2415 (),
2416 Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
2417 );
2418 activate();
2419 subscription
2420 }
2421
2422 /// Register a listener to be called when the given focus handle receives focus.
2423 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2424 /// is dropped.
2425 pub fn on_focus(
2426 &mut self,
2427 handle: &FocusHandle,
2428 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2429 ) -> Subscription {
2430 let view = self.view.downgrade();
2431 let focus_id = handle.id;
2432 let (subscription, activate) = self.window.focus_listeners.insert(
2433 (),
2434 Box::new(move |event, cx| {
2435 view.update(cx, |view, cx| {
2436 if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
2437 listener(view, cx)
2438 }
2439 })
2440 .is_ok()
2441 }),
2442 );
2443 self.app.defer(move |_| activate());
2444 subscription
2445 }
2446
2447 /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2448 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2449 /// is dropped.
2450 pub fn on_focus_in(
2451 &mut self,
2452 handle: &FocusHandle,
2453 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2454 ) -> Subscription {
2455 let view = self.view.downgrade();
2456 let focus_id = handle.id;
2457 let (subscription, activate) = self.window.focus_listeners.insert(
2458 (),
2459 Box::new(move |event, cx| {
2460 view.update(cx, |view, cx| {
2461 if event
2462 .focused
2463 .as_ref()
2464 .map_or(false, |focused| focus_id.contains(focused.id, cx))
2465 {
2466 listener(view, cx)
2467 }
2468 })
2469 .is_ok()
2470 }),
2471 );
2472 self.app.defer(move |_| activate());
2473 subscription
2474 }
2475
2476 /// Register a listener to be called when the given focus handle loses focus.
2477 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2478 /// is dropped.
2479 pub fn on_blur(
2480 &mut self,
2481 handle: &FocusHandle,
2482 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2483 ) -> Subscription {
2484 let view = self.view.downgrade();
2485 let focus_id = handle.id;
2486 let (subscription, activate) = self.window.focus_listeners.insert(
2487 (),
2488 Box::new(move |event, cx| {
2489 view.update(cx, |view, cx| {
2490 if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2491 listener(view, cx)
2492 }
2493 })
2494 .is_ok()
2495 }),
2496 );
2497 self.app.defer(move |_| activate());
2498 subscription
2499 }
2500
2501 /// Register a listener to be called when the window loses focus.
2502 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2503 /// is dropped.
2504 pub fn on_blur_window(
2505 &mut self,
2506 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2507 ) -> Subscription {
2508 let view = self.view.downgrade();
2509 let (subscription, activate) = self.window.blur_listeners.insert(
2510 (),
2511 Box::new(move |cx| view.update(cx, |view, cx| listener(view, cx)).is_ok()),
2512 );
2513 activate();
2514 subscription
2515 }
2516
2517 /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2518 /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2519 /// is dropped.
2520 pub fn on_focus_out(
2521 &mut self,
2522 handle: &FocusHandle,
2523 mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2524 ) -> Subscription {
2525 let view = self.view.downgrade();
2526 let focus_id = handle.id;
2527 let (subscription, activate) = self.window.focus_listeners.insert(
2528 (),
2529 Box::new(move |event, cx| {
2530 view.update(cx, |view, cx| {
2531 if event
2532 .blurred
2533 .as_ref()
2534 .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2535 {
2536 listener(view, cx)
2537 }
2538 })
2539 .is_ok()
2540 }),
2541 );
2542 self.app.defer(move |_| activate());
2543 subscription
2544 }
2545
2546 pub fn spawn<Fut, R>(
2547 &mut self,
2548 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2549 ) -> Task<R>
2550 where
2551 R: 'static,
2552 Fut: Future<Output = R> + 'static,
2553 {
2554 let view = self.view().downgrade();
2555 self.window_cx.spawn(|cx| f(view, cx))
2556 }
2557
2558 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2559 where
2560 G: 'static,
2561 {
2562 let mut global = self.app.lease_global::<G>();
2563 let result = f(&mut global, self);
2564 self.app.end_global_lease(global);
2565 result
2566 }
2567
2568 pub fn observe_global<G: 'static>(
2569 &mut self,
2570 mut f: impl FnMut(&mut V, &mut ViewContext<'_, V>) + 'static,
2571 ) -> Subscription {
2572 let window_handle = self.window.handle;
2573 let view = self.view().downgrade();
2574 let (subscription, activate) = self.global_observers.insert(
2575 TypeId::of::<G>(),
2576 Box::new(move |cx| {
2577 window_handle
2578 .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2579 .unwrap_or(false)
2580 }),
2581 );
2582 self.app.defer(move |_| activate());
2583 subscription
2584 }
2585
2586 pub fn on_mouse_event<Event: 'static>(
2587 &mut self,
2588 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2589 ) {
2590 let handle = self.view().clone();
2591 self.window_cx.on_mouse_event(move |event, phase, cx| {
2592 handle.update(cx, |view, cx| {
2593 handler(view, event, phase, cx);
2594 })
2595 });
2596 }
2597
2598 pub fn on_key_event<Event: 'static>(
2599 &mut self,
2600 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2601 ) {
2602 let handle = self.view().clone();
2603 self.window_cx.on_key_event(move |event, phase, cx| {
2604 handle.update(cx, |view, cx| {
2605 handler(view, event, phase, cx);
2606 })
2607 });
2608 }
2609
2610 pub fn on_action(
2611 &mut self,
2612 action_type: TypeId,
2613 handler: impl Fn(&mut V, &dyn Any, DispatchPhase, &mut ViewContext<V>) + 'static,
2614 ) {
2615 let handle = self.view().clone();
2616 self.window_cx
2617 .on_action(action_type, move |action, phase, cx| {
2618 handle.update(cx, |view, cx| {
2619 handler(view, action, phase, cx);
2620 })
2621 });
2622 }
2623
2624 pub fn emit<Evt>(&mut self, event: Evt)
2625 where
2626 Evt: 'static,
2627 V: EventEmitter<Evt>,
2628 {
2629 let emitter = self.view.model.entity_id;
2630 self.app.push_effect(Effect::Emit {
2631 emitter,
2632 event_type: TypeId::of::<Evt>(),
2633 event: Box::new(event),
2634 });
2635 }
2636
2637 pub fn focus_self(&mut self)
2638 where
2639 V: FocusableView,
2640 {
2641 self.defer(|view, cx| view.focus_handle(cx).focus(cx))
2642 }
2643
2644 pub fn dismiss_self(&mut self)
2645 where
2646 V: ManagedView,
2647 {
2648 self.defer(|_, cx| cx.emit(DismissEvent))
2649 }
2650
2651 pub fn listener<E>(
2652 &self,
2653 f: impl Fn(&mut V, &E, &mut ViewContext<V>) + 'static,
2654 ) -> impl Fn(&E, &mut WindowContext) + 'static {
2655 let view = self.view().downgrade();
2656 move |e: &E, cx: &mut WindowContext| {
2657 view.update(cx, |view, cx| f(view, e, cx)).ok();
2658 }
2659 }
2660}
2661
2662impl<V> Context for ViewContext<'_, V> {
2663 type Result<U> = U;
2664
2665 fn build_model<T: 'static>(
2666 &mut self,
2667 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2668 ) -> Model<T> {
2669 self.window_cx.build_model(build_model)
2670 }
2671
2672 fn update_model<T: 'static, R>(
2673 &mut self,
2674 model: &Model<T>,
2675 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2676 ) -> R {
2677 self.window_cx.update_model(model, update)
2678 }
2679
2680 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2681 where
2682 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2683 {
2684 self.window_cx.update_window(window, update)
2685 }
2686
2687 fn read_model<T, R>(
2688 &self,
2689 handle: &Model<T>,
2690 read: impl FnOnce(&T, &AppContext) -> R,
2691 ) -> Self::Result<R>
2692 where
2693 T: 'static,
2694 {
2695 self.window_cx.read_model(handle, read)
2696 }
2697
2698 fn read_window<T, R>(
2699 &self,
2700 window: &WindowHandle<T>,
2701 read: impl FnOnce(View<T>, &AppContext) -> R,
2702 ) -> Result<R>
2703 where
2704 T: 'static,
2705 {
2706 self.window_cx.read_window(window, read)
2707 }
2708}
2709
2710impl<V: 'static> VisualContext for ViewContext<'_, V> {
2711 fn build_view<W: Render + 'static>(
2712 &mut self,
2713 build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2714 ) -> Self::Result<View<W>> {
2715 self.window_cx.build_view(build_view_state)
2716 }
2717
2718 fn update_view<V2: 'static, R>(
2719 &mut self,
2720 view: &View<V2>,
2721 update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2722 ) -> Self::Result<R> {
2723 self.window_cx.update_view(view, update)
2724 }
2725
2726 fn replace_root_view<W>(
2727 &mut self,
2728 build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2729 ) -> Self::Result<View<W>>
2730 where
2731 W: 'static + Render,
2732 {
2733 self.window_cx.replace_root_view(build_view)
2734 }
2735
2736 fn focus_view<W: FocusableView>(&mut self, view: &View<W>) -> Self::Result<()> {
2737 self.window_cx.focus_view(view)
2738 }
2739
2740 fn dismiss_view<W: ManagedView>(&mut self, view: &View<W>) -> Self::Result<()> {
2741 self.window_cx.dismiss_view(view)
2742 }
2743}
2744
2745impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2746 type Target = WindowContext<'a>;
2747
2748 fn deref(&self) -> &Self::Target {
2749 &self.window_cx
2750 }
2751}
2752
2753impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2754 fn deref_mut(&mut self) -> &mut Self::Target {
2755 &mut self.window_cx
2756 }
2757}
2758
2759// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2760slotmap::new_key_type! { pub struct WindowId; }
2761
2762impl WindowId {
2763 pub fn as_u64(&self) -> u64 {
2764 self.0.as_ffi()
2765 }
2766}
2767
2768#[derive(Deref, DerefMut)]
2769pub struct WindowHandle<V> {
2770 #[deref]
2771 #[deref_mut]
2772 pub(crate) any_handle: AnyWindowHandle,
2773 state_type: PhantomData<V>,
2774}
2775
2776impl<V: 'static + Render> WindowHandle<V> {
2777 pub fn new(id: WindowId) -> Self {
2778 WindowHandle {
2779 any_handle: AnyWindowHandle {
2780 id,
2781 state_type: TypeId::of::<V>(),
2782 },
2783 state_type: PhantomData,
2784 }
2785 }
2786
2787 pub fn root<C>(&self, cx: &mut C) -> Result<View<V>>
2788 where
2789 C: Context,
2790 {
2791 Flatten::flatten(cx.update_window(self.any_handle, |root_view, _| {
2792 root_view
2793 .downcast::<V>()
2794 .map_err(|_| anyhow!("the type of the window's root view has changed"))
2795 }))
2796 }
2797
2798 pub fn update<C, R>(
2799 &self,
2800 cx: &mut C,
2801 update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2802 ) -> Result<R>
2803 where
2804 C: Context,
2805 {
2806 cx.update_window(self.any_handle, |root_view, cx| {
2807 let view = root_view
2808 .downcast::<V>()
2809 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2810 Ok(cx.update_view(&view, update))
2811 })?
2812 }
2813
2814 pub fn read<'a>(&self, cx: &'a AppContext) -> Result<&'a V> {
2815 let x = cx
2816 .windows
2817 .get(self.id)
2818 .and_then(|window| {
2819 window
2820 .as_ref()
2821 .and_then(|window| window.root_view.clone())
2822 .map(|root_view| root_view.downcast::<V>())
2823 })
2824 .ok_or_else(|| anyhow!("window not found"))?
2825 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2826
2827 Ok(x.read(cx))
2828 }
2829
2830 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &AppContext) -> R) -> Result<R>
2831 where
2832 C: Context,
2833 {
2834 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
2835 }
2836
2837 pub fn root_view<C>(&self, cx: &C) -> Result<View<V>>
2838 where
2839 C: Context,
2840 {
2841 cx.read_window(self, |root_view, _cx| root_view.clone())
2842 }
2843
2844 pub fn is_active(&self, cx: &AppContext) -> Option<bool> {
2845 cx.windows
2846 .get(self.id)
2847 .and_then(|window| window.as_ref().map(|window| window.active))
2848 }
2849}
2850
2851impl<V> Copy for WindowHandle<V> {}
2852
2853impl<V> Clone for WindowHandle<V> {
2854 fn clone(&self) -> Self {
2855 WindowHandle {
2856 any_handle: self.any_handle,
2857 state_type: PhantomData,
2858 }
2859 }
2860}
2861
2862impl<V> PartialEq for WindowHandle<V> {
2863 fn eq(&self, other: &Self) -> bool {
2864 self.any_handle == other.any_handle
2865 }
2866}
2867
2868impl<V> Eq for WindowHandle<V> {}
2869
2870impl<V> Hash for WindowHandle<V> {
2871 fn hash<H: Hasher>(&self, state: &mut H) {
2872 self.any_handle.hash(state);
2873 }
2874}
2875
2876impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2877 fn into(self) -> AnyWindowHandle {
2878 self.any_handle
2879 }
2880}
2881
2882#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2883pub struct AnyWindowHandle {
2884 pub(crate) id: WindowId,
2885 state_type: TypeId,
2886}
2887
2888impl AnyWindowHandle {
2889 pub fn window_id(&self) -> WindowId {
2890 self.id
2891 }
2892
2893 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2894 if TypeId::of::<T>() == self.state_type {
2895 Some(WindowHandle {
2896 any_handle: *self,
2897 state_type: PhantomData,
2898 })
2899 } else {
2900 None
2901 }
2902 }
2903
2904 pub fn update<C, R>(
2905 self,
2906 cx: &mut C,
2907 update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2908 ) -> Result<R>
2909 where
2910 C: Context,
2911 {
2912 cx.update_window(self, update)
2913 }
2914
2915 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(View<T>, &AppContext) -> R) -> Result<R>
2916 where
2917 C: Context,
2918 T: 'static,
2919 {
2920 let view = self
2921 .downcast::<T>()
2922 .context("the type of the window's root view has changed")?;
2923
2924 cx.read_window(&view, read)
2925 }
2926}
2927
2928// #[cfg(any(test, feature = "test-support"))]
2929// impl From<SmallVec<[u32; 16]>> for StackingOrder {
2930// fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2931// StackingOrder(small_vec)
2932// }
2933// }
2934
2935#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2936pub enum ElementId {
2937 View(EntityId),
2938 Integer(usize),
2939 Name(SharedString),
2940 FocusHandle(FocusId),
2941 NamedInteger(SharedString, usize),
2942}
2943
2944impl ElementId {
2945 pub(crate) fn from_entity_id(entity_id: EntityId) -> Self {
2946 ElementId::View(entity_id)
2947 }
2948}
2949
2950impl TryInto<SharedString> for ElementId {
2951 type Error = anyhow::Error;
2952
2953 fn try_into(self) -> anyhow::Result<SharedString> {
2954 if let ElementId::Name(name) = self {
2955 Ok(name)
2956 } else {
2957 Err(anyhow!("element id is not string"))
2958 }
2959 }
2960}
2961
2962impl From<usize> for ElementId {
2963 fn from(id: usize) -> Self {
2964 ElementId::Integer(id)
2965 }
2966}
2967
2968impl From<i32> for ElementId {
2969 fn from(id: i32) -> Self {
2970 Self::Integer(id as usize)
2971 }
2972}
2973
2974impl From<SharedString> for ElementId {
2975 fn from(name: SharedString) -> Self {
2976 ElementId::Name(name)
2977 }
2978}
2979
2980impl From<&'static str> for ElementId {
2981 fn from(name: &'static str) -> Self {
2982 ElementId::Name(name.into())
2983 }
2984}
2985
2986impl<'a> From<&'a FocusHandle> for ElementId {
2987 fn from(handle: &'a FocusHandle) -> Self {
2988 ElementId::FocusHandle(handle.id)
2989 }
2990}
2991
2992impl From<(&'static str, EntityId)> for ElementId {
2993 fn from((name, id): (&'static str, EntityId)) -> Self {
2994 ElementId::NamedInteger(name.into(), id.as_u64() as usize)
2995 }
2996}
2997
2998impl From<(&'static str, usize)> for ElementId {
2999 fn from((name, id): (&'static str, usize)) -> Self {
3000 ElementId::NamedInteger(name.into(), id)
3001 }
3002}
3003
3004impl From<(&'static str, u64)> for ElementId {
3005 fn from((name, id): (&'static str, u64)) -> Self {
3006 ElementId::NamedInteger(name.into(), id as usize)
3007 }
3008}
3009
3010/// A rectangle, to be rendered on the screen by GPUI at the given position and size.
3011pub struct PaintQuad {
3012 bounds: Bounds<Pixels>,
3013 corner_radii: Corners<Pixels>,
3014 background: Hsla,
3015 border_widths: Edges<Pixels>,
3016 border_color: Hsla,
3017}
3018
3019impl PaintQuad {
3020 /// Set the corner radii of the quad.
3021 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
3022 PaintQuad {
3023 corner_radii: corner_radii.into(),
3024 ..self
3025 }
3026 }
3027
3028 /// Set the border widths of the quad.
3029 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
3030 PaintQuad {
3031 border_widths: border_widths.into(),
3032 ..self
3033 }
3034 }
3035
3036 /// Set the border color of the quad.
3037 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
3038 PaintQuad {
3039 border_color: border_color.into(),
3040 ..self
3041 }
3042 }
3043
3044 /// Set the background color of the quad.
3045 pub fn background(self, background: impl Into<Hsla>) -> Self {
3046 PaintQuad {
3047 background: background.into(),
3048 ..self
3049 }
3050 }
3051}
3052
3053/// Create a quad with the given parameters.
3054pub fn quad(
3055 bounds: Bounds<Pixels>,
3056 corner_radii: impl Into<Corners<Pixels>>,
3057 background: impl Into<Hsla>,
3058 border_widths: impl Into<Edges<Pixels>>,
3059 border_color: impl Into<Hsla>,
3060) -> PaintQuad {
3061 PaintQuad {
3062 bounds,
3063 corner_radii: corner_radii.into(),
3064 background: background.into(),
3065 border_widths: border_widths.into(),
3066 border_color: border_color.into(),
3067 }
3068}
3069
3070/// Create a filled quad with the given bounds and background color.
3071pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Hsla>) -> PaintQuad {
3072 PaintQuad {
3073 bounds: bounds.into(),
3074 corner_radii: (0.).into(),
3075 background: background.into(),
3076 border_widths: (0.).into(),
3077 border_color: transparent_black(),
3078 }
3079}
3080
3081/// Create a rectangle outline with the given bounds, border color, and a 1px border width
3082pub fn outline(bounds: impl Into<Bounds<Pixels>>, border_color: impl Into<Hsla>) -> PaintQuad {
3083 PaintQuad {
3084 bounds: bounds.into(),
3085 corner_radii: (0.).into(),
3086 background: transparent_black(),
3087 border_widths: (1.).into(),
3088 border_color: border_color.into(),
3089 }
3090}