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