1use crate::{
2 px, size, Action, AnyBox, AnyDrag, AnyView, AppContext, AsyncWindowContext, AvailableSpace,
3 Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,
4 Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,
5 Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,
6 MainThread, MainThreadOnly, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton,
7 MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow,
8 Point, PolychromeSprite, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams,
9 ScaledPixels, SceneBuilder, Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine,
10 Task, Underline, UnderlineStyle, View, VisualContext, WeakView, WindowOptions,
11 SUBPIXEL_VARIANTS,
12};
13use anyhow::{anyhow, Result};
14use collections::HashMap;
15use derive_more::{Deref, DerefMut};
16use parking_lot::RwLock;
17use slotmap::SlotMap;
18use smallvec::SmallVec;
19use std::{
20 any::{Any, TypeId},
21 borrow::{Borrow, BorrowMut, Cow},
22 fmt::Debug,
23 future::Future,
24 hash::{Hash, Hasher},
25 marker::PhantomData,
26 mem,
27 sync::{
28 atomic::{AtomicUsize, Ordering::SeqCst},
29 Arc,
30 },
31};
32use util::ResultExt;
33
34/// A global stacking order, which is created by stacking successive z-index values.
35/// Each z-index will always be interpreted in the context of its parent z-index.
36#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
37pub(crate) struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
38
39/// Represents the two different phases when dispatching events.
40#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
41pub enum DispatchPhase {
42 /// After the capture phase comes the bubble phase, in which mouse event listeners are
43 /// invoked front to back and keyboard event listeners are invoked from the focused element
44 /// to the root of the element tree. This is the phase you'll most commonly want to use when
45 /// registering event listeners.
46 #[default]
47 Bubble,
48 /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
49 /// listeners are invoked from the root of the tree downward toward the focused element. This phase
50 /// is used for special purposes such as clearing the "pressed" state for click events. If
51 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
52 /// outside of the immediate region may rely on detecting non-local events during this phase.
53 Capture,
54}
55
56type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + 'static>;
57type AnyKeyListener = Box<
58 dyn Fn(
59 &dyn Any,
60 &[&DispatchContext],
61 DispatchPhase,
62 &mut WindowContext,
63 ) -> Option<Box<dyn Action>>
64 + Send
65 + 'static,
66>;
67type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + Send + 'static>;
68
69slotmap::new_key_type! { pub struct FocusId; }
70
71/// A handle which can be used to track and manipulate the focused element in a window.
72pub struct FocusHandle {
73 pub(crate) id: FocusId,
74 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
75}
76
77impl FocusHandle {
78 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
79 let id = handles.write().insert(AtomicUsize::new(1));
80 Self {
81 id,
82 handles: handles.clone(),
83 }
84 }
85
86 pub(crate) fn for_id(
87 id: FocusId,
88 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
89 ) -> Option<Self> {
90 let lock = handles.read();
91 let ref_count = lock.get(id)?;
92 if ref_count.load(SeqCst) == 0 {
93 None
94 } else {
95 ref_count.fetch_add(1, SeqCst);
96 Some(Self {
97 id,
98 handles: handles.clone(),
99 })
100 }
101 }
102
103 /// Obtains whether the element associated with this handle is currently focused.
104 pub fn is_focused(&self, cx: &WindowContext) -> bool {
105 cx.window.focus == Some(self.id)
106 }
107
108 /// Obtains whether the element associated with this handle contains the focused
109 /// element or is itself focused.
110 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
111 cx.focused()
112 .map_or(false, |focused| self.contains(&focused, cx))
113 }
114
115 /// Obtains whether the element associated with this handle is contained within the
116 /// focused element or is itself focused.
117 pub fn within_focused(&self, cx: &WindowContext) -> bool {
118 let focused = cx.focused();
119 focused.map_or(false, |focused| focused.contains(self, cx))
120 }
121
122 /// Obtains whether this handle contains the given handle in the most recently rendered frame.
123 pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
124 let mut ancestor = Some(other.id);
125 while let Some(ancestor_id) = ancestor {
126 if self.id == ancestor_id {
127 return true;
128 } else {
129 ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
130 }
131 }
132 false
133 }
134}
135
136impl Clone for FocusHandle {
137 fn clone(&self) -> Self {
138 Self::for_id(self.id, &self.handles).unwrap()
139 }
140}
141
142impl PartialEq for FocusHandle {
143 fn eq(&self, other: &Self) -> bool {
144 self.id == other.id
145 }
146}
147
148impl Eq for FocusHandle {}
149
150impl Drop for FocusHandle {
151 fn drop(&mut self) {
152 self.handles
153 .read()
154 .get(self.id)
155 .unwrap()
156 .fetch_sub(1, SeqCst);
157 }
158}
159
160// Holds the state for a specific window.
161pub struct Window {
162 pub(crate) handle: AnyWindowHandle,
163 platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
164 display_id: DisplayId,
165 sprite_atlas: Arc<dyn PlatformAtlas>,
166 rem_size: Pixels,
167 content_size: Size<Pixels>,
168 pub(crate) layout_engine: TaffyLayoutEngine,
169 pub(crate) root_view: Option<AnyView>,
170 pub(crate) element_id_stack: GlobalElementId,
171 prev_frame_element_states: HashMap<GlobalElementId, AnyBox>,
172 element_states: HashMap<GlobalElementId, AnyBox>,
173 prev_frame_key_matchers: HashMap<GlobalElementId, KeyMatcher>,
174 key_matchers: HashMap<GlobalElementId, KeyMatcher>,
175 z_index_stack: StackingOrder,
176 content_mask_stack: Vec<ContentMask<Pixels>>,
177 element_offset_stack: Vec<Point<Pixels>>,
178 mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
179 key_dispatch_stack: Vec<KeyDispatchStackFrame>,
180 freeze_key_dispatch_stack: bool,
181 focus_stack: Vec<FocusId>,
182 focus_parents_by_child: HashMap<FocusId, FocusId>,
183 pub(crate) focus_listeners: Vec<AnyFocusListener>,
184 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
185 default_prevented: bool,
186 mouse_position: Point<Pixels>,
187 scale_factor: f32,
188 pub(crate) scene_builder: SceneBuilder,
189 pub(crate) dirty: bool,
190 pub(crate) last_blur: Option<Option<FocusId>>,
191 pub(crate) focus: Option<FocusId>,
192}
193
194impl Window {
195 pub(crate) fn new(
196 handle: AnyWindowHandle,
197 options: WindowOptions,
198 cx: &mut MainThread<AppContext>,
199 ) -> Self {
200 let platform_window = cx.platform().open_window(handle, options);
201 let display_id = platform_window.display().id();
202 let sprite_atlas = platform_window.sprite_atlas();
203 let mouse_position = platform_window.mouse_position();
204 let content_size = platform_window.content_size();
205 let scale_factor = platform_window.scale_factor();
206 platform_window.on_resize(Box::new({
207 let mut cx = cx.to_async();
208 move |content_size, scale_factor| {
209 cx.update_window(handle, |_, cx| {
210 cx.window.scale_factor = scale_factor;
211 cx.window.scene_builder = SceneBuilder::new();
212 cx.window.content_size = content_size;
213 cx.window.display_id = cx
214 .window
215 .platform_window
216 .borrow_on_main_thread()
217 .display()
218 .id();
219 cx.window.dirty = true;
220 })
221 .log_err();
222 }
223 }));
224
225 platform_window.on_input({
226 let mut cx = cx.to_async();
227 Box::new(move |event| {
228 cx.update_window(handle, |_, cx| cx.dispatch_event(event))
229 .log_err()
230 .unwrap_or(true)
231 })
232 });
233
234 let platform_window = MainThreadOnly::new(Arc::new(platform_window), cx.executor.clone());
235
236 Window {
237 handle,
238 platform_window,
239 display_id,
240 sprite_atlas,
241 rem_size: px(16.),
242 content_size,
243 layout_engine: TaffyLayoutEngine::new(),
244 root_view: None,
245 element_id_stack: GlobalElementId::default(),
246 prev_frame_element_states: HashMap::default(),
247 element_states: HashMap::default(),
248 prev_frame_key_matchers: HashMap::default(),
249 key_matchers: HashMap::default(),
250 z_index_stack: StackingOrder(SmallVec::new()),
251 content_mask_stack: Vec::new(),
252 element_offset_stack: Vec::new(),
253 mouse_listeners: HashMap::default(),
254 key_dispatch_stack: Vec::new(),
255 freeze_key_dispatch_stack: false,
256 focus_stack: Vec::new(),
257 focus_parents_by_child: HashMap::default(),
258 focus_listeners: Vec::new(),
259 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
260 default_prevented: true,
261 mouse_position,
262 scale_factor,
263 scene_builder: SceneBuilder::new(),
264 dirty: true,
265 last_blur: None,
266 focus: None,
267 }
268 }
269}
270
271/// When constructing the element tree, we maintain a stack of key dispatch frames until we
272/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
273/// contexts when matching key events against the keymap.
274enum KeyDispatchStackFrame {
275 Listener {
276 event_type: TypeId,
277 listener: AnyKeyListener,
278 },
279 Context(DispatchContext),
280}
281
282/// Indicates which region of the window is visible. Content falling outside of this mask will not be
283/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
284/// to leave room to support more complex shapes in the future.
285#[derive(Clone, Debug, Default, PartialEq, Eq)]
286#[repr(C)]
287pub struct ContentMask<P: Clone + Default + Debug> {
288 pub bounds: Bounds<P>,
289}
290
291impl ContentMask<Pixels> {
292 /// Scale the content mask's pixel units by the given scaling factor.
293 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
294 ContentMask {
295 bounds: self.bounds.scale(factor),
296 }
297 }
298
299 /// Intersect the content mask with the given content mask.
300 pub fn intersect(&self, other: &Self) -> Self {
301 let bounds = self.bounds.intersect(&other.bounds);
302 ContentMask { bounds }
303 }
304}
305
306/// Provides access to application state in the context of a single window. Derefs
307/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
308/// an `AppContext` and call any `AppContext` methods.
309pub struct WindowContext<'a> {
310 pub(crate) app: &'a mut AppContext,
311 pub(crate) window: &'a mut Window,
312}
313
314impl<'a> WindowContext<'a> {
315 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
316 Self { app, window }
317 }
318
319 /// Obtain a handle to the window that belongs to this context.
320 pub fn window_handle(&self) -> AnyWindowHandle {
321 self.window.handle
322 }
323
324 /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
325 pub fn notify(&mut self) {
326 self.window.dirty = true;
327 }
328
329 /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
330 /// for elements rendered within this window.
331 pub fn focus_handle(&mut self) -> FocusHandle {
332 FocusHandle::new(&self.window.focus_handles)
333 }
334
335 /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
336 pub fn focused(&self) -> Option<FocusHandle> {
337 self.window
338 .focus
339 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
340 }
341
342 /// Move focus to the element associated with the given `FocusHandle`.
343 pub fn focus(&mut self, handle: &FocusHandle) {
344 if self.window.last_blur.is_none() {
345 self.window.last_blur = Some(self.window.focus);
346 }
347
348 self.window.focus = Some(handle.id);
349 self.app.push_effect(Effect::FocusChanged {
350 window_handle: self.window.handle,
351 focused: Some(handle.id),
352 });
353 self.notify();
354 }
355
356 /// Remove focus from all elements within this context's window.
357 pub fn blur(&mut self) {
358 if self.window.last_blur.is_none() {
359 self.window.last_blur = Some(self.window.focus);
360 }
361
362 self.window.focus = None;
363 self.app.push_effect(Effect::FocusChanged {
364 window_handle: self.window.handle,
365 focused: None,
366 });
367 self.notify();
368 }
369
370 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
371 /// that are currently on the stack to be returned to the app.
372 pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static + Send) {
373 let window = self.window.handle;
374 self.app.defer(move |cx| {
375 cx.update_window(window, |_, cx| f(cx)).ok();
376 });
377 }
378
379 pub fn subscribe<Emitter, E>(
380 &mut self,
381 entity: &E,
382 mut on_event: impl FnMut(E, &Emitter::Event, &mut WindowContext<'_>) + Send + 'static,
383 ) -> Subscription
384 where
385 Emitter: EventEmitter,
386 E: Entity<Emitter>,
387 {
388 let entity_id = entity.entity_id();
389 let entity = entity.downgrade();
390 let window_handle = self.window.handle;
391 self.app.event_listeners.insert(
392 entity_id,
393 Box::new(move |event, cx| {
394 cx.update_window(window_handle, |_, cx| {
395 if let Some(handle) = E::upgrade_from(&entity) {
396 let event = event.downcast_ref().expect("invalid event type");
397 on_event(handle, event, cx);
398 true
399 } else {
400 false
401 }
402 })
403 .unwrap_or(false)
404 }),
405 )
406 }
407
408 /// Schedule the given closure to be run on the main thread. It will be invoked with
409 /// a `MainThread<WindowContext>`, which provides access to platform-specific functionality
410 /// of the window.
411 pub fn run_on_main<R>(
412 &mut self,
413 f: impl FnOnce(&mut MainThread<WindowContext<'_>>) -> R + Send + 'static,
414 ) -> Task<Result<R>>
415 where
416 R: Send + 'static,
417 {
418 if self.executor.is_main_thread() {
419 Task::ready(Ok(f(unsafe {
420 mem::transmute::<&mut Self, &mut MainThread<Self>>(self)
421 })))
422 } else {
423 let handle = self.window.handle;
424 self.app
425 .run_on_main(move |cx| cx.update_window(handle, |_, cx| f(cx)))
426 }
427 }
428
429 /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
430 /// await points in async code.
431 pub fn to_async(&self) -> AsyncWindowContext {
432 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
433 }
434
435 /// Schedule the given closure to be run directly after the current frame is rendered.
436 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
437 let f = Box::new(f);
438 let display_id = self.window.display_id;
439 self.run_on_main(move |cx| {
440 if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {
441 callbacks.push(f);
442 // If there was already a callback, it means that we already scheduled a frame.
443 if callbacks.len() > 1 {
444 return;
445 }
446 } else {
447 let mut async_cx = cx.to_async();
448 cx.next_frame_callbacks.insert(display_id, vec![f]);
449 cx.platform().set_display_link_output_callback(
450 display_id,
451 Box::new(move |_current_time, _output_time| {
452 let _ = async_cx.update(|_, cx| {
453 let callbacks = cx
454 .next_frame_callbacks
455 .get_mut(&display_id)
456 .unwrap()
457 .drain(..)
458 .collect::<Vec<_>>();
459 for callback in callbacks {
460 callback(cx);
461 }
462
463 cx.run_on_main(move |cx| {
464 if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
465 cx.platform().stop_display_link(display_id);
466 }
467 })
468 .detach();
469 });
470 }),
471 );
472 }
473
474 cx.platform().start_display_link(display_id);
475 })
476 .detach();
477 }
478
479 /// Spawn the future returned by the given closure on the application thread pool.
480 /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
481 /// use within your future.
482 pub fn spawn<Fut, R>(
483 &mut self,
484 f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut + Send + 'static,
485 ) -> Task<R>
486 where
487 R: Send + 'static,
488 Fut: Future<Output = R> + Send + 'static,
489 {
490 let window = self.window.handle;
491 self.app.spawn(move |app| {
492 let cx = AsyncWindowContext::new(app, window);
493 let future = f(window, cx);
494 async move { future.await }
495 })
496 }
497
498 /// Update the global of the given type. The given closure is given simultaneous mutable
499 /// access both to the global and the context.
500 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
501 where
502 G: 'static,
503 {
504 let mut global = self.app.lease_global::<G>();
505 let result = f(&mut global, self);
506 self.app.end_global_lease(global);
507 result
508 }
509
510 /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
511 /// layout is being requested, along with the layout ids of any children. This method is called during
512 /// calls to the `Element::layout` trait method and enables any element to participate in layout.
513 pub fn request_layout(
514 &mut self,
515 style: &Style,
516 children: impl IntoIterator<Item = LayoutId>,
517 ) -> LayoutId {
518 self.app.layout_id_buffer.clear();
519 self.app.layout_id_buffer.extend(children.into_iter());
520 let rem_size = self.rem_size();
521
522 self.window
523 .layout_engine
524 .request_layout(style, rem_size, &self.app.layout_id_buffer)
525 }
526
527 /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
528 /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
529 /// determine the element's size. One place this is used internally is when measuring text.
530 ///
531 /// The given closure is invoked at layout time with the known dimensions and available space and
532 /// returns a `Size`.
533 pub fn request_measured_layout<
534 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
535 >(
536 &mut self,
537 style: Style,
538 rem_size: Pixels,
539 measure: F,
540 ) -> LayoutId {
541 self.window
542 .layout_engine
543 .request_measured_layout(style, rem_size, measure)
544 }
545
546 /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
547 /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
548 /// in order to pass your element its `Bounds` automatically.
549 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
550 let mut bounds = self
551 .window
552 .layout_engine
553 .layout_bounds(layout_id)
554 .map(Into::into);
555 bounds.origin += self.element_offset();
556 bounds
557 }
558
559 /// The scale factor of the display associated with the window. For example, it could
560 /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
561 /// be rendered as two pixels on screen.
562 pub fn scale_factor(&self) -> f32 {
563 self.window.scale_factor
564 }
565
566 /// The size of an em for the base font of the application. Adjusting this value allows the
567 /// UI to scale, just like zooming a web page.
568 pub fn rem_size(&self) -> Pixels {
569 self.window.rem_size
570 }
571
572 /// The line height associated with the current text style.
573 pub fn line_height(&self) -> Pixels {
574 let rem_size = self.rem_size();
575 let text_style = self.text_style();
576 text_style
577 .line_height
578 .to_pixels(text_style.font_size.into(), rem_size)
579 }
580
581 /// Call to prevent the default action of an event. Currently only used to prevent
582 /// parent elements from becoming focused on mouse down.
583 pub fn prevent_default(&mut self) {
584 self.window.default_prevented = true;
585 }
586
587 /// Obtain whether default has been prevented for the event currently being dispatched.
588 pub fn default_prevented(&self) -> bool {
589 self.window.default_prevented
590 }
591
592 /// Register a mouse event listener on the window for the current frame. The type of event
593 /// is determined by the first parameter of the given listener. When the next frame is rendered
594 /// the listener will be cleared.
595 ///
596 /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
597 /// a specific need to register a global listener.
598 pub fn on_mouse_event<Event: 'static>(
599 &mut self,
600 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + 'static,
601 ) {
602 let order = self.window.z_index_stack.clone();
603 self.window
604 .mouse_listeners
605 .entry(TypeId::of::<Event>())
606 .or_default()
607 .push((
608 order,
609 Box::new(move |event: &dyn Any, phase, cx| {
610 handler(event.downcast_ref().unwrap(), phase, cx)
611 }),
612 ))
613 }
614
615 /// The position of the mouse relative to the window.
616 pub fn mouse_position(&self) -> Point<Pixels> {
617 self.window.mouse_position
618 }
619
620 /// Called during painting to invoke the given closure in a new stacking context. The given
621 /// z-index is interpreted relative to the previous call to `stack`.
622 pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
623 self.window.z_index_stack.push(z_index);
624 let result = f(self);
625 self.window.z_index_stack.pop();
626 result
627 }
628
629 /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
630 pub fn paint_shadows(
631 &mut self,
632 bounds: Bounds<Pixels>,
633 corner_radii: Corners<Pixels>,
634 shadows: &[BoxShadow],
635 ) {
636 let scale_factor = self.scale_factor();
637 let content_mask = self.content_mask();
638 let window = &mut *self.window;
639 for shadow in shadows {
640 let mut shadow_bounds = bounds;
641 shadow_bounds.origin += shadow.offset;
642 shadow_bounds.dilate(shadow.spread_radius);
643 window.scene_builder.insert(
644 &window.z_index_stack,
645 Shadow {
646 order: 0,
647 bounds: shadow_bounds.scale(scale_factor),
648 content_mask: content_mask.scale(scale_factor),
649 corner_radii: corner_radii.scale(scale_factor),
650 color: shadow.color,
651 blur_radius: shadow.blur_radius.scale(scale_factor),
652 },
653 );
654 }
655 }
656
657 /// Paint one or more quads into the scene for the current frame at the current stacking context.
658 /// Quads are colored rectangular regions with an optional background, border, and corner radius.
659 pub fn paint_quad(
660 &mut self,
661 bounds: Bounds<Pixels>,
662 corner_radii: Corners<Pixels>,
663 background: impl Into<Hsla>,
664 border_widths: Edges<Pixels>,
665 border_color: impl Into<Hsla>,
666 ) {
667 let scale_factor = self.scale_factor();
668 let content_mask = self.content_mask();
669
670 let window = &mut *self.window;
671 window.scene_builder.insert(
672 &window.z_index_stack,
673 Quad {
674 order: 0,
675 bounds: bounds.scale(scale_factor),
676 content_mask: content_mask.scale(scale_factor),
677 background: background.into(),
678 border_color: border_color.into(),
679 corner_radii: corner_radii.scale(scale_factor),
680 border_widths: border_widths.scale(scale_factor),
681 },
682 );
683 }
684
685 /// Paint the given `Path` into the scene for the current frame at the current z-index.
686 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
687 let scale_factor = self.scale_factor();
688 let content_mask = self.content_mask();
689 path.content_mask = content_mask;
690 path.color = color.into();
691 let window = &mut *self.window;
692 window
693 .scene_builder
694 .insert(&window.z_index_stack, path.scale(scale_factor));
695 }
696
697 /// Paint an underline into the scene for the current frame at the current z-index.
698 pub fn paint_underline(
699 &mut self,
700 origin: Point<Pixels>,
701 width: Pixels,
702 style: &UnderlineStyle,
703 ) -> Result<()> {
704 let scale_factor = self.scale_factor();
705 let height = if style.wavy {
706 style.thickness * 3.
707 } else {
708 style.thickness
709 };
710 let bounds = Bounds {
711 origin,
712 size: size(width, height),
713 };
714 let content_mask = self.content_mask();
715 let window = &mut *self.window;
716 window.scene_builder.insert(
717 &window.z_index_stack,
718 Underline {
719 order: 0,
720 bounds: bounds.scale(scale_factor),
721 content_mask: content_mask.scale(scale_factor),
722 thickness: style.thickness.scale(scale_factor),
723 color: style.color.unwrap_or_default(),
724 wavy: style.wavy,
725 },
726 );
727 Ok(())
728 }
729
730 /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
731 pub fn paint_glyph(
732 &mut self,
733 origin: Point<Pixels>,
734 font_id: FontId,
735 glyph_id: GlyphId,
736 font_size: Pixels,
737 color: Hsla,
738 ) -> Result<()> {
739 let scale_factor = self.scale_factor();
740 let glyph_origin = origin.scale(scale_factor);
741 let subpixel_variant = Point {
742 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
743 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
744 };
745 let params = RenderGlyphParams {
746 font_id,
747 glyph_id,
748 font_size,
749 subpixel_variant,
750 scale_factor,
751 is_emoji: false,
752 };
753
754 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
755 if !raster_bounds.is_zero() {
756 let tile =
757 self.window
758 .sprite_atlas
759 .get_or_insert_with(¶ms.clone().into(), &mut || {
760 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
761 Ok((size, Cow::Owned(bytes)))
762 })?;
763 let bounds = Bounds {
764 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
765 size: tile.bounds.size.map(Into::into),
766 };
767 let content_mask = self.content_mask().scale(scale_factor);
768 let window = &mut *self.window;
769 window.scene_builder.insert(
770 &window.z_index_stack,
771 MonochromeSprite {
772 order: 0,
773 bounds,
774 content_mask,
775 color,
776 tile,
777 },
778 );
779 }
780 Ok(())
781 }
782
783 /// Paint an emoji glyph into the scene for the current frame at the current z-index.
784 pub fn paint_emoji(
785 &mut self,
786 origin: Point<Pixels>,
787 font_id: FontId,
788 glyph_id: GlyphId,
789 font_size: Pixels,
790 ) -> Result<()> {
791 let scale_factor = self.scale_factor();
792 let glyph_origin = origin.scale(scale_factor);
793 let params = RenderGlyphParams {
794 font_id,
795 glyph_id,
796 font_size,
797 // We don't render emojis with subpixel variants.
798 subpixel_variant: Default::default(),
799 scale_factor,
800 is_emoji: true,
801 };
802
803 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
804 if !raster_bounds.is_zero() {
805 let tile =
806 self.window
807 .sprite_atlas
808 .get_or_insert_with(¶ms.clone().into(), &mut || {
809 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
810 Ok((size, Cow::Owned(bytes)))
811 })?;
812 let bounds = Bounds {
813 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
814 size: tile.bounds.size.map(Into::into),
815 };
816 let content_mask = self.content_mask().scale(scale_factor);
817 let window = &mut *self.window;
818
819 window.scene_builder.insert(
820 &window.z_index_stack,
821 PolychromeSprite {
822 order: 0,
823 bounds,
824 corner_radii: Default::default(),
825 content_mask,
826 tile,
827 grayscale: false,
828 },
829 );
830 }
831 Ok(())
832 }
833
834 /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
835 pub fn paint_svg(
836 &mut self,
837 bounds: Bounds<Pixels>,
838 path: SharedString,
839 color: Hsla,
840 ) -> Result<()> {
841 let scale_factor = self.scale_factor();
842 let bounds = bounds.scale(scale_factor);
843 // Render the SVG at twice the size to get a higher quality result.
844 let params = RenderSvgParams {
845 path,
846 size: bounds
847 .size
848 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
849 };
850
851 let tile =
852 self.window
853 .sprite_atlas
854 .get_or_insert_with(¶ms.clone().into(), &mut || {
855 let bytes = self.svg_renderer.render(¶ms)?;
856 Ok((params.size, Cow::Owned(bytes)))
857 })?;
858 let content_mask = self.content_mask().scale(scale_factor);
859
860 let window = &mut *self.window;
861 window.scene_builder.insert(
862 &window.z_index_stack,
863 MonochromeSprite {
864 order: 0,
865 bounds,
866 content_mask,
867 color,
868 tile,
869 },
870 );
871
872 Ok(())
873 }
874
875 /// Paint an image into the scene for the current frame at the current z-index.
876 pub fn paint_image(
877 &mut self,
878 bounds: Bounds<Pixels>,
879 corner_radii: Corners<Pixels>,
880 data: Arc<ImageData>,
881 grayscale: bool,
882 ) -> Result<()> {
883 let scale_factor = self.scale_factor();
884 let bounds = bounds.scale(scale_factor);
885 let params = RenderImageParams { image_id: data.id };
886
887 let tile = self
888 .window
889 .sprite_atlas
890 .get_or_insert_with(¶ms.clone().into(), &mut || {
891 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
892 })?;
893 let content_mask = self.content_mask().scale(scale_factor);
894 let corner_radii = corner_radii.scale(scale_factor);
895
896 let window = &mut *self.window;
897 window.scene_builder.insert(
898 &window.z_index_stack,
899 PolychromeSprite {
900 order: 0,
901 bounds,
902 content_mask,
903 corner_radii,
904 tile,
905 grayscale,
906 },
907 );
908 Ok(())
909 }
910
911 /// Draw pixels to the display for this window based on the contents of its scene.
912 pub(crate) fn draw(&mut self) {
913 let root_view = self.window.root_view.take().unwrap();
914
915 self.start_frame();
916
917 self.stack(0, |cx| {
918 let available_space = cx.window.content_size.map(Into::into);
919 root_view.draw(available_space, cx);
920 });
921
922 if let Some(active_drag) = self.app.active_drag.take() {
923 self.stack(1, |cx| {
924 let offset = cx.mouse_position() - active_drag.cursor_offset;
925 cx.with_element_offset(Some(offset), |cx| {
926 let available_space =
927 size(AvailableSpace::MinContent, AvailableSpace::MinContent);
928 active_drag.view.draw(available_space, cx);
929 cx.active_drag = Some(active_drag);
930 });
931 });
932 }
933
934 self.window.root_view = Some(root_view);
935 let scene = self.window.scene_builder.build();
936
937 self.run_on_main(|cx| {
938 cx.window
939 .platform_window
940 .borrow_on_main_thread()
941 .draw(scene);
942 cx.window.dirty = false;
943 })
944 .detach();
945 }
946
947 fn start_frame(&mut self) {
948 self.text_system().start_frame();
949
950 let window = &mut *self.window;
951
952 // Move the current frame element states to the previous frame.
953 // The new empty element states map will be populated for any element states we
954 // reference during the upcoming frame.
955 mem::swap(
956 &mut window.element_states,
957 &mut window.prev_frame_element_states,
958 );
959 window.element_states.clear();
960
961 // Make the current key matchers the previous, and then clear the current.
962 // An empty key matcher map will be created for every identified element in the
963 // upcoming frame.
964 mem::swap(
965 &mut window.key_matchers,
966 &mut window.prev_frame_key_matchers,
967 );
968 window.key_matchers.clear();
969
970 // Clear mouse event listeners, because elements add new element listeners
971 // when the upcoming frame is painted.
972 window.mouse_listeners.values_mut().for_each(Vec::clear);
973
974 // Clear focus state, because we determine what is focused when the new elements
975 // in the upcoming frame are initialized.
976 window.focus_listeners.clear();
977 window.key_dispatch_stack.clear();
978 window.focus_parents_by_child.clear();
979 window.freeze_key_dispatch_stack = false;
980 }
981
982 /// Dispatch a mouse or keyboard event on the window.
983 fn dispatch_event(&mut self, event: InputEvent) -> bool {
984 let event = match event {
985 // Track the mouse position with our own state, since accessing the platform
986 // API for the mouse position can only occur on the main thread.
987 InputEvent::MouseMove(mouse_move) => {
988 self.window.mouse_position = mouse_move.position;
989 InputEvent::MouseMove(mouse_move)
990 }
991 // Translate dragging and dropping of external files from the operating system
992 // to internal drag and drop events.
993 InputEvent::FileDrop(file_drop) => match file_drop {
994 FileDropEvent::Entered { position, files } => {
995 self.window.mouse_position = position;
996 if self.active_drag.is_none() {
997 self.active_drag = Some(AnyDrag {
998 view: self.build_view(|_| files).into(),
999 cursor_offset: position,
1000 });
1001 }
1002 InputEvent::MouseDown(MouseDownEvent {
1003 position,
1004 button: MouseButton::Left,
1005 click_count: 1,
1006 modifiers: Modifiers::default(),
1007 })
1008 }
1009 FileDropEvent::Pending { position } => {
1010 self.window.mouse_position = position;
1011 InputEvent::MouseMove(MouseMoveEvent {
1012 position,
1013 pressed_button: Some(MouseButton::Left),
1014 modifiers: Modifiers::default(),
1015 })
1016 }
1017 FileDropEvent::Submit { position } => {
1018 self.window.mouse_position = position;
1019 InputEvent::MouseUp(MouseUpEvent {
1020 button: MouseButton::Left,
1021 position,
1022 modifiers: Modifiers::default(),
1023 click_count: 1,
1024 })
1025 }
1026 FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1027 button: MouseButton::Left,
1028 position: Point::default(),
1029 modifiers: Modifiers::default(),
1030 click_count: 1,
1031 }),
1032 },
1033 _ => event,
1034 };
1035
1036 if let Some(any_mouse_event) = event.mouse_event() {
1037 // Handlers may set this to false by calling `stop_propagation`
1038 self.app.propagate_event = true;
1039 self.window.default_prevented = false;
1040
1041 if let Some(mut handlers) = self
1042 .window
1043 .mouse_listeners
1044 .remove(&any_mouse_event.type_id())
1045 {
1046 // Because handlers may add other handlers, we sort every time.
1047 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1048
1049 // Capture phase, events bubble from back to front. Handlers for this phase are used for
1050 // special purposes, such as detecting events outside of a given Bounds.
1051 for (_, handler) in &handlers {
1052 handler(any_mouse_event, DispatchPhase::Capture, self);
1053 if !self.app.propagate_event {
1054 break;
1055 }
1056 }
1057
1058 // Bubble phase, where most normal handlers do their work.
1059 if self.app.propagate_event {
1060 for (_, handler) in handlers.iter().rev() {
1061 handler(any_mouse_event, DispatchPhase::Bubble, self);
1062 if !self.app.propagate_event {
1063 break;
1064 }
1065 }
1066 }
1067
1068 if self.app.propagate_event
1069 && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1070 {
1071 self.active_drag = None;
1072 }
1073
1074 // Just in case any handlers added new handlers, which is weird, but possible.
1075 handlers.extend(
1076 self.window
1077 .mouse_listeners
1078 .get_mut(&any_mouse_event.type_id())
1079 .into_iter()
1080 .flat_map(|handlers| handlers.drain(..)),
1081 );
1082 self.window
1083 .mouse_listeners
1084 .insert(any_mouse_event.type_id(), handlers);
1085 }
1086 } else if let Some(any_key_event) = event.keyboard_event() {
1087 let key_dispatch_stack = mem::take(&mut self.window.key_dispatch_stack);
1088 let key_event_type = any_key_event.type_id();
1089 let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1090
1091 for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1092 match frame {
1093 KeyDispatchStackFrame::Listener {
1094 event_type,
1095 listener,
1096 } => {
1097 if key_event_type == *event_type {
1098 if let Some(action) = listener(
1099 any_key_event,
1100 &context_stack,
1101 DispatchPhase::Capture,
1102 self,
1103 ) {
1104 self.dispatch_action(action, &key_dispatch_stack[..ix]);
1105 }
1106 if !self.app.propagate_event {
1107 break;
1108 }
1109 }
1110 }
1111 KeyDispatchStackFrame::Context(context) => {
1112 context_stack.push(&context);
1113 }
1114 }
1115 }
1116
1117 if self.app.propagate_event {
1118 for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1119 match frame {
1120 KeyDispatchStackFrame::Listener {
1121 event_type,
1122 listener,
1123 } => {
1124 if key_event_type == *event_type {
1125 if let Some(action) = listener(
1126 any_key_event,
1127 &context_stack,
1128 DispatchPhase::Bubble,
1129 self,
1130 ) {
1131 self.dispatch_action(action, &key_dispatch_stack[..ix]);
1132 }
1133
1134 if !self.app.propagate_event {
1135 break;
1136 }
1137 }
1138 }
1139 KeyDispatchStackFrame::Context(_) => {
1140 context_stack.pop();
1141 }
1142 }
1143 }
1144 }
1145
1146 drop(context_stack);
1147 self.window.key_dispatch_stack = key_dispatch_stack;
1148 }
1149
1150 true
1151 }
1152
1153 /// Attempt to map a keystroke to an action based on the keymap.
1154 pub fn match_keystroke(
1155 &mut self,
1156 element_id: &GlobalElementId,
1157 keystroke: &Keystroke,
1158 context_stack: &[&DispatchContext],
1159 ) -> KeyMatch {
1160 let key_match = self
1161 .window
1162 .key_matchers
1163 .get_mut(element_id)
1164 .unwrap()
1165 .match_keystroke(keystroke, context_stack);
1166
1167 if key_match.is_some() {
1168 for matcher in self.window.key_matchers.values_mut() {
1169 matcher.clear_pending();
1170 }
1171 }
1172
1173 key_match
1174 }
1175
1176 /// Register the given handler to be invoked whenever the global of the given type
1177 /// is updated.
1178 pub fn observe_global<G: 'static>(
1179 &mut self,
1180 f: impl Fn(&mut WindowContext<'_>) + Send + 'static,
1181 ) -> Subscription {
1182 let window_handle = self.window.handle;
1183 self.global_observers.insert(
1184 TypeId::of::<G>(),
1185 Box::new(move |cx| cx.update_window(window_handle, |_, cx| f(cx)).is_ok()),
1186 )
1187 }
1188
1189 fn dispatch_action(
1190 &mut self,
1191 action: Box<dyn Action>,
1192 dispatch_stack: &[KeyDispatchStackFrame],
1193 ) {
1194 let action_type = action.as_any().type_id();
1195
1196 if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1197 for listener in &global_listeners {
1198 listener(action.as_ref(), DispatchPhase::Capture, self);
1199 if !self.app.propagate_event {
1200 break;
1201 }
1202 }
1203 global_listeners.extend(
1204 self.global_action_listeners
1205 .remove(&action_type)
1206 .unwrap_or_default(),
1207 );
1208 self.global_action_listeners
1209 .insert(action_type, global_listeners);
1210 }
1211
1212 if self.app.propagate_event {
1213 for stack_frame in dispatch_stack {
1214 if let KeyDispatchStackFrame::Listener {
1215 event_type,
1216 listener,
1217 } = stack_frame
1218 {
1219 if action_type == *event_type {
1220 listener(action.as_any(), &[], DispatchPhase::Capture, self);
1221 if !self.app.propagate_event {
1222 break;
1223 }
1224 }
1225 }
1226 }
1227 }
1228
1229 if self.app.propagate_event {
1230 for stack_frame in dispatch_stack.iter().rev() {
1231 if let KeyDispatchStackFrame::Listener {
1232 event_type,
1233 listener,
1234 } = stack_frame
1235 {
1236 if action_type == *event_type {
1237 listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1238 if !self.app.propagate_event {
1239 break;
1240 }
1241 }
1242 }
1243 }
1244 }
1245
1246 if self.app.propagate_event {
1247 if let Some(mut global_listeners) =
1248 self.app.global_action_listeners.remove(&action_type)
1249 {
1250 for listener in global_listeners.iter().rev() {
1251 listener(action.as_ref(), DispatchPhase::Bubble, self);
1252 if !self.app.propagate_event {
1253 break;
1254 }
1255 }
1256 global_listeners.extend(
1257 self.global_action_listeners
1258 .remove(&action_type)
1259 .unwrap_or_default(),
1260 );
1261 self.global_action_listeners
1262 .insert(action_type, global_listeners);
1263 }
1264 }
1265 }
1266}
1267
1268impl Context for WindowContext<'_> {
1269 type WindowContext<'a> = WindowContext<'a>;
1270 type ModelContext<'a, T> = ModelContext<'a, T>;
1271 type Result<T> = T;
1272
1273 fn build_model<T>(
1274 &mut self,
1275 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1276 ) -> Model<T>
1277 where
1278 T: 'static + Send,
1279 {
1280 let slot = self.app.entities.reserve();
1281 let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1282 self.entities.insert(slot, model)
1283 }
1284
1285 fn update_model<T: 'static, R>(
1286 &mut self,
1287 model: &Model<T>,
1288 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1289 ) -> R {
1290 let mut entity = self.entities.lease(model);
1291 let result = update(
1292 &mut *entity,
1293 &mut ModelContext::new(&mut *self.app, model.downgrade()),
1294 );
1295 self.entities.end_lease(entity);
1296 result
1297 }
1298
1299 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1300 where
1301 F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,
1302 {
1303 if window == self.window.handle {
1304 let root_view = self.window.root_view.clone().unwrap();
1305 Ok(update(root_view, self))
1306 } else {
1307 self.app.update_window(window, update)
1308 }
1309 }
1310}
1311
1312impl VisualContext for WindowContext<'_> {
1313 type ViewContext<'a, V: 'static> = ViewContext<'a, V>;
1314
1315 fn build_view<V>(
1316 &mut self,
1317 build_view_state: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,
1318 ) -> Self::Result<View<V>>
1319 where
1320 V: 'static + Send,
1321 {
1322 let slot = self.app.entities.reserve();
1323 let view = View {
1324 model: slot.clone(),
1325 };
1326 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1327 let entity = build_view_state(&mut cx);
1328 self.entities.insert(slot, entity);
1329 view
1330 }
1331
1332 /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1333 fn update_view<T: 'static, R>(
1334 &mut self,
1335 view: &View<T>,
1336 update: impl FnOnce(&mut T, &mut Self::ViewContext<'_, T>) -> R,
1337 ) -> Self::Result<R> {
1338 let mut lease = self.app.entities.lease(&view.model);
1339 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1340 let result = update(&mut *lease, &mut cx);
1341 cx.app.entities.end_lease(lease);
1342 result
1343 }
1344
1345 fn replace_root_view<V>(
1346 &mut self,
1347 build_view: impl FnOnce(&mut Self::ViewContext<'_, V>) -> V,
1348 ) -> Self::Result<View<V>>
1349 where
1350 V: 'static + Send + Render,
1351 {
1352 let slot = self.app.entities.reserve();
1353 let view = View {
1354 model: slot.clone(),
1355 };
1356 let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1357 let entity = build_view(&mut cx);
1358 self.entities.insert(slot, entity);
1359 self.window.root_view = Some(view.clone().into());
1360 view
1361 }
1362}
1363
1364impl<'a> std::ops::Deref for WindowContext<'a> {
1365 type Target = AppContext;
1366
1367 fn deref(&self) -> &Self::Target {
1368 &self.app
1369 }
1370}
1371
1372impl<'a> std::ops::DerefMut for WindowContext<'a> {
1373 fn deref_mut(&mut self) -> &mut Self::Target {
1374 &mut self.app
1375 }
1376}
1377
1378impl<'a> Borrow<AppContext> for WindowContext<'a> {
1379 fn borrow(&self) -> &AppContext {
1380 &self.app
1381 }
1382}
1383
1384impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1385 fn borrow_mut(&mut self) -> &mut AppContext {
1386 &mut self.app
1387 }
1388}
1389
1390pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1391 fn app_mut(&mut self) -> &mut AppContext {
1392 self.borrow_mut()
1393 }
1394
1395 fn window(&self) -> &Window {
1396 self.borrow()
1397 }
1398
1399 fn window_mut(&mut self) -> &mut Window {
1400 self.borrow_mut()
1401 }
1402
1403 /// Pushes the given element id onto the global stack and invokes the given closure
1404 /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1405 /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1406 /// used to associate state with identified elements across separate frames.
1407 fn with_element_id<R>(
1408 &mut self,
1409 id: impl Into<ElementId>,
1410 f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1411 ) -> R {
1412 let keymap = self.app_mut().keymap.clone();
1413 let window = self.window_mut();
1414 window.element_id_stack.push(id.into());
1415 let global_id = window.element_id_stack.clone();
1416
1417 if window.key_matchers.get(&global_id).is_none() {
1418 window.key_matchers.insert(
1419 global_id.clone(),
1420 window
1421 .prev_frame_key_matchers
1422 .remove(&global_id)
1423 .unwrap_or_else(|| KeyMatcher::new(keymap)),
1424 );
1425 }
1426
1427 let result = f(global_id, self);
1428 let window: &mut Window = self.borrow_mut();
1429 window.element_id_stack.pop();
1430 result
1431 }
1432
1433 /// Invoke the given function with the given content mask after intersecting it
1434 /// with the current mask.
1435 fn with_content_mask<R>(
1436 &mut self,
1437 mask: ContentMask<Pixels>,
1438 f: impl FnOnce(&mut Self) -> R,
1439 ) -> R {
1440 let mask = mask.intersect(&self.content_mask());
1441 self.window_mut().content_mask_stack.push(mask);
1442 let result = f(self);
1443 self.window_mut().content_mask_stack.pop();
1444 result
1445 }
1446
1447 /// Update the global element offset based on the given offset. This is used to implement
1448 /// scrolling and position drag handles.
1449 fn with_element_offset<R>(
1450 &mut self,
1451 offset: Option<Point<Pixels>>,
1452 f: impl FnOnce(&mut Self) -> R,
1453 ) -> R {
1454 let Some(offset) = offset else {
1455 return f(self);
1456 };
1457
1458 let offset = self.element_offset() + offset;
1459 self.window_mut().element_offset_stack.push(offset);
1460 let result = f(self);
1461 self.window_mut().element_offset_stack.pop();
1462 result
1463 }
1464
1465 /// Obtain the current element offset.
1466 fn element_offset(&self) -> Point<Pixels> {
1467 self.window()
1468 .element_offset_stack
1469 .last()
1470 .copied()
1471 .unwrap_or_default()
1472 }
1473
1474 /// Update or intialize state for an element with the given id that lives across multiple
1475 /// frames. If an element with this id existed in the previous frame, its state will be passed
1476 /// to the given closure. The state returned by the closure will be stored so it can be referenced
1477 /// when drawing the next frame.
1478 fn with_element_state<S, R>(
1479 &mut self,
1480 id: ElementId,
1481 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1482 ) -> R
1483 where
1484 S: 'static + Send,
1485 {
1486 self.with_element_id(id, |global_id, cx| {
1487 if let Some(any) = cx
1488 .window_mut()
1489 .element_states
1490 .remove(&global_id)
1491 .or_else(|| cx.window_mut().prev_frame_element_states.remove(&global_id))
1492 {
1493 // Using the extra inner option to avoid needing to reallocate a new box.
1494 let mut state_box = any
1495 .downcast::<Option<S>>()
1496 .expect("invalid element state type for id");
1497 let state = state_box
1498 .take()
1499 .expect("element state is already on the stack");
1500 let (result, state) = f(Some(state), cx);
1501 state_box.replace(state);
1502 cx.window_mut().element_states.insert(global_id, state_box);
1503 result
1504 } else {
1505 let (result, state) = f(None, cx);
1506 cx.window_mut()
1507 .element_states
1508 .insert(global_id, Box::new(Some(state)));
1509 result
1510 }
1511 })
1512 }
1513
1514 /// Like `with_element_state`, but for situations where the element_id is optional. If the
1515 /// id is `None`, no state will be retrieved or stored.
1516 fn with_optional_element_state<S, R>(
1517 &mut self,
1518 element_id: Option<ElementId>,
1519 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1520 ) -> R
1521 where
1522 S: 'static + Send,
1523 {
1524 if let Some(element_id) = element_id {
1525 self.with_element_state(element_id, f)
1526 } else {
1527 f(None, self).0
1528 }
1529 }
1530
1531 /// Obtain the current content mask.
1532 fn content_mask(&self) -> ContentMask<Pixels> {
1533 self.window()
1534 .content_mask_stack
1535 .last()
1536 .cloned()
1537 .unwrap_or_else(|| ContentMask {
1538 bounds: Bounds {
1539 origin: Point::default(),
1540 size: self.window().content_size,
1541 },
1542 })
1543 }
1544
1545 /// The size of an em for the base font of the application. Adjusting this value allows the
1546 /// UI to scale, just like zooming a web page.
1547 fn rem_size(&self) -> Pixels {
1548 self.window().rem_size
1549 }
1550}
1551
1552impl Borrow<Window> for WindowContext<'_> {
1553 fn borrow(&self) -> &Window {
1554 &self.window
1555 }
1556}
1557
1558impl BorrowMut<Window> for WindowContext<'_> {
1559 fn borrow_mut(&mut self) -> &mut Window {
1560 &mut self.window
1561 }
1562}
1563
1564impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1565
1566pub struct ViewContext<'a, V> {
1567 window_cx: WindowContext<'a>,
1568 view: &'a View<V>,
1569}
1570
1571impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1572 fn borrow(&self) -> &AppContext {
1573 &*self.window_cx.app
1574 }
1575}
1576
1577impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1578 fn borrow_mut(&mut self) -> &mut AppContext {
1579 &mut *self.window_cx.app
1580 }
1581}
1582
1583impl<V> Borrow<Window> for ViewContext<'_, V> {
1584 fn borrow(&self) -> &Window {
1585 &*self.window_cx.window
1586 }
1587}
1588
1589impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1590 fn borrow_mut(&mut self) -> &mut Window {
1591 &mut *self.window_cx.window
1592 }
1593}
1594
1595impl<'a, V: 'static> ViewContext<'a, V> {
1596 pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1597 Self {
1598 window_cx: WindowContext::new(app, window),
1599 view,
1600 }
1601 }
1602
1603 pub fn view(&self) -> View<V> {
1604 self.view.clone()
1605 }
1606
1607 pub fn model(&self) -> Model<V> {
1608 self.view.model.clone()
1609 }
1610
1611 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1612 self.window.z_index_stack.push(order);
1613 let result = f(self);
1614 self.window.z_index_stack.pop();
1615 result
1616 }
1617
1618 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static)
1619 where
1620 V: Any + Send,
1621 {
1622 let view = self.view();
1623 self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1624 }
1625
1626 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1627 /// that are currently on the stack to be returned to the app.
1628 pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static + Send) {
1629 let view = self.view().downgrade();
1630 self.window_cx.defer(move |cx| {
1631 view.update(cx, f).ok();
1632 });
1633 }
1634
1635 pub fn observe<V2, E>(
1636 &mut self,
1637 entity: &E,
1638 mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + Send + 'static,
1639 ) -> Subscription
1640 where
1641 V2: 'static,
1642 V: 'static + Send,
1643 E: Entity<V2>,
1644 {
1645 let view = self.view().downgrade();
1646 let entity_id = entity.entity_id();
1647 let entity = entity.downgrade();
1648 let window_handle = self.window.handle;
1649 self.app.observers.insert(
1650 entity_id,
1651 Box::new(move |cx| {
1652 cx.update_window(window_handle, |_, cx| {
1653 if let Some(handle) = E::upgrade_from(&entity) {
1654 view.update(cx, |this, cx| on_notify(this, handle, cx))
1655 .is_ok()
1656 } else {
1657 false
1658 }
1659 })
1660 .unwrap_or(false)
1661 }),
1662 )
1663 }
1664
1665 pub fn subscribe<V2, E>(
1666 &mut self,
1667 entity: &E,
1668 mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + Send + 'static,
1669 ) -> Subscription
1670 where
1671 V2: EventEmitter,
1672 E: Entity<V2>,
1673 {
1674 let view = self.view().downgrade();
1675 let entity_id = entity.entity_id();
1676 let handle = entity.downgrade();
1677 let window_handle = self.window.handle;
1678 self.app.event_listeners.insert(
1679 entity_id,
1680 Box::new(move |event, cx| {
1681 cx.update_window(window_handle, |_, cx| {
1682 if let Some(handle) = E::upgrade_from(&handle) {
1683 let event = event.downcast_ref().expect("invalid event type");
1684 view.update(cx, |this, cx| on_event(this, handle, event, cx))
1685 .is_ok()
1686 } else {
1687 false
1688 }
1689 })
1690 .unwrap_or(false)
1691 }),
1692 )
1693 }
1694
1695 pub fn on_release(
1696 &mut self,
1697 on_release: impl FnOnce(&mut V, &mut WindowContext) + Send + 'static,
1698 ) -> Subscription {
1699 let window_handle = self.window.handle;
1700 self.app.release_listeners.insert(
1701 self.view.model.entity_id,
1702 Box::new(move |this, cx| {
1703 let this = this.downcast_mut().expect("invalid entity type");
1704 // todo!("are we okay with silently swallowing the error?")
1705 let _ = cx.update_window(window_handle, |_, cx| on_release(this, cx));
1706 }),
1707 )
1708 }
1709
1710 pub fn observe_release<V2, E>(
1711 &mut self,
1712 entity: &E,
1713 mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + Send + 'static,
1714 ) -> Subscription
1715 where
1716 V: Any + Send,
1717 V2: 'static,
1718 E: Entity<V2>,
1719 {
1720 let view = self.view().downgrade();
1721 let entity_id = entity.entity_id();
1722 let window_handle = self.window.handle;
1723 self.app.release_listeners.insert(
1724 entity_id,
1725 Box::new(move |entity, cx| {
1726 let entity = entity.downcast_mut().expect("invalid entity type");
1727 let _ = cx.update_window(window_handle, |_, cx| {
1728 view.update(cx, |this, cx| on_release(this, entity, cx))
1729 });
1730 }),
1731 )
1732 }
1733
1734 pub fn notify(&mut self) {
1735 self.window_cx.notify();
1736 self.window_cx.app.push_effect(Effect::Notify {
1737 emitter: self.view.model.entity_id,
1738 });
1739 }
1740
1741 pub fn on_focus_changed(
1742 &mut self,
1743 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
1744 ) {
1745 let handle = self.view().downgrade();
1746 self.window.focus_listeners.push(Box::new(move |event, cx| {
1747 handle
1748 .update(cx, |view, cx| listener(view, event, cx))
1749 .log_err();
1750 }));
1751 }
1752
1753 pub fn with_key_listeners<R>(
1754 &mut self,
1755 key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1756 f: impl FnOnce(&mut Self) -> R,
1757 ) -> R {
1758 let old_stack_len = self.window.key_dispatch_stack.len();
1759 if !self.window.freeze_key_dispatch_stack {
1760 for (event_type, listener) in key_listeners {
1761 let handle = self.view().downgrade();
1762 let listener = Box::new(
1763 move |event: &dyn Any,
1764 context_stack: &[&DispatchContext],
1765 phase: DispatchPhase,
1766 cx: &mut WindowContext<'_>| {
1767 handle
1768 .update(cx, |view, cx| {
1769 listener(view, event, context_stack, phase, cx)
1770 })
1771 .log_err()
1772 .flatten()
1773 },
1774 );
1775 self.window
1776 .key_dispatch_stack
1777 .push(KeyDispatchStackFrame::Listener {
1778 event_type,
1779 listener,
1780 });
1781 }
1782 }
1783
1784 let result = f(self);
1785
1786 if !self.window.freeze_key_dispatch_stack {
1787 self.window.key_dispatch_stack.truncate(old_stack_len);
1788 }
1789
1790 result
1791 }
1792
1793 pub fn with_key_dispatch_context<R>(
1794 &mut self,
1795 context: DispatchContext,
1796 f: impl FnOnce(&mut Self) -> R,
1797 ) -> R {
1798 if context.is_empty() {
1799 return f(self);
1800 }
1801
1802 if !self.window.freeze_key_dispatch_stack {
1803 self.window
1804 .key_dispatch_stack
1805 .push(KeyDispatchStackFrame::Context(context));
1806 }
1807
1808 let result = f(self);
1809
1810 if !self.window.freeze_key_dispatch_stack {
1811 self.window.key_dispatch_stack.pop();
1812 }
1813
1814 result
1815 }
1816
1817 pub fn with_focus<R>(
1818 &mut self,
1819 focus_handle: FocusHandle,
1820 f: impl FnOnce(&mut Self) -> R,
1821 ) -> R {
1822 if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1823 self.window
1824 .focus_parents_by_child
1825 .insert(focus_handle.id, parent_focus_id);
1826 }
1827 self.window.focus_stack.push(focus_handle.id);
1828
1829 if Some(focus_handle.id) == self.window.focus {
1830 self.window.freeze_key_dispatch_stack = true;
1831 }
1832
1833 let result = f(self);
1834
1835 self.window.focus_stack.pop();
1836 result
1837 }
1838
1839 pub fn run_on_main<R>(
1840 &mut self,
1841 view: &mut V,
1842 f: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, V>>) -> R + Send + 'static,
1843 ) -> Task<Result<R>>
1844 where
1845 R: Send + 'static,
1846 {
1847 if self.executor.is_main_thread() {
1848 let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
1849 Task::ready(Ok(f(view, cx)))
1850 } else {
1851 let view = self.view();
1852 self.window_cx.run_on_main(move |cx| view.update(cx, f))
1853 }
1854 }
1855
1856 pub fn spawn<Fut, R>(
1857 &mut self,
1858 f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut + Send + 'static,
1859 ) -> Task<R>
1860 where
1861 R: Send + 'static,
1862 Fut: Future<Output = R> + Send + 'static,
1863 {
1864 let view = self.view().downgrade();
1865 self.window_cx.spawn(move |_, cx| {
1866 let result = f(view, cx);
1867 async move { result.await }
1868 })
1869 }
1870
1871 pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1872 where
1873 G: 'static + Send,
1874 {
1875 let mut global = self.app.lease_global::<G>();
1876 let result = f(&mut global, self);
1877 self.app.end_global_lease(global);
1878 result
1879 }
1880
1881 pub fn observe_global<G: 'static>(
1882 &mut self,
1883 f: impl Fn(&mut V, &mut ViewContext<'_, V>) + Send + 'static,
1884 ) -> Subscription {
1885 let window_handle = self.window.handle;
1886 let view = self.view().downgrade();
1887 self.global_observers.insert(
1888 TypeId::of::<G>(),
1889 Box::new(move |cx| {
1890 cx.update_window(window_handle, |_, cx| {
1891 view.update(cx, |view, cx| f(view, cx)).is_ok()
1892 })
1893 .unwrap_or(false)
1894 }),
1895 )
1896 }
1897
1898 pub fn on_mouse_event<Event: 'static>(
1899 &mut self,
1900 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + 'static,
1901 ) {
1902 let handle = self.view();
1903 self.window_cx.on_mouse_event(move |event, phase, cx| {
1904 handle.update(cx, |view, cx| {
1905 handler(view, event, phase, cx);
1906 })
1907 });
1908 }
1909}
1910
1911impl<V> ViewContext<'_, V>
1912where
1913 V: EventEmitter,
1914 V::Event: 'static + Send,
1915{
1916 pub fn emit(&mut self, event: V::Event) {
1917 let emitter = self.view.model.entity_id;
1918 self.app.push_effect(Effect::Emit {
1919 emitter,
1920 event: Box::new(event),
1921 });
1922 }
1923}
1924
1925impl<V: 'static> MainThread<ViewContext<'_, V>> {
1926 fn platform_window(&self) -> &dyn PlatformWindow {
1927 self.window.platform_window.borrow_on_main_thread().as_ref()
1928 }
1929
1930 pub fn activate_window(&self) {
1931 self.platform_window().activate();
1932 }
1933}
1934
1935impl<V> Context for ViewContext<'_, V> {
1936 type WindowContext<'a> = WindowContext<'a>;
1937 type ModelContext<'b, U> = ModelContext<'b, U>;
1938 type Result<U> = U;
1939
1940 fn build_model<T>(
1941 &mut self,
1942 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
1943 ) -> Model<T>
1944 where
1945 T: 'static + Send,
1946 {
1947 self.window_cx.build_model(build_model)
1948 }
1949
1950 fn update_model<T: 'static, R>(
1951 &mut self,
1952 model: &Model<T>,
1953 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
1954 ) -> R {
1955 self.window_cx.update_model(model, update)
1956 }
1957
1958 fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1959 where
1960 F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,
1961 {
1962 self.window_cx.update_window(window, update)
1963 }
1964}
1965
1966impl<V: 'static> VisualContext for ViewContext<'_, V> {
1967 type ViewContext<'a, W: 'static> = ViewContext<'a, W>;
1968
1969 fn build_view<W: 'static + Send>(
1970 &mut self,
1971 build_view: impl FnOnce(&mut Self::ViewContext<'_, W>) -> W,
1972 ) -> Self::Result<View<W>> {
1973 self.window_cx.build_view(build_view)
1974 }
1975
1976 fn update_view<V2: 'static, R>(
1977 &mut self,
1978 view: &View<V2>,
1979 update: impl FnOnce(&mut V2, &mut Self::ViewContext<'_, V2>) -> R,
1980 ) -> Self::Result<R> {
1981 self.window_cx.update_view(view, update)
1982 }
1983
1984 fn replace_root_view<W>(
1985 &mut self,
1986 build_view: impl FnOnce(&mut Self::ViewContext<'_, W>) -> W,
1987 ) -> Self::Result<View<W>>
1988 where
1989 W: 'static + Send + Render,
1990 {
1991 self.window_cx.replace_root_view(build_view)
1992 }
1993}
1994
1995impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
1996 type Target = WindowContext<'a>;
1997
1998 fn deref(&self) -> &Self::Target {
1999 &self.window_cx
2000 }
2001}
2002
2003impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2004 fn deref_mut(&mut self) -> &mut Self::Target {
2005 &mut self.window_cx
2006 }
2007}
2008
2009// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2010slotmap::new_key_type! { pub struct WindowId; }
2011
2012impl WindowId {
2013 pub fn as_u64(&self) -> u64 {
2014 self.0.as_ffi()
2015 }
2016}
2017
2018#[derive(Deref, DerefMut)]
2019pub struct WindowHandle<V> {
2020 #[deref]
2021 #[deref_mut]
2022 pub(crate) any_handle: AnyWindowHandle,
2023 state_type: PhantomData<V>,
2024}
2025
2026impl<V: 'static + Render> WindowHandle<V> {
2027 pub fn new(id: WindowId) -> Self {
2028 WindowHandle {
2029 any_handle: AnyWindowHandle {
2030 id,
2031 state_type: TypeId::of::<V>(),
2032 },
2033 state_type: PhantomData,
2034 }
2035 }
2036
2037 pub fn update_root<C, R, W>(
2038 &self,
2039 cx: &mut C,
2040 update: impl FnOnce(
2041 &mut V,
2042 &mut <C::WindowContext<'_> as VisualContext>::ViewContext<'_, V>,
2043 ) -> R,
2044 ) -> Result<R>
2045 where
2046 C: for<'a> Context<WindowContext<'a> = W>,
2047 W: VisualContext<Result<R> = R>,
2048 {
2049 cx.update_window(self.any_handle, |root_view, cx| {
2050 let view = root_view
2051 .downcast::<V>()
2052 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2053 Ok(view.update(cx, update))
2054 })?
2055 }
2056}
2057
2058impl<V> Copy for WindowHandle<V> {}
2059
2060impl<V> Clone for WindowHandle<V> {
2061 fn clone(&self) -> Self {
2062 WindowHandle {
2063 any_handle: self.any_handle,
2064 state_type: PhantomData,
2065 }
2066 }
2067}
2068
2069impl<V> PartialEq for WindowHandle<V> {
2070 fn eq(&self, other: &Self) -> bool {
2071 self.any_handle == other.any_handle
2072 }
2073}
2074
2075impl<V> Eq for WindowHandle<V> {}
2076
2077impl<V> Hash for WindowHandle<V> {
2078 fn hash<H: Hasher>(&self, state: &mut H) {
2079 self.any_handle.hash(state);
2080 }
2081}
2082
2083impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2084 fn into(self) -> AnyWindowHandle {
2085 self.any_handle
2086 }
2087}
2088
2089#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2090pub struct AnyWindowHandle {
2091 pub(crate) id: WindowId,
2092 state_type: TypeId,
2093}
2094
2095impl AnyWindowHandle {
2096 pub fn window_id(&self) -> WindowId {
2097 self.id
2098 }
2099
2100 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2101 if TypeId::of::<T>() == self.state_type {
2102 Some(WindowHandle {
2103 any_handle: *self,
2104 state_type: PhantomData,
2105 })
2106 } else {
2107 None
2108 }
2109 }
2110}
2111
2112#[cfg(any(test, feature = "test-support"))]
2113impl From<SmallVec<[u32; 16]>> for StackingOrder {
2114 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2115 StackingOrder(small_vec)
2116 }
2117}
2118
2119#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2120pub enum ElementId {
2121 View(EntityId),
2122 Number(usize),
2123 Name(SharedString),
2124 FocusHandle(FocusId),
2125}
2126
2127impl From<EntityId> for ElementId {
2128 fn from(id: EntityId) -> Self {
2129 ElementId::View(id)
2130 }
2131}
2132
2133impl From<usize> for ElementId {
2134 fn from(id: usize) -> Self {
2135 ElementId::Number(id)
2136 }
2137}
2138
2139impl From<i32> for ElementId {
2140 fn from(id: i32) -> Self {
2141 Self::Number(id as usize)
2142 }
2143}
2144
2145impl From<SharedString> for ElementId {
2146 fn from(name: SharedString) -> Self {
2147 ElementId::Name(name)
2148 }
2149}
2150
2151impl From<&'static str> for ElementId {
2152 fn from(name: &'static str) -> Self {
2153 ElementId::Name(name.into())
2154 }
2155}
2156
2157impl<'a> From<&'a FocusHandle> for ElementId {
2158 fn from(handle: &'a FocusHandle) -> Self {
2159 ElementId::FocusHandle(handle.id)
2160 }
2161}