1use crate::{
2 px, size, AnyBox, AnyView, AppContext, AsyncWindowContext, AvailableSpace, BorrowAppContext,
3 Bounds, BoxShadow, Context, Corners, DevicePixels, DisplayId, Edges, Effect, Element, EntityId,
4 EventEmitter, FocusEvent, FontId, GlobalElementId, GlyphId, Handle, Hsla, ImageData,
5 InputEvent, IsZero, KeyListener, LayoutId, MainThread, MainThreadOnly, MonochromeSprite,
6 MouseMoveEvent, Path, Pixels, Platform, PlatformAtlas, PlatformWindow, Point, PolychromeSprite,
7 Quad, Reference, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels,
8 SceneBuilder, Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine, Task,
9 Underline, UnderlineStyle, WeakHandle, WindowOptions, SUBPIXEL_VARIANTS,
10};
11use anyhow::Result;
12use collections::HashMap;
13use derive_more::{Deref, DerefMut};
14use parking_lot::RwLock;
15use slotmap::SlotMap;
16use smallvec::SmallVec;
17use std::{
18 any::{Any, TypeId},
19 borrow::Cow,
20 fmt::Debug,
21 future::Future,
22 marker::PhantomData,
23 mem,
24 sync::{
25 atomic::{AtomicUsize, Ordering::SeqCst},
26 Arc,
27 },
28};
29use util::ResultExt;
30
31#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
32pub struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
33
34#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
35pub enum DispatchPhase {
36 /// After the capture phase comes the bubble phase, in which event handlers are
37 /// invoked front to back. This is the phase you'll usually want to use for event handlers.
38 #[default]
39 Bubble,
40 /// During the initial capture phase, event handlers are invoked back to front. This phase
41 /// is used for special purposes such as clearing the "pressed" state for click events. If
42 /// you stop event propagation during this phase, you need to know what you're doing. Handlers
43 /// outside of the immediate region may rely on detecting non-local events during this phase.
44 Capture,
45}
46
47type AnyListener = Arc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>;
48type AnyFocusListener = Arc<dyn Fn(&FocusEvent, &mut WindowContext) + Send + Sync + 'static>;
49
50slotmap::new_key_type! { pub struct FocusId; }
51
52pub struct FocusHandle {
53 pub(crate) id: FocusId,
54 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
55}
56
57impl FocusHandle {
58 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
59 let id = handles.write().insert(AtomicUsize::new(1));
60 Self {
61 id,
62 handles: handles.clone(),
63 }
64 }
65
66 pub(crate) fn for_id(
67 id: FocusId,
68 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
69 ) -> Option<Self> {
70 let lock = handles.read();
71 let ref_count = lock.get(id)?;
72 if ref_count.load(SeqCst) == 0 {
73 None
74 } else {
75 ref_count.fetch_add(1, SeqCst);
76 Some(Self {
77 id,
78 handles: handles.clone(),
79 })
80 }
81 }
82
83 pub fn is_focused(&self, cx: &WindowContext) -> bool {
84 cx.window.focus == Some(self.id)
85 }
86
87 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
88 cx.focused()
89 .map_or(false, |focused| self.contains(&focused, cx))
90 }
91
92 pub fn within_focused(&self, cx: &WindowContext) -> bool {
93 let focused = cx.focused();
94 focused.map_or(false, |focused| focused.contains(self, cx))
95 }
96
97 pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
98 let mut ancestor = Some(other.id);
99 while let Some(ancestor_id) = ancestor {
100 if self.id == ancestor_id {
101 return true;
102 } else {
103 ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
104 }
105 }
106 false
107 }
108}
109
110impl Clone for FocusHandle {
111 fn clone(&self) -> Self {
112 Self::for_id(self.id, &self.handles).unwrap()
113 }
114}
115
116impl PartialEq for FocusHandle {
117 fn eq(&self, other: &Self) -> bool {
118 self.id == other.id
119 }
120}
121
122impl Eq for FocusHandle {}
123
124impl Drop for FocusHandle {
125 fn drop(&mut self) {
126 self.handles
127 .read()
128 .get(self.id)
129 .unwrap()
130 .fetch_sub(1, SeqCst);
131 }
132}
133
134pub struct Window {
135 handle: AnyWindowHandle,
136 platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
137 display_id: DisplayId,
138 sprite_atlas: Arc<dyn PlatformAtlas>,
139 rem_size: Pixels,
140 content_size: Size<Pixels>,
141 layout_engine: TaffyLayoutEngine,
142 pub(crate) root_view: Option<AnyView>,
143 pub(crate) element_id_stack: GlobalElementId,
144 prev_element_states: HashMap<GlobalElementId, AnyBox>,
145 element_states: HashMap<GlobalElementId, AnyBox>,
146 z_index_stack: StackingOrder,
147 content_mask_stack: Vec<ContentMask<Pixels>>,
148 mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
149 key_listeners: HashMap<TypeId, Vec<AnyListener>>,
150 key_events_enabled: bool,
151 focus_stack: Vec<FocusId>,
152 focus_parents_by_child: HashMap<FocusId, FocusId>,
153 pub(crate) focus_listeners: Vec<AnyFocusListener>,
154 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
155 propagate_event: bool,
156 default_prevented: bool,
157 mouse_position: Point<Pixels>,
158 scale_factor: f32,
159 pub(crate) scene_builder: SceneBuilder,
160 pub(crate) dirty: bool,
161 pub(crate) last_blur: Option<Option<FocusId>>,
162 pub(crate) focus: Option<FocusId>,
163}
164
165impl Window {
166 pub fn new(
167 handle: AnyWindowHandle,
168 options: WindowOptions,
169 cx: &mut MainThread<AppContext>,
170 ) -> Self {
171 let platform_window = cx.platform().open_window(handle, options);
172 let display_id = platform_window.display().id();
173 let sprite_atlas = platform_window.sprite_atlas();
174 let mouse_position = platform_window.mouse_position();
175 let content_size = platform_window.content_size();
176 let scale_factor = platform_window.scale_factor();
177 platform_window.on_resize(Box::new({
178 let cx = cx.to_async();
179 move |content_size, scale_factor| {
180 cx.update_window(handle, |cx| {
181 cx.window.scale_factor = scale_factor;
182 cx.window.scene_builder = SceneBuilder::new();
183 cx.window.content_size = content_size;
184 cx.window.display_id = cx
185 .window
186 .platform_window
187 .borrow_on_main_thread()
188 .display()
189 .id();
190 cx.window.dirty = true;
191 })
192 .log_err();
193 }
194 }));
195
196 platform_window.on_input({
197 let cx = cx.to_async();
198 Box::new(move |event| {
199 cx.update_window(handle, |cx| cx.dispatch_event(event))
200 .log_err()
201 .unwrap_or(true)
202 })
203 });
204
205 let platform_window = MainThreadOnly::new(Arc::new(platform_window), cx.executor.clone());
206
207 Window {
208 handle,
209 platform_window,
210 display_id,
211 sprite_atlas,
212 rem_size: px(16.),
213 content_size,
214 layout_engine: TaffyLayoutEngine::new(),
215 root_view: None,
216 element_id_stack: GlobalElementId::default(),
217 prev_element_states: HashMap::default(),
218 element_states: HashMap::default(),
219 z_index_stack: StackingOrder(SmallVec::new()),
220 content_mask_stack: Vec::new(),
221 mouse_listeners: HashMap::default(),
222 key_listeners: HashMap::default(),
223 key_events_enabled: true,
224 focus_stack: Vec::new(),
225 focus_parents_by_child: HashMap::default(),
226 focus_listeners: Vec::new(),
227 propagate_event: true,
228 default_prevented: true,
229 mouse_position,
230 scale_factor,
231 scene_builder: SceneBuilder::new(),
232 dirty: true,
233 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
234 last_blur: None,
235 focus: None,
236 }
237 }
238}
239
240#[derive(Clone, Debug, Default, PartialEq, Eq)]
241#[repr(C)]
242pub struct ContentMask<P: Clone + Default + Debug> {
243 pub bounds: Bounds<P>,
244}
245
246impl ContentMask<Pixels> {
247 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
248 ContentMask {
249 bounds: self.bounds.scale(factor),
250 }
251 }
252
253 pub fn intersect(&self, other: &Self) -> Self {
254 let bounds = self.bounds.intersect(&other.bounds);
255 ContentMask { bounds }
256 }
257}
258
259pub struct WindowContext<'a, 'w> {
260 app: Reference<'a, AppContext>,
261 pub(crate) window: Reference<'w, Window>,
262}
263
264impl<'a, 'w> WindowContext<'a, 'w> {
265 pub(crate) fn mutable(app: &'a mut AppContext, window: &'w mut Window) -> Self {
266 Self {
267 app: Reference::Mutable(app),
268 window: Reference::Mutable(window),
269 }
270 }
271
272 pub fn notify(&mut self) {
273 self.window.dirty = true;
274 }
275
276 pub fn focus_handle(&mut self) -> FocusHandle {
277 FocusHandle::new(&self.window.focus_handles)
278 }
279
280 pub fn focused(&self) -> Option<FocusHandle> {
281 self.window
282 .focus
283 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
284 }
285
286 pub fn focus(&mut self, handle: &FocusHandle) {
287 if self.window.last_blur.is_none() {
288 self.window.last_blur = Some(self.window.focus);
289 }
290
291 let window_id = self.window.handle.id;
292 self.window.focus = Some(handle.id);
293 self.push_effect(Effect::FocusChanged {
294 window_id,
295 focused: Some(handle.id),
296 });
297 self.notify();
298 }
299
300 pub fn blur(&mut self) {
301 if self.window.last_blur.is_none() {
302 self.window.last_blur = Some(self.window.focus);
303 }
304
305 let window_id = self.window.handle.id;
306 self.window.focus = None;
307 self.push_effect(Effect::FocusChanged {
308 window_id,
309 focused: None,
310 });
311 self.notify();
312 }
313
314 pub fn run_on_main<R>(
315 &mut self,
316 f: impl FnOnce(&mut MainThread<WindowContext<'_, '_>>) -> R + Send + 'static,
317 ) -> Task<Result<R>>
318 where
319 R: Send + 'static,
320 {
321 if self.executor.is_main_thread() {
322 Task::ready(Ok(f(unsafe {
323 mem::transmute::<&mut Self, &mut MainThread<Self>>(self)
324 })))
325 } else {
326 let id = self.window.handle.id;
327 self.app.run_on_main(move |cx| cx.update_window(id, f))
328 }
329 }
330
331 pub fn to_async(&self) -> AsyncWindowContext {
332 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
333 }
334
335 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
336 let f = Box::new(f);
337 let display_id = self.window.display_id;
338 self.run_on_main(move |cx| {
339 if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {
340 callbacks.push(f);
341 // If there was already a callback, it means that we already scheduled a frame.
342 if callbacks.len() > 1 {
343 return;
344 }
345 } else {
346 let async_cx = cx.to_async();
347 cx.next_frame_callbacks.insert(display_id, vec![f]);
348 cx.platform().set_display_link_output_callback(
349 display_id,
350 Box::new(move |_current_time, _output_time| {
351 let _ = async_cx.update(|cx| {
352 let callbacks = cx
353 .next_frame_callbacks
354 .get_mut(&display_id)
355 .unwrap()
356 .drain(..)
357 .collect::<Vec<_>>();
358 for callback in callbacks {
359 callback(cx);
360 }
361
362 cx.run_on_main(move |cx| {
363 if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
364 cx.platform().stop_display_link(display_id);
365 }
366 })
367 .detach();
368 });
369 }),
370 );
371 }
372
373 cx.platform().start_display_link(display_id);
374 })
375 .detach();
376 }
377
378 pub fn spawn<Fut, R>(
379 &mut self,
380 f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut + Send + 'static,
381 ) -> Task<R>
382 where
383 R: Send + 'static,
384 Fut: Future<Output = R> + Send + 'static,
385 {
386 let window = self.window.handle;
387 self.app.spawn(move |app| {
388 let cx = AsyncWindowContext::new(app, window);
389 let future = f(window, cx);
390 async move { future.await }
391 })
392 }
393
394 pub fn request_layout(
395 &mut self,
396 style: &Style,
397 children: impl IntoIterator<Item = LayoutId>,
398 ) -> LayoutId {
399 self.app.layout_id_buffer.clear();
400 self.app.layout_id_buffer.extend(children.into_iter());
401 let rem_size = self.rem_size();
402
403 self.window
404 .layout_engine
405 .request_layout(style, rem_size, &self.app.layout_id_buffer)
406 }
407
408 pub fn request_measured_layout<
409 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
410 >(
411 &mut self,
412 style: Style,
413 rem_size: Pixels,
414 measure: F,
415 ) -> LayoutId {
416 self.window
417 .layout_engine
418 .request_measured_layout(style, rem_size, measure)
419 }
420
421 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
422 self.window
423 .layout_engine
424 .layout_bounds(layout_id)
425 .map(Into::into)
426 }
427
428 pub fn scale_factor(&self) -> f32 {
429 self.window.scale_factor
430 }
431
432 pub fn rem_size(&self) -> Pixels {
433 self.window.rem_size
434 }
435
436 pub fn stop_propagation(&mut self) {
437 self.window.propagate_event = false;
438 }
439
440 pub fn prevent_default(&mut self) {
441 self.window.default_prevented = true;
442 }
443
444 pub fn default_prevented(&self) -> bool {
445 self.window.default_prevented
446 }
447
448 pub fn on_mouse_event<Event: 'static>(
449 &mut self,
450 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + Sync + 'static,
451 ) {
452 let order = self.window.z_index_stack.clone();
453 self.window
454 .mouse_listeners
455 .entry(TypeId::of::<Event>())
456 .or_default()
457 .push((
458 order,
459 Arc::new(move |event: &dyn Any, phase, cx| {
460 handler(event.downcast_ref().unwrap(), phase, cx)
461 }),
462 ))
463 }
464
465 pub fn on_keyboard_event<Event: 'static>(
466 &mut self,
467 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + Sync + 'static,
468 ) {
469 self.window
470 .key_listeners
471 .entry(TypeId::of::<Event>())
472 .or_default()
473 .push(Arc::new(move |event: &dyn Any, phase, cx| {
474 handler(event.downcast_ref().unwrap(), phase, cx)
475 }))
476 }
477
478 pub fn mouse_position(&self) -> Point<Pixels> {
479 self.window.mouse_position
480 }
481
482 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
483 self.window.z_index_stack.push(order);
484 let result = f(self);
485 self.window.z_index_stack.pop();
486 result
487 }
488
489 pub fn paint_shadows(
490 &mut self,
491 bounds: Bounds<Pixels>,
492 corner_radii: Corners<Pixels>,
493 shadows: &[BoxShadow],
494 ) {
495 let scale_factor = self.scale_factor();
496 let content_mask = self.content_mask();
497 let window = &mut *self.window;
498 for shadow in shadows {
499 let mut shadow_bounds = bounds;
500 shadow_bounds.origin += shadow.offset;
501 shadow_bounds.dilate(shadow.spread_radius);
502 window.scene_builder.insert(
503 &window.z_index_stack,
504 Shadow {
505 order: 0,
506 bounds: shadow_bounds.scale(scale_factor),
507 content_mask: content_mask.scale(scale_factor),
508 corner_radii: corner_radii.scale(scale_factor),
509 color: shadow.color,
510 blur_radius: shadow.blur_radius.scale(scale_factor),
511 },
512 );
513 }
514 }
515
516 pub fn paint_quad(
517 &mut self,
518 bounds: Bounds<Pixels>,
519 corner_radii: Corners<Pixels>,
520 background: impl Into<Hsla>,
521 border_widths: Edges<Pixels>,
522 border_color: impl Into<Hsla>,
523 ) {
524 let scale_factor = self.scale_factor();
525 let content_mask = self.content_mask();
526
527 let window = &mut *self.window;
528 window.scene_builder.insert(
529 &window.z_index_stack,
530 Quad {
531 order: 0,
532 bounds: bounds.scale(scale_factor),
533 content_mask: content_mask.scale(scale_factor),
534 background: background.into(),
535 border_color: border_color.into(),
536 corner_radii: corner_radii.scale(scale_factor),
537 border_widths: border_widths.scale(scale_factor),
538 },
539 );
540 }
541
542 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
543 let scale_factor = self.scale_factor();
544 let content_mask = self.content_mask();
545 path.content_mask = content_mask;
546 path.color = color.into();
547 let window = &mut *self.window;
548 window
549 .scene_builder
550 .insert(&window.z_index_stack, path.scale(scale_factor));
551 }
552
553 pub fn paint_underline(
554 &mut self,
555 origin: Point<Pixels>,
556 width: Pixels,
557 style: &UnderlineStyle,
558 ) -> Result<()> {
559 let scale_factor = self.scale_factor();
560 let height = if style.wavy {
561 style.thickness * 3.
562 } else {
563 style.thickness
564 };
565 let bounds = Bounds {
566 origin,
567 size: size(width, height),
568 };
569 let content_mask = self.content_mask();
570 let window = &mut *self.window;
571 window.scene_builder.insert(
572 &window.z_index_stack,
573 Underline {
574 order: 0,
575 bounds: bounds.scale(scale_factor),
576 content_mask: content_mask.scale(scale_factor),
577 thickness: style.thickness.scale(scale_factor),
578 color: style.color.unwrap_or_default(),
579 wavy: style.wavy,
580 },
581 );
582 Ok(())
583 }
584
585 pub fn paint_glyph(
586 &mut self,
587 origin: Point<Pixels>,
588 font_id: FontId,
589 glyph_id: GlyphId,
590 font_size: Pixels,
591 color: Hsla,
592 ) -> Result<()> {
593 let scale_factor = self.scale_factor();
594 let glyph_origin = origin.scale(scale_factor);
595 let subpixel_variant = Point {
596 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
597 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
598 };
599 let params = RenderGlyphParams {
600 font_id,
601 glyph_id,
602 font_size,
603 subpixel_variant,
604 scale_factor,
605 is_emoji: false,
606 };
607
608 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
609 if !raster_bounds.is_zero() {
610 let tile =
611 self.window
612 .sprite_atlas
613 .get_or_insert_with(¶ms.clone().into(), &mut || {
614 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
615 Ok((size, Cow::Owned(bytes)))
616 })?;
617 let bounds = Bounds {
618 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
619 size: tile.bounds.size.map(Into::into),
620 };
621 let content_mask = self.content_mask().scale(scale_factor);
622 let window = &mut *self.window;
623 window.scene_builder.insert(
624 &window.z_index_stack,
625 MonochromeSprite {
626 order: 0,
627 bounds,
628 content_mask,
629 color,
630 tile,
631 },
632 );
633 }
634 Ok(())
635 }
636
637 pub fn paint_emoji(
638 &mut self,
639 origin: Point<Pixels>,
640 font_id: FontId,
641 glyph_id: GlyphId,
642 font_size: Pixels,
643 ) -> Result<()> {
644 let scale_factor = self.scale_factor();
645 let glyph_origin = origin.scale(scale_factor);
646 let params = RenderGlyphParams {
647 font_id,
648 glyph_id,
649 font_size,
650 // We don't render emojis with subpixel variants.
651 subpixel_variant: Default::default(),
652 scale_factor,
653 is_emoji: true,
654 };
655
656 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
657 if !raster_bounds.is_zero() {
658 let tile =
659 self.window
660 .sprite_atlas
661 .get_or_insert_with(¶ms.clone().into(), &mut || {
662 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
663 Ok((size, Cow::Owned(bytes)))
664 })?;
665 let bounds = Bounds {
666 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
667 size: tile.bounds.size.map(Into::into),
668 };
669 let content_mask = self.content_mask().scale(scale_factor);
670 let window = &mut *self.window;
671
672 window.scene_builder.insert(
673 &window.z_index_stack,
674 PolychromeSprite {
675 order: 0,
676 bounds,
677 corner_radii: Default::default(),
678 content_mask,
679 tile,
680 grayscale: false,
681 },
682 );
683 }
684 Ok(())
685 }
686
687 pub fn paint_svg(
688 &mut self,
689 bounds: Bounds<Pixels>,
690 path: SharedString,
691 color: Hsla,
692 ) -> Result<()> {
693 let scale_factor = self.scale_factor();
694 let bounds = bounds.scale(scale_factor);
695 // Render the SVG at twice the size to get a higher quality result.
696 let params = RenderSvgParams {
697 path,
698 size: bounds
699 .size
700 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
701 };
702
703 let tile =
704 self.window
705 .sprite_atlas
706 .get_or_insert_with(¶ms.clone().into(), &mut || {
707 let bytes = self.svg_renderer.render(¶ms)?;
708 Ok((params.size, Cow::Owned(bytes)))
709 })?;
710 let content_mask = self.content_mask().scale(scale_factor);
711
712 let window = &mut *self.window;
713 window.scene_builder.insert(
714 &window.z_index_stack,
715 MonochromeSprite {
716 order: 0,
717 bounds,
718 content_mask,
719 color,
720 tile,
721 },
722 );
723
724 Ok(())
725 }
726
727 pub fn paint_image(
728 &mut self,
729 bounds: Bounds<Pixels>,
730 corner_radii: Corners<Pixels>,
731 data: Arc<ImageData>,
732 grayscale: bool,
733 ) -> Result<()> {
734 let scale_factor = self.scale_factor();
735 let bounds = bounds.scale(scale_factor);
736 let params = RenderImageParams { image_id: data.id };
737
738 let tile = self
739 .window
740 .sprite_atlas
741 .get_or_insert_with(¶ms.clone().into(), &mut || {
742 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
743 })?;
744 let content_mask = self.content_mask().scale(scale_factor);
745 let corner_radii = corner_radii.scale(scale_factor);
746
747 let window = &mut *self.window;
748 window.scene_builder.insert(
749 &window.z_index_stack,
750 PolychromeSprite {
751 order: 0,
752 bounds,
753 content_mask,
754 corner_radii,
755 tile,
756 grayscale,
757 },
758 );
759 Ok(())
760 }
761
762 pub(crate) fn draw(&mut self) {
763 let unit_entity = self.unit_entity.clone();
764 self.update_entity(&unit_entity, |view, cx| {
765 cx.start_frame();
766
767 let mut root_view = cx.window.root_view.take().unwrap();
768
769 if let Some(element_id) = root_view.id() {
770 cx.with_element_state(element_id, |element_state, cx| {
771 let element_state = draw_with_element_state(&mut root_view, element_state, cx);
772 ((), element_state)
773 });
774 } else {
775 draw_with_element_state(&mut root_view, None, cx);
776 };
777
778 cx.window.root_view = Some(root_view);
779 let scene = cx.window.scene_builder.build();
780 cx.end_frame();
781
782 cx.run_on_main(view, |_, cx| {
783 cx.window
784 .platform_window
785 .borrow_on_main_thread()
786 .draw(scene);
787 cx.window.dirty = false;
788 })
789 .detach();
790 });
791
792 fn draw_with_element_state(
793 root_view: &mut AnyView,
794 element_state: Option<AnyBox>,
795 cx: &mut ViewContext<()>,
796 ) -> AnyBox {
797 let mut element_state = root_view.initialize(&mut (), element_state, cx);
798 let layout_id = root_view.layout(&mut (), &mut element_state, cx);
799 let available_space = cx.window.content_size.map(Into::into);
800 cx.window
801 .layout_engine
802 .compute_layout(layout_id, available_space);
803 let bounds = cx.window.layout_engine.layout_bounds(layout_id);
804 root_view.paint(bounds, &mut (), &mut element_state, cx);
805 element_state
806 }
807 }
808
809 fn start_frame(&mut self) {
810 // Make the current element states the previous, and then clear the current.
811 // The empty element states map will be populated for any element states we
812 // reference during the upcoming frame.
813 let window = &mut *self.window;
814 mem::swap(&mut window.element_states, &mut window.prev_element_states);
815 window.element_states.clear();
816
817 // Clear mouse event listeners, because elements add new element listeners
818 // when the upcoming frame is painted.
819 window.mouse_listeners.values_mut().for_each(Vec::clear);
820
821 // Clear focus state, because we determine what is focused when the new elements
822 // in the upcoming frame are initialized.
823 window.focus_listeners.clear();
824 window.key_listeners.values_mut().for_each(Vec::clear);
825 window.focus_parents_by_child.clear();
826 window.key_events_enabled = true;
827 }
828
829 fn end_frame(&mut self) {
830 self.text_system().end_frame();
831 }
832
833 fn dispatch_event(&mut self, event: InputEvent) -> bool {
834 if let Some(any_mouse_event) = event.mouse_event() {
835 if let Some(MouseMoveEvent { position, .. }) = any_mouse_event.downcast_ref() {
836 self.window.mouse_position = *position;
837 }
838
839 // Handlers may set this to false by calling `stop_propagation`
840 self.window.propagate_event = true;
841 self.window.default_prevented = false;
842
843 if let Some(mut handlers) = self
844 .window
845 .mouse_listeners
846 .remove(&any_mouse_event.type_id())
847 {
848 // Because handlers may add other handlers, we sort every time.
849 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
850
851 // Capture phase, events bubble from back to front. Handlers for this phase are used for
852 // special purposes, such as detecting events outside of a given Bounds.
853 for (_, handler) in &handlers {
854 handler(any_mouse_event, DispatchPhase::Capture, self);
855 if !self.window.propagate_event {
856 break;
857 }
858 }
859
860 // Bubble phase, where most normal handlers do their work.
861 if self.window.propagate_event {
862 for (_, handler) in handlers.iter().rev() {
863 handler(any_mouse_event, DispatchPhase::Bubble, self);
864 if !self.window.propagate_event {
865 break;
866 }
867 }
868 }
869
870 // Just in case any handlers added new handlers, which is weird, but possible.
871 handlers.extend(
872 self.window
873 .mouse_listeners
874 .get_mut(&any_mouse_event.type_id())
875 .into_iter()
876 .flat_map(|handlers| handlers.drain(..)),
877 );
878 self.window
879 .mouse_listeners
880 .insert(any_mouse_event.type_id(), handlers);
881 }
882 } else if let Some(any_keyboard_event) = event.keyboard_event() {
883 if let Some(mut handlers) = self
884 .window
885 .key_listeners
886 .remove(&any_keyboard_event.type_id())
887 {
888 for handler in &handlers {
889 handler(any_keyboard_event, DispatchPhase::Capture, self);
890 if !self.window.propagate_event {
891 break;
892 }
893 }
894
895 if self.window.propagate_event {
896 for handler in handlers.iter().rev() {
897 handler(any_keyboard_event, DispatchPhase::Bubble, self);
898 if !self.window.propagate_event {
899 break;
900 }
901 }
902 }
903
904 handlers.extend(
905 self.window
906 .key_listeners
907 .get_mut(&any_keyboard_event.type_id())
908 .into_iter()
909 .flat_map(|handlers| handlers.drain(..)),
910 );
911 self.window
912 .key_listeners
913 .insert(any_keyboard_event.type_id(), handlers);
914 }
915 }
916
917 true
918 }
919}
920
921impl<'a, 'w> MainThread<WindowContext<'a, 'w>> {
922 fn platform(&self) -> &dyn Platform {
923 self.platform.borrow_on_main_thread()
924 }
925}
926
927impl Context for WindowContext<'_, '_> {
928 type EntityContext<'a, 'w, T: 'static + Send + Sync> = ViewContext<'a, 'w, T>;
929 type Result<T> = T;
930
931 fn entity<T: Send + Sync + 'static>(
932 &mut self,
933 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
934 ) -> Handle<T> {
935 let slot = self.app.entities.reserve();
936 let entity = build_entity(&mut ViewContext::mutable(
937 &mut *self.app,
938 &mut self.window,
939 slot.id,
940 ));
941 self.entities.insert(slot, entity)
942 }
943
944 fn update_entity<T: Send + Sync + 'static, R>(
945 &mut self,
946 handle: &Handle<T>,
947 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
948 ) -> R {
949 let mut entity = self.entities.lease(handle);
950 let result = update(
951 &mut *entity,
952 &mut ViewContext::mutable(&mut *self.app, &mut *self.window, handle.id),
953 );
954 self.entities.end_lease(entity);
955 result
956 }
957}
958
959impl<'a, 'w> std::ops::Deref for WindowContext<'a, 'w> {
960 type Target = AppContext;
961
962 fn deref(&self) -> &Self::Target {
963 &self.app
964 }
965}
966
967impl<'a, 'w> std::ops::DerefMut for WindowContext<'a, 'w> {
968 fn deref_mut(&mut self) -> &mut Self::Target {
969 &mut self.app
970 }
971}
972
973impl BorrowAppContext for WindowContext<'_, '_> {
974 fn app_mut(&mut self) -> &mut AppContext {
975 &mut *self.app
976 }
977}
978
979pub trait BorrowWindow: BorrowAppContext {
980 fn window(&self) -> &Window;
981 fn window_mut(&mut self) -> &mut Window;
982
983 fn with_element_id<R>(
984 &mut self,
985 id: impl Into<ElementId>,
986 f: impl FnOnce(&mut Self) -> R,
987 ) -> R {
988 self.window_mut().element_id_stack.push(id.into());
989 let result = f(self);
990 self.window_mut().element_id_stack.pop();
991 result
992 }
993
994 fn with_content_mask<R>(
995 &mut self,
996 mask: ContentMask<Pixels>,
997 f: impl FnOnce(&mut Self) -> R,
998 ) -> R {
999 let mask = mask.intersect(&self.content_mask());
1000 self.window_mut().content_mask_stack.push(mask);
1001 let result = f(self);
1002 self.window_mut().content_mask_stack.pop();
1003 result
1004 }
1005
1006 fn with_element_state<S: 'static + Send + Sync, R>(
1007 &mut self,
1008 id: ElementId,
1009 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1010 ) -> R {
1011 self.with_element_id(id, |cx| {
1012 let global_id = cx.window_mut().element_id_stack.clone();
1013 if let Some(any) = cx
1014 .window_mut()
1015 .element_states
1016 .remove(&global_id)
1017 .or_else(|| cx.window_mut().prev_element_states.remove(&global_id))
1018 {
1019 // Using the extra inner option to avoid needing to reallocate a new box.
1020 let mut state_box = any
1021 .downcast::<Option<S>>()
1022 .expect("invalid element state type for id");
1023 let state = state_box
1024 .take()
1025 .expect("element state is already on the stack");
1026 let (result, state) = f(Some(state), cx);
1027 state_box.replace(state);
1028 cx.window_mut().element_states.insert(global_id, state_box);
1029 result
1030 } else {
1031 let (result, state) = f(None, cx);
1032 cx.window_mut()
1033 .element_states
1034 .insert(global_id, Box::new(Some(state)));
1035 result
1036 }
1037 })
1038 }
1039
1040 fn content_mask(&self) -> ContentMask<Pixels> {
1041 self.window()
1042 .content_mask_stack
1043 .last()
1044 .cloned()
1045 .unwrap_or_else(|| ContentMask {
1046 bounds: Bounds {
1047 origin: Point::default(),
1048 size: self.window().content_size,
1049 },
1050 })
1051 }
1052
1053 fn rem_size(&self) -> Pixels {
1054 self.window().rem_size
1055 }
1056}
1057
1058impl BorrowWindow for WindowContext<'_, '_> {
1059 fn window(&self) -> &Window {
1060 &*self.window
1061 }
1062
1063 fn window_mut(&mut self) -> &mut Window {
1064 &mut *self.window
1065 }
1066}
1067
1068pub struct ViewContext<'a, 'w, S> {
1069 window_cx: WindowContext<'a, 'w>,
1070 entity_type: PhantomData<S>,
1071 entity_id: EntityId,
1072}
1073
1074impl<S> BorrowAppContext for ViewContext<'_, '_, S> {
1075 fn app_mut(&mut self) -> &mut AppContext {
1076 &mut *self.window_cx.app
1077 }
1078}
1079
1080impl<S> BorrowWindow for ViewContext<'_, '_, S> {
1081 fn window(&self) -> &Window {
1082 &self.window_cx.window
1083 }
1084
1085 fn window_mut(&mut self) -> &mut Window {
1086 &mut *self.window_cx.window
1087 }
1088}
1089
1090impl<'a, 'w, V: Send + Sync + 'static> ViewContext<'a, 'w, V> {
1091 fn mutable(app: &'a mut AppContext, window: &'w mut Window, entity_id: EntityId) -> Self {
1092 Self {
1093 window_cx: WindowContext::mutable(app, window),
1094 entity_id,
1095 entity_type: PhantomData,
1096 }
1097 }
1098
1099 pub fn handle(&self) -> WeakHandle<V> {
1100 self.entities.weak_handle(self.entity_id)
1101 }
1102
1103 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1104 self.window.z_index_stack.push(order);
1105 let result = f(self);
1106 self.window.z_index_stack.pop();
1107 result
1108 }
1109
1110 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + Send + 'static) {
1111 let entity = self.handle();
1112 self.window_cx.on_next_frame(move |cx| {
1113 entity.update(cx, f).ok();
1114 });
1115 }
1116
1117 pub fn observe<E: Send + Sync + 'static>(
1118 &mut self,
1119 handle: &Handle<E>,
1120 on_notify: impl Fn(&mut V, Handle<E>, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
1121 ) -> Subscription {
1122 let this = self.handle();
1123 let handle = handle.downgrade();
1124 let window_handle = self.window.handle;
1125 self.app.observers.insert(
1126 handle.id,
1127 Box::new(move |cx| {
1128 cx.update_window(window_handle.id, |cx| {
1129 if let Some(handle) = handle.upgrade(cx) {
1130 this.update(cx, |this, cx| on_notify(this, handle, cx))
1131 .is_ok()
1132 } else {
1133 false
1134 }
1135 })
1136 .unwrap_or(false)
1137 }),
1138 )
1139 }
1140
1141 pub fn subscribe<E: EventEmitter + Send + Sync + 'static>(
1142 &mut self,
1143 handle: &Handle<E>,
1144 on_event: impl Fn(&mut V, Handle<E>, &E::Event, &mut ViewContext<'_, '_, V>)
1145 + Send
1146 + Sync
1147 + 'static,
1148 ) -> Subscription {
1149 let this = self.handle();
1150 let handle = handle.downgrade();
1151 let window_handle = self.window.handle;
1152 self.app.event_handlers.insert(
1153 handle.id,
1154 Box::new(move |event, cx| {
1155 cx.update_window(window_handle.id, |cx| {
1156 if let Some(handle) = handle.upgrade(cx) {
1157 let event = event.downcast_ref().expect("invalid event type");
1158 this.update(cx, |this, cx| on_event(this, handle, event, cx))
1159 .is_ok()
1160 } else {
1161 false
1162 }
1163 })
1164 .unwrap_or(false)
1165 }),
1166 )
1167 }
1168
1169 pub fn on_release(
1170 &mut self,
1171 on_release: impl Fn(&mut V, &mut WindowContext) + Send + Sync + 'static,
1172 ) -> Subscription {
1173 let window_handle = self.window.handle;
1174 self.app.release_handlers.insert(
1175 self.entity_id,
1176 Box::new(move |this, cx| {
1177 let this = this.downcast_mut().expect("invalid entity type");
1178 // todo!("are we okay with silently swallowing the error?")
1179 let _ = cx.update_window(window_handle.id, |cx| on_release(this, cx));
1180 }),
1181 )
1182 }
1183
1184 pub fn observe_release<E: Send + Sync + 'static>(
1185 &mut self,
1186 handle: &Handle<E>,
1187 on_release: impl Fn(&mut V, &mut E, &mut ViewContext<'_, '_, V>) + Send + Sync + 'static,
1188 ) -> Subscription {
1189 let this = self.handle();
1190 let window_handle = self.window.handle;
1191 self.app.release_handlers.insert(
1192 handle.id,
1193 Box::new(move |entity, cx| {
1194 let entity = entity.downcast_mut().expect("invalid entity type");
1195 // todo!("are we okay with silently swallowing the error?")
1196 let _ = cx.update_window(window_handle.id, |cx| {
1197 this.update(cx, |this, cx| on_release(this, entity, cx))
1198 });
1199 }),
1200 )
1201 }
1202
1203 pub fn notify(&mut self) {
1204 self.window_cx.notify();
1205 self.window_cx.app.push_effect(Effect::Notify {
1206 emitter: self.entity_id,
1207 });
1208 }
1209
1210 pub fn on_focus_changed(
1211 &mut self,
1212 listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + Sync + 'static,
1213 ) {
1214 let handle = self.handle();
1215 self.window.focus_listeners.push(Arc::new(move |event, cx| {
1216 handle
1217 .update(cx, |view, cx| listener(view, event, cx))
1218 .log_err();
1219 }));
1220 }
1221
1222 pub fn with_key_listeners<R>(
1223 &mut self,
1224 key_listeners: &[(TypeId, KeyListener<V>)],
1225 f: impl FnOnce(&mut Self) -> R,
1226 ) -> R {
1227 if self.window.key_events_enabled {
1228 let handle = self.handle();
1229 for (type_id, listener) in key_listeners {
1230 let handle = handle.clone();
1231 let listener = listener.clone();
1232 self.window
1233 .key_listeners
1234 .entry(*type_id)
1235 .or_default()
1236 .push(Arc::new(move |event, phase, cx| {
1237 handle
1238 .update(cx, |view, cx| listener(view, event, phase, cx))
1239 .log_err();
1240 }));
1241 }
1242 }
1243
1244 let result = f(self);
1245
1246 if self.window.key_events_enabled {
1247 for (type_id, _) in key_listeners {
1248 self.window.key_listeners.get_mut(type_id).unwrap().pop();
1249 }
1250 }
1251
1252 result
1253 }
1254
1255 pub fn with_focus<R>(
1256 &mut self,
1257 focus_handle: FocusHandle,
1258 f: impl FnOnce(&mut Self) -> R,
1259 ) -> R {
1260 if let Some(parent_focus_id) = self.window.focus_stack.last().copied() {
1261 self.window
1262 .focus_parents_by_child
1263 .insert(focus_handle.id, parent_focus_id);
1264 }
1265 self.window.focus_stack.push(focus_handle.id);
1266
1267 if Some(focus_handle.id) == self.window.focus {
1268 self.window.key_events_enabled = false;
1269 }
1270
1271 let result = f(self);
1272
1273 self.window.focus_stack.pop();
1274 result
1275 }
1276
1277 pub fn run_on_main<R>(
1278 &mut self,
1279 view: &mut V,
1280 f: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, '_, V>>) -> R + Send + 'static,
1281 ) -> Task<Result<R>>
1282 where
1283 R: Send + 'static,
1284 {
1285 if self.executor.is_main_thread() {
1286 let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
1287 Task::ready(Ok(f(view, cx)))
1288 } else {
1289 let handle = self.handle().upgrade(self).unwrap();
1290 self.window_cx.run_on_main(move |cx| handle.update(cx, f))
1291 }
1292 }
1293
1294 pub fn spawn<Fut, R>(
1295 &mut self,
1296 f: impl FnOnce(WeakHandle<V>, AsyncWindowContext) -> Fut + Send + 'static,
1297 ) -> Task<R>
1298 where
1299 R: Send + 'static,
1300 Fut: Future<Output = R> + Send + 'static,
1301 {
1302 let handle = self.handle();
1303 self.window_cx.spawn(move |_, cx| {
1304 let result = f(handle, cx);
1305 async move { result.await }
1306 })
1307 }
1308
1309 pub fn on_mouse_event<Event: 'static>(
1310 &mut self,
1311 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + Sync + 'static,
1312 ) {
1313 let handle = self.handle().upgrade(self).unwrap();
1314 self.window_cx.on_mouse_event(move |event, phase, cx| {
1315 handle.update(cx, |view, cx| {
1316 handler(view, event, phase, cx);
1317 })
1318 });
1319 }
1320
1321 pub fn on_keyboard_event<Event: 'static>(
1322 &mut self,
1323 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + Sync + 'static,
1324 ) {
1325 let handle = self.handle().upgrade(self).unwrap();
1326 self.window_cx.on_keyboard_event(move |event, phase, cx| {
1327 handle.update(cx, |view, cx| {
1328 handler(view, event, phase, cx);
1329 })
1330 });
1331 }
1332}
1333
1334impl<'a, 'w, S: EventEmitter + Send + Sync + 'static> ViewContext<'a, 'w, S> {
1335 pub fn emit(&mut self, event: S::Event) {
1336 self.window_cx.app.push_effect(Effect::Emit {
1337 emitter: self.entity_id,
1338 event: Box::new(event),
1339 });
1340 }
1341}
1342
1343impl<'a, 'w, S> Context for ViewContext<'a, 'w, S> {
1344 type EntityContext<'b, 'c, U: 'static + Send + Sync> = ViewContext<'b, 'c, U>;
1345 type Result<U> = U;
1346
1347 fn entity<T2: Send + Sync + 'static>(
1348 &mut self,
1349 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T2>) -> T2,
1350 ) -> Handle<T2> {
1351 self.window_cx.entity(build_entity)
1352 }
1353
1354 fn update_entity<U: Send + Sync + 'static, R>(
1355 &mut self,
1356 handle: &Handle<U>,
1357 update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
1358 ) -> R {
1359 self.window_cx.update_entity(handle, update)
1360 }
1361}
1362
1363impl<'a, 'w, S: 'static> std::ops::Deref for ViewContext<'a, 'w, S> {
1364 type Target = WindowContext<'a, 'w>;
1365
1366 fn deref(&self) -> &Self::Target {
1367 &self.window_cx
1368 }
1369}
1370
1371impl<'a, 'w, S: 'static> std::ops::DerefMut for ViewContext<'a, 'w, S> {
1372 fn deref_mut(&mut self) -> &mut Self::Target {
1373 &mut self.window_cx
1374 }
1375}
1376
1377// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
1378slotmap::new_key_type! { pub struct WindowId; }
1379
1380#[derive(PartialEq, Eq)]
1381pub struct WindowHandle<S> {
1382 id: WindowId,
1383 state_type: PhantomData<S>,
1384}
1385
1386impl<S> Copy for WindowHandle<S> {}
1387
1388impl<S> Clone for WindowHandle<S> {
1389 fn clone(&self) -> Self {
1390 WindowHandle {
1391 id: self.id,
1392 state_type: PhantomData,
1393 }
1394 }
1395}
1396
1397impl<S> WindowHandle<S> {
1398 pub fn new(id: WindowId) -> Self {
1399 WindowHandle {
1400 id,
1401 state_type: PhantomData,
1402 }
1403 }
1404}
1405
1406impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
1407 fn into(self) -> AnyWindowHandle {
1408 AnyWindowHandle {
1409 id: self.id,
1410 state_type: TypeId::of::<S>(),
1411 }
1412 }
1413}
1414
1415#[derive(Copy, Clone, PartialEq, Eq)]
1416pub struct AnyWindowHandle {
1417 pub(crate) id: WindowId,
1418 state_type: TypeId,
1419}
1420
1421#[cfg(any(test, feature = "test"))]
1422impl From<SmallVec<[u32; 16]>> for StackingOrder {
1423 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
1424 StackingOrder(small_vec)
1425 }
1426}
1427
1428#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1429pub enum ElementId {
1430 View(EntityId),
1431 Number(usize),
1432 Name(SharedString),
1433}
1434
1435impl From<EntityId> for ElementId {
1436 fn from(id: EntityId) -> Self {
1437 ElementId::View(id)
1438 }
1439}
1440
1441impl From<usize> for ElementId {
1442 fn from(id: usize) -> Self {
1443 ElementId::Number(id)
1444 }
1445}
1446
1447impl From<i32> for ElementId {
1448 fn from(id: i32) -> Self {
1449 Self::Number(id as usize)
1450 }
1451}
1452
1453impl From<SharedString> for ElementId {
1454 fn from(name: SharedString) -> Self {
1455 ElementId::Name(name)
1456 }
1457}
1458
1459impl From<&'static str> for ElementId {
1460 fn from(name: &'static str) -> Self {
1461 ElementId::Name(name.into())
1462 }
1463}