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, FocusListener, FontId, GlobalElementId, GlyphId, Handle, Hsla,
5 ImageData, InputEvent, IsZero, KeyDownEvent, KeyDownListener, KeyUpEvent, KeyUpListener,
6 LayoutId, MainThread, MainThreadOnly, MonochromeSprite, MouseMoveEvent, Path, Pixels, Platform,
7 PlatformAtlas, PlatformWindow, Point, PolychromeSprite, Quad, Reference, RenderGlyphParams,
8 RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size,
9 Style, Subscription, TaffyLayoutEngine, Task, Underline, UnderlineStyle, WeakHandle,
10 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 AnyMouseEventListener =
49 Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>;
50type AnyKeyboardEventListener =
51 Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>;
52type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + Send + Sync + 'static>;
53type AnyKeyDownListener =
54 Box<dyn Fn(&KeyDownEvent, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>;
55type AnyKeyUpListener =
56 Box<dyn Fn(&KeyUpEvent, DispatchPhase, &mut WindowContext) + Send + Sync + 'static>;
57
58slotmap::new_key_type! { pub struct FocusId; }
59
60pub struct FocusHandle {
61 pub(crate) id: FocusId,
62 handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
63}
64
65impl FocusHandle {
66 pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
67 let id = handles.write().insert(AtomicUsize::new(1));
68 Self {
69 id,
70 handles: handles.clone(),
71 }
72 }
73
74 pub(crate) fn for_id(
75 id: FocusId,
76 handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
77 ) -> Option<Self> {
78 let lock = handles.read();
79 let ref_count = lock.get(id)?;
80 if ref_count.load(SeqCst) == 0 {
81 None
82 } else {
83 ref_count.fetch_add(1, SeqCst);
84 Some(Self {
85 id,
86 handles: handles.clone(),
87 })
88 }
89 }
90
91 pub fn is_focused(&self, cx: &WindowContext) -> bool {
92 cx.window.focus == Some(self.id)
93 }
94
95 pub fn contains_focused(&self, cx: &WindowContext) -> bool {
96 cx.focused()
97 .map_or(false, |focused| self.contains(&focused, cx))
98 }
99
100 pub fn within_focused(&self, cx: &WindowContext) -> bool {
101 let focused = cx.focused();
102 focused.map_or(false, |focused| focused.contains(self, cx))
103 }
104
105 pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
106 let mut ancestor = Some(other.id);
107 while let Some(ancestor_id) = ancestor {
108 if self.id == ancestor_id {
109 return true;
110 } else {
111 ancestor = cx.window.focus_parents_by_child.get(&ancestor_id).copied();
112 }
113 }
114 false
115 }
116}
117
118impl Clone for FocusHandle {
119 fn clone(&self) -> Self {
120 Self::for_id(self.id, &self.handles).unwrap()
121 }
122}
123
124impl PartialEq for FocusHandle {
125 fn eq(&self, other: &Self) -> bool {
126 self.id == other.id
127 }
128}
129
130impl Eq for FocusHandle {}
131
132impl Drop for FocusHandle {
133 fn drop(&mut self) {
134 self.handles
135 .read()
136 .get(self.id)
137 .unwrap()
138 .fetch_sub(1, SeqCst);
139 }
140}
141
142pub struct Window {
143 handle: AnyWindowHandle,
144 platform_window: MainThreadOnly<Box<dyn PlatformWindow>>,
145 display_id: DisplayId,
146 sprite_atlas: Arc<dyn PlatformAtlas>,
147 rem_size: Pixels,
148 content_size: Size<Pixels>,
149 layout_engine: TaffyLayoutEngine,
150 pub(crate) root_view: Option<AnyView>,
151 pub(crate) element_id_stack: GlobalElementId,
152 prev_element_states: HashMap<GlobalElementId, AnyBox>,
153 element_states: HashMap<GlobalElementId, AnyBox>,
154 z_index_stack: StackingOrder,
155 content_mask_stack: Vec<ContentMask<Pixels>>,
156 mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyMouseEventListener)>>,
157 keyboard_listeners: HashMap<TypeId, Vec<AnyKeyboardEventListener>>,
158 focus_stack: Vec<FocusStackFrame>,
159 focus_parents_by_child: HashMap<FocusId, FocusId>,
160 pub(crate) focus_listeners: Vec<AnyFocusListener>,
161 pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
162 propagate_event: bool,
163 mouse_position: Point<Pixels>,
164 scale_factor: f32,
165 pub(crate) scene_builder: SceneBuilder,
166 pub(crate) dirty: bool,
167 pub(crate) last_blur: Option<Option<FocusId>>,
168 pub(crate) focus: Option<FocusId>,
169}
170
171impl Window {
172 pub fn new(
173 handle: AnyWindowHandle,
174 options: WindowOptions,
175 cx: &mut MainThread<AppContext>,
176 ) -> Self {
177 let platform_window = cx.platform().open_window(handle, options);
178 let display_id = platform_window.display().id();
179 let sprite_atlas = platform_window.sprite_atlas();
180 let mouse_position = platform_window.mouse_position();
181 let content_size = platform_window.content_size();
182 let scale_factor = platform_window.scale_factor();
183 platform_window.on_resize(Box::new({
184 let cx = cx.to_async();
185 move |content_size, scale_factor| {
186 cx.update_window(handle, |cx| {
187 cx.window.scale_factor = scale_factor;
188 cx.window.scene_builder = SceneBuilder::new();
189 cx.window.content_size = content_size;
190 cx.window.display_id = cx
191 .window
192 .platform_window
193 .borrow_on_main_thread()
194 .display()
195 .id();
196 cx.window.dirty = true;
197 })
198 .log_err();
199 }
200 }));
201
202 platform_window.on_input({
203 let cx = cx.to_async();
204 Box::new(move |event| {
205 cx.update_window(handle, |cx| cx.dispatch_event(event))
206 .log_err()
207 .unwrap_or(true)
208 })
209 });
210
211 let platform_window = MainThreadOnly::new(Arc::new(platform_window), cx.executor.clone());
212
213 Window {
214 handle,
215 platform_window,
216 display_id,
217 sprite_atlas,
218 rem_size: px(16.),
219 content_size,
220 layout_engine: TaffyLayoutEngine::new(),
221 root_view: None,
222 element_id_stack: GlobalElementId::default(),
223 prev_element_states: HashMap::default(),
224 element_states: HashMap::default(),
225 z_index_stack: StackingOrder(SmallVec::new()),
226 content_mask_stack: Vec::new(),
227 mouse_listeners: HashMap::default(),
228 keyboard_listeners: HashMap::default(),
229 focus_stack: Vec::new(),
230 focus_parents_by_child: HashMap::default(),
231 focus_listeners: Vec::new(),
232 propagate_event: true,
233 mouse_position,
234 scale_factor,
235 scene_builder: SceneBuilder::new(),
236 dirty: true,
237 focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
238 last_blur: None,
239 focus: None,
240 }
241 }
242}
243
244#[derive(Clone, Debug, Default, PartialEq, Eq)]
245#[repr(C)]
246pub struct ContentMask<P: Clone + Default + Debug> {
247 pub bounds: Bounds<P>,
248}
249
250impl ContentMask<Pixels> {
251 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
252 ContentMask {
253 bounds: self.bounds.scale(factor),
254 }
255 }
256
257 pub fn intersect(&self, other: &Self) -> Self {
258 let bounds = self.bounds.intersect(&other.bounds);
259 ContentMask { bounds }
260 }
261}
262
263struct FocusStackFrame {
264 handle: FocusHandle,
265 key_down_listeners: SmallVec<[AnyKeyDownListener; 2]>,
266 key_up_listeners: SmallVec<[AnyKeyUpListener; 2]>,
267}
268
269pub struct WindowContext<'a, 'w> {
270 app: Reference<'a, AppContext>,
271 pub(crate) window: Reference<'w, Window>,
272}
273
274impl<'a, 'w> WindowContext<'a, 'w> {
275 pub(crate) fn mutable(app: &'a mut AppContext, window: &'w mut Window) -> Self {
276 Self {
277 app: Reference::Mutable(app),
278 window: Reference::Mutable(window),
279 }
280 }
281
282 pub fn notify(&mut self) {
283 self.window.dirty = true;
284 }
285
286 pub fn focus_handle(&mut self) -> FocusHandle {
287 FocusHandle::new(&self.window.focus_handles)
288 }
289
290 pub fn focused(&self) -> Option<FocusHandle> {
291 self.window
292 .focus
293 .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
294 }
295
296 pub fn focus(&mut self, handle: &FocusHandle) {
297 if self.window.last_blur.is_none() {
298 self.window.last_blur = Some(self.window.focus);
299 }
300
301 let window_id = self.window.handle.id;
302 self.window.focus = Some(handle.id);
303 self.push_effect(Effect::FocusChanged {
304 window_id,
305 focused: Some(handle.id),
306 });
307 self.notify();
308 }
309
310 pub fn blur(&mut self) {
311 if self.window.last_blur.is_none() {
312 self.window.last_blur = Some(self.window.focus);
313 }
314
315 let window_id = self.window.handle.id;
316 self.window.focus = None;
317 self.push_effect(Effect::FocusChanged {
318 window_id,
319 focused: None,
320 });
321 self.notify();
322 }
323
324 pub fn run_on_main<R>(
325 &mut self,
326 f: impl FnOnce(&mut MainThread<WindowContext<'_, '_>>) -> R + Send + 'static,
327 ) -> Task<Result<R>>
328 where
329 R: Send + 'static,
330 {
331 if self.executor.is_main_thread() {
332 Task::ready(Ok(f(unsafe {
333 mem::transmute::<&mut Self, &mut MainThread<Self>>(self)
334 })))
335 } else {
336 let id = self.window.handle.id;
337 self.app.run_on_main(move |cx| cx.update_window(id, f))
338 }
339 }
340
341 pub fn to_async(&self) -> AsyncWindowContext {
342 AsyncWindowContext::new(self.app.to_async(), self.window.handle)
343 }
344
345 pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
346 let f = Box::new(f);
347 let display_id = self.window.display_id;
348 self.run_on_main(move |cx| {
349 if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {
350 callbacks.push(f);
351 // If there was already a callback, it means that we already scheduled a frame.
352 if callbacks.len() > 1 {
353 return;
354 }
355 } else {
356 let async_cx = cx.to_async();
357 cx.next_frame_callbacks.insert(display_id, vec![f]);
358 cx.platform().set_display_link_output_callback(
359 display_id,
360 Box::new(move |_current_time, _output_time| {
361 let _ = async_cx.update(|cx| {
362 let callbacks = cx
363 .next_frame_callbacks
364 .get_mut(&display_id)
365 .unwrap()
366 .drain(..)
367 .collect::<Vec<_>>();
368 for callback in callbacks {
369 callback(cx);
370 }
371
372 cx.run_on_main(move |cx| {
373 if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
374 cx.platform().stop_display_link(display_id);
375 }
376 })
377 .detach();
378 });
379 }),
380 );
381 }
382
383 cx.platform().start_display_link(display_id);
384 })
385 .detach();
386 }
387
388 pub fn spawn<Fut, R>(
389 &mut self,
390 f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut + Send + 'static,
391 ) -> Task<R>
392 where
393 R: Send + 'static,
394 Fut: Future<Output = R> + Send + 'static,
395 {
396 let window = self.window.handle;
397 self.app.spawn(move |app| {
398 let cx = AsyncWindowContext::new(app, window);
399 let future = f(window, cx);
400 async move { future.await }
401 })
402 }
403
404 pub fn request_layout(
405 &mut self,
406 style: &Style,
407 children: impl IntoIterator<Item = LayoutId>,
408 ) -> LayoutId {
409 self.app.layout_id_buffer.clear();
410 self.app.layout_id_buffer.extend(children.into_iter());
411 let rem_size = self.rem_size();
412
413 self.window
414 .layout_engine
415 .request_layout(style, rem_size, &self.app.layout_id_buffer)
416 }
417
418 pub fn request_measured_layout<
419 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
420 >(
421 &mut self,
422 style: Style,
423 rem_size: Pixels,
424 measure: F,
425 ) -> LayoutId {
426 self.window
427 .layout_engine
428 .request_measured_layout(style, rem_size, measure)
429 }
430
431 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
432 self.window
433 .layout_engine
434 .layout_bounds(layout_id)
435 .map(Into::into)
436 }
437
438 pub fn scale_factor(&self) -> f32 {
439 self.window.scale_factor
440 }
441
442 pub fn rem_size(&self) -> Pixels {
443 self.window.rem_size
444 }
445
446 pub fn stop_propagation(&mut self) {
447 self.window.propagate_event = false;
448 }
449
450 pub fn on_mouse_event<Event: 'static>(
451 &mut self,
452 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + Sync + 'static,
453 ) {
454 let order = self.window.z_index_stack.clone();
455 self.window
456 .mouse_listeners
457 .entry(TypeId::of::<Event>())
458 .or_default()
459 .push((
460 order,
461 Box::new(move |event: &dyn Any, phase, cx| {
462 handler(event.downcast_ref().unwrap(), phase, cx)
463 }),
464 ))
465 }
466
467 pub fn on_keyboard_event<Event: 'static>(
468 &mut self,
469 handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + Sync + 'static,
470 ) {
471 self.window
472 .keyboard_listeners
473 .entry(TypeId::of::<Event>())
474 .or_default()
475 .push(Box::new(move |event: &dyn Any, phase, cx| {
476 handler(event.downcast_ref().unwrap(), phase, cx)
477 }))
478 }
479
480 pub fn mouse_position(&self) -> Point<Pixels> {
481 self.window.mouse_position
482 }
483
484 pub fn stack<R>(&mut self, order: u32, f: impl FnOnce(&mut Self) -> R) -> R {
485 self.window.z_index_stack.push(order);
486 let result = f(self);
487 self.window.z_index_stack.pop();
488 result
489 }
490
491 pub fn paint_shadows(
492 &mut self,
493 bounds: Bounds<Pixels>,
494 corner_radii: Corners<Pixels>,
495 shadows: &[BoxShadow],
496 ) {
497 let scale_factor = self.scale_factor();
498 let content_mask = self.content_mask();
499 let window = &mut *self.window;
500 for shadow in shadows {
501 let mut shadow_bounds = bounds;
502 shadow_bounds.origin += shadow.offset;
503 shadow_bounds.dilate(shadow.spread_radius);
504 window.scene_builder.insert(
505 &window.z_index_stack,
506 Shadow {
507 order: 0,
508 bounds: shadow_bounds.scale(scale_factor),
509 content_mask: content_mask.scale(scale_factor),
510 corner_radii: corner_radii.scale(scale_factor),
511 color: shadow.color,
512 blur_radius: shadow.blur_radius.scale(scale_factor),
513 },
514 );
515 }
516 }
517
518 pub fn paint_quad(
519 &mut self,
520 bounds: Bounds<Pixels>,
521 corner_radii: Corners<Pixels>,
522 background: impl Into<Hsla>,
523 border_widths: Edges<Pixels>,
524 border_color: impl Into<Hsla>,
525 ) {
526 let scale_factor = self.scale_factor();
527 let content_mask = self.content_mask();
528
529 let window = &mut *self.window;
530 window.scene_builder.insert(
531 &window.z_index_stack,
532 Quad {
533 order: 0,
534 bounds: bounds.scale(scale_factor),
535 content_mask: content_mask.scale(scale_factor),
536 background: background.into(),
537 border_color: border_color.into(),
538 corner_radii: corner_radii.scale(scale_factor),
539 border_widths: border_widths.scale(scale_factor),
540 },
541 );
542 }
543
544 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
545 let scale_factor = self.scale_factor();
546 let content_mask = self.content_mask();
547 path.content_mask = content_mask;
548 path.color = color.into();
549 let window = &mut *self.window;
550 window
551 .scene_builder
552 .insert(&window.z_index_stack, path.scale(scale_factor));
553 }
554
555 pub fn paint_underline(
556 &mut self,
557 origin: Point<Pixels>,
558 width: Pixels,
559 style: &UnderlineStyle,
560 ) -> Result<()> {
561 let scale_factor = self.scale_factor();
562 let height = if style.wavy {
563 style.thickness * 3.
564 } else {
565 style.thickness
566 };
567 let bounds = Bounds {
568 origin,
569 size: size(width, height),
570 };
571 let content_mask = self.content_mask();
572 let window = &mut *self.window;
573 window.scene_builder.insert(
574 &window.z_index_stack,
575 Underline {
576 order: 0,
577 bounds: bounds.scale(scale_factor),
578 content_mask: content_mask.scale(scale_factor),
579 thickness: style.thickness.scale(scale_factor),
580 color: style.color.unwrap_or_default(),
581 wavy: style.wavy,
582 },
583 );
584 Ok(())
585 }
586
587 pub fn paint_glyph(
588 &mut self,
589 origin: Point<Pixels>,
590 font_id: FontId,
591 glyph_id: GlyphId,
592 font_size: Pixels,
593 color: Hsla,
594 ) -> Result<()> {
595 let scale_factor = self.scale_factor();
596 let glyph_origin = origin.scale(scale_factor);
597 let subpixel_variant = Point {
598 x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
599 y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
600 };
601 let params = RenderGlyphParams {
602 font_id,
603 glyph_id,
604 font_size,
605 subpixel_variant,
606 scale_factor,
607 is_emoji: false,
608 };
609
610 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
611 if !raster_bounds.is_zero() {
612 let tile =
613 self.window
614 .sprite_atlas
615 .get_or_insert_with(¶ms.clone().into(), &mut || {
616 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
617 Ok((size, Cow::Owned(bytes)))
618 })?;
619 let bounds = Bounds {
620 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
621 size: tile.bounds.size.map(Into::into),
622 };
623 let content_mask = self.content_mask().scale(scale_factor);
624 let window = &mut *self.window;
625 window.scene_builder.insert(
626 &window.z_index_stack,
627 MonochromeSprite {
628 order: 0,
629 bounds,
630 content_mask,
631 color,
632 tile,
633 },
634 );
635 }
636 Ok(())
637 }
638
639 pub fn paint_emoji(
640 &mut self,
641 origin: Point<Pixels>,
642 font_id: FontId,
643 glyph_id: GlyphId,
644 font_size: Pixels,
645 ) -> Result<()> {
646 let scale_factor = self.scale_factor();
647 let glyph_origin = origin.scale(scale_factor);
648 let params = RenderGlyphParams {
649 font_id,
650 glyph_id,
651 font_size,
652 // We don't render emojis with subpixel variants.
653 subpixel_variant: Default::default(),
654 scale_factor,
655 is_emoji: true,
656 };
657
658 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
659 if !raster_bounds.is_zero() {
660 let tile =
661 self.window
662 .sprite_atlas
663 .get_or_insert_with(¶ms.clone().into(), &mut || {
664 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
665 Ok((size, Cow::Owned(bytes)))
666 })?;
667 let bounds = Bounds {
668 origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
669 size: tile.bounds.size.map(Into::into),
670 };
671 let content_mask = self.content_mask().scale(scale_factor);
672 let window = &mut *self.window;
673
674 window.scene_builder.insert(
675 &window.z_index_stack,
676 PolychromeSprite {
677 order: 0,
678 bounds,
679 corner_radii: Default::default(),
680 content_mask,
681 tile,
682 grayscale: false,
683 },
684 );
685 }
686 Ok(())
687 }
688
689 pub fn paint_svg(
690 &mut self,
691 bounds: Bounds<Pixels>,
692 path: SharedString,
693 color: Hsla,
694 ) -> Result<()> {
695 let scale_factor = self.scale_factor();
696 let bounds = bounds.scale(scale_factor);
697 // Render the SVG at twice the size to get a higher quality result.
698 let params = RenderSvgParams {
699 path,
700 size: bounds
701 .size
702 .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
703 };
704
705 let tile =
706 self.window
707 .sprite_atlas
708 .get_or_insert_with(¶ms.clone().into(), &mut || {
709 let bytes = self.svg_renderer.render(¶ms)?;
710 Ok((params.size, Cow::Owned(bytes)))
711 })?;
712 let content_mask = self.content_mask().scale(scale_factor);
713
714 let window = &mut *self.window;
715 window.scene_builder.insert(
716 &window.z_index_stack,
717 MonochromeSprite {
718 order: 0,
719 bounds,
720 content_mask,
721 color,
722 tile,
723 },
724 );
725
726 Ok(())
727 }
728
729 pub fn paint_image(
730 &mut self,
731 bounds: Bounds<Pixels>,
732 corner_radii: Corners<Pixels>,
733 data: Arc<ImageData>,
734 grayscale: bool,
735 ) -> Result<()> {
736 let scale_factor = self.scale_factor();
737 let bounds = bounds.scale(scale_factor);
738 let params = RenderImageParams { image_id: data.id };
739
740 let tile = self
741 .window
742 .sprite_atlas
743 .get_or_insert_with(¶ms.clone().into(), &mut || {
744 Ok((data.size(), Cow::Borrowed(data.as_bytes())))
745 })?;
746 let content_mask = self.content_mask().scale(scale_factor);
747 let corner_radii = corner_radii.scale(scale_factor);
748
749 let window = &mut *self.window;
750 window.scene_builder.insert(
751 &window.z_index_stack,
752 PolychromeSprite {
753 order: 0,
754 bounds,
755 content_mask,
756 corner_radii,
757 tile,
758 grayscale,
759 },
760 );
761 Ok(())
762 }
763
764 pub(crate) fn draw(&mut self) {
765 let unit_entity = self.unit_entity.clone();
766 self.update_entity(&unit_entity, |view, cx| {
767 cx.start_frame();
768
769 let mut root_view = cx.window.root_view.take().unwrap();
770
771 if let Some(element_id) = root_view.id() {
772 cx.with_element_state(element_id, |element_state, cx| {
773 let element_state = draw_with_element_state(&mut root_view, element_state, cx);
774 ((), element_state)
775 });
776 } else {
777 draw_with_element_state(&mut root_view, None, cx);
778 };
779
780 cx.window.root_view = Some(root_view);
781 let scene = cx.window.scene_builder.build();
782 cx.end_frame();
783
784 cx.run_on_main(view, |_, cx| {
785 cx.window
786 .platform_window
787 .borrow_on_main_thread()
788 .draw(scene);
789 cx.window.dirty = false;
790 })
791 .detach();
792 });
793
794 fn draw_with_element_state(
795 root_view: &mut AnyView,
796 element_state: Option<AnyBox>,
797 cx: &mut ViewContext<()>,
798 ) -> AnyBox {
799 let mut element_state = root_view.initialize(&mut (), element_state, cx);
800 let layout_id = root_view.layout(&mut (), &mut element_state, cx);
801 let available_space = cx.window.content_size.map(Into::into);
802 cx.window
803 .layout_engine
804 .compute_layout(layout_id, available_space);
805 let bounds = cx.window.layout_engine.layout_bounds(layout_id);
806 root_view.paint(bounds, &mut (), &mut element_state, cx);
807 element_state
808 }
809 }
810
811 fn start_frame(&mut self) {
812 // Make the current element states the previous, and then clear the current.
813 // The empty element states map will be populated for any element states we
814 // reference during the upcoming frame.
815 let window = &mut *self.window;
816 mem::swap(&mut window.element_states, &mut window.prev_element_states);
817 window.element_states.clear();
818
819 // Clear mouse event listeners, because elements add new element listeners
820 // when the upcoming frame is painted.
821 window.mouse_listeners.values_mut().for_each(Vec::clear);
822
823 // Clear focus state, because we determine what is focused when the new elements
824 // in the upcoming frame are initialized.
825 window.focus_listeners.clear();
826 window.keyboard_listeners.values_mut().for_each(Vec::clear);
827 window.focus_parents_by_child.clear();
828 }
829
830 fn end_frame(&mut self) {
831 self.text_system().end_frame();
832 }
833
834 fn dispatch_event(&mut self, event: InputEvent) -> bool {
835 if let Some(any_mouse_event) = event.mouse_event() {
836 if let Some(MouseMoveEvent { position, .. }) = any_mouse_event.downcast_ref() {
837 self.window.mouse_position = *position;
838 }
839
840 if let Some(mut handlers) = self
841 .window
842 .mouse_listeners
843 .remove(&any_mouse_event.type_id())
844 {
845 // Because handlers may add other handlers, we sort every time.
846 handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
847
848 // Handlers may set this to false by calling `stop_propagation`
849 self.window.propagate_event = true;
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 .keyboard_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 .keyboard_listeners
907 .get_mut(&any_keyboard_event.type_id())
908 .into_iter()
909 .flat_map(|handlers| handlers.drain(..)),
910 );
911 self.window
912 .keyboard_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 with_focus<R>(
1211 &mut self,
1212 focus_handle: Option<FocusHandle>,
1213 key_down: impl IntoIterator<Item = KeyDownListener<V>>,
1214 key_up: impl IntoIterator<Item = KeyUpListener<V>>,
1215 focus: impl IntoIterator<Item = FocusListener<V>>,
1216 f: impl FnOnce(&mut Self) -> R,
1217 ) -> R {
1218 let Some(focus_handle) = focus_handle else {
1219 return f(self);
1220 };
1221
1222 let handle = self.handle();
1223 let window = &mut *self.window;
1224
1225 for listener in focus {
1226 let handle = handle.clone();
1227 window.focus_listeners.push(Box::new(move |event, cx| {
1228 handle
1229 .update(cx, |view, cx| listener(view, event, cx))
1230 .log_err();
1231 }));
1232 }
1233
1234 let mut focus_stack = mem::take(&mut window.focus_stack);
1235 if let Some(parent_frame) = focus_stack.last() {
1236 window
1237 .focus_parents_by_child
1238 .insert(focus_handle.id, parent_frame.handle.id);
1239 }
1240
1241 let mut frame = FocusStackFrame {
1242 handle: focus_handle.clone(),
1243 key_down_listeners: SmallVec::new(),
1244 key_up_listeners: SmallVec::new(),
1245 };
1246
1247 for listener in key_down {
1248 let handle = handle.clone();
1249 frame
1250 .key_down_listeners
1251 .push(Box::new(move |event, phase, cx| {
1252 handle
1253 .update(cx, |view, cx| listener(view, event, phase, cx))
1254 .log_err();
1255 }));
1256 }
1257 for listener in key_up {
1258 let handle = handle.clone();
1259 frame
1260 .key_up_listeners
1261 .push(Box::new(move |event, phase, cx| {
1262 handle
1263 .update(cx, |view, cx| listener(view, event, phase, cx))
1264 .log_err();
1265 }));
1266 }
1267 focus_stack.push(frame);
1268
1269 if Some(focus_handle.id) == window.focus {
1270 for focus_frame in &mut focus_stack {
1271 for listener in focus_frame.key_down_listeners.drain(..) {
1272 self.window_cx.on_keyboard_event(listener);
1273 }
1274 for listener in focus_frame.key_up_listeners.drain(..) {
1275 self.window_cx.on_keyboard_event(listener);
1276 }
1277 }
1278 }
1279
1280 self.window.focus_stack = focus_stack;
1281 let result = f(self);
1282 self.window.focus_stack.pop();
1283 result
1284 }
1285
1286 pub fn run_on_main<R>(
1287 &mut self,
1288 view: &mut V,
1289 f: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, '_, V>>) -> R + Send + 'static,
1290 ) -> Task<Result<R>>
1291 where
1292 R: Send + 'static,
1293 {
1294 if self.executor.is_main_thread() {
1295 let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
1296 Task::ready(Ok(f(view, cx)))
1297 } else {
1298 let handle = self.handle().upgrade(self).unwrap();
1299 self.window_cx.run_on_main(move |cx| handle.update(cx, f))
1300 }
1301 }
1302
1303 pub fn spawn<Fut, R>(
1304 &mut self,
1305 f: impl FnOnce(WeakHandle<V>, AsyncWindowContext) -> Fut + Send + 'static,
1306 ) -> Task<R>
1307 where
1308 R: Send + 'static,
1309 Fut: Future<Output = R> + Send + 'static,
1310 {
1311 let handle = self.handle();
1312 self.window_cx.spawn(move |_, cx| {
1313 let result = f(handle, cx);
1314 async move { result.await }
1315 })
1316 }
1317
1318 pub fn on_mouse_event<Event: 'static>(
1319 &mut self,
1320 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + Sync + 'static,
1321 ) {
1322 let handle = self.handle().upgrade(self).unwrap();
1323 self.window_cx.on_mouse_event(move |event, phase, cx| {
1324 handle.update(cx, |view, cx| {
1325 handler(view, event, phase, cx);
1326 })
1327 });
1328 }
1329
1330 pub fn on_keyboard_event<Event: 'static>(
1331 &mut self,
1332 handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + Sync + 'static,
1333 ) {
1334 let handle = self.handle().upgrade(self).unwrap();
1335 self.window_cx.on_keyboard_event(move |event, phase, cx| {
1336 handle.update(cx, |view, cx| {
1337 handler(view, event, phase, cx);
1338 })
1339 });
1340 }
1341}
1342
1343impl<'a, 'w, S: EventEmitter + Send + Sync + 'static> ViewContext<'a, 'w, S> {
1344 pub fn emit(&mut self, event: S::Event) {
1345 self.window_cx.app.push_effect(Effect::Emit {
1346 emitter: self.entity_id,
1347 event: Box::new(event),
1348 });
1349 }
1350}
1351
1352impl<'a, 'w, S> Context for ViewContext<'a, 'w, S> {
1353 type EntityContext<'b, 'c, U: 'static + Send + Sync> = ViewContext<'b, 'c, U>;
1354 type Result<U> = U;
1355
1356 fn entity<T2: Send + Sync + 'static>(
1357 &mut self,
1358 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T2>) -> T2,
1359 ) -> Handle<T2> {
1360 self.window_cx.entity(build_entity)
1361 }
1362
1363 fn update_entity<U: Send + Sync + 'static, R>(
1364 &mut self,
1365 handle: &Handle<U>,
1366 update: impl FnOnce(&mut U, &mut Self::EntityContext<'_, '_, U>) -> R,
1367 ) -> R {
1368 self.window_cx.update_entity(handle, update)
1369 }
1370}
1371
1372impl<'a, 'w, S: 'static> std::ops::Deref for ViewContext<'a, 'w, S> {
1373 type Target = WindowContext<'a, 'w>;
1374
1375 fn deref(&self) -> &Self::Target {
1376 &self.window_cx
1377 }
1378}
1379
1380impl<'a, 'w, S: 'static> std::ops::DerefMut for ViewContext<'a, 'w, S> {
1381 fn deref_mut(&mut self) -> &mut Self::Target {
1382 &mut self.window_cx
1383 }
1384}
1385
1386// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
1387slotmap::new_key_type! { pub struct WindowId; }
1388
1389#[derive(PartialEq, Eq)]
1390pub struct WindowHandle<S> {
1391 id: WindowId,
1392 state_type: PhantomData<S>,
1393}
1394
1395impl<S> Copy for WindowHandle<S> {}
1396
1397impl<S> Clone for WindowHandle<S> {
1398 fn clone(&self) -> Self {
1399 WindowHandle {
1400 id: self.id,
1401 state_type: PhantomData,
1402 }
1403 }
1404}
1405
1406impl<S> WindowHandle<S> {
1407 pub fn new(id: WindowId) -> Self {
1408 WindowHandle {
1409 id,
1410 state_type: PhantomData,
1411 }
1412 }
1413}
1414
1415impl<S: 'static> Into<AnyWindowHandle> for WindowHandle<S> {
1416 fn into(self) -> AnyWindowHandle {
1417 AnyWindowHandle {
1418 id: self.id,
1419 state_type: TypeId::of::<S>(),
1420 }
1421 }
1422}
1423
1424#[derive(Copy, Clone, PartialEq, Eq)]
1425pub struct AnyWindowHandle {
1426 pub(crate) id: WindowId,
1427 state_type: TypeId,
1428}
1429
1430#[cfg(any(test, feature = "test"))]
1431impl From<SmallVec<[u32; 16]>> for StackingOrder {
1432 fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
1433 StackingOrder(small_vec)
1434 }
1435}
1436
1437#[derive(Clone, Debug, Eq, PartialEq, Hash)]
1438pub enum ElementId {
1439 View(EntityId),
1440 Number(usize),
1441 Name(SharedString),
1442}
1443
1444impl From<EntityId> for ElementId {
1445 fn from(id: EntityId) -> Self {
1446 ElementId::View(id)
1447 }
1448}
1449
1450impl From<usize> for ElementId {
1451 fn from(id: usize) -> Self {
1452 ElementId::Number(id)
1453 }
1454}
1455
1456impl From<i32> for ElementId {
1457 fn from(id: i32) -> Self {
1458 Self::Number(id as usize)
1459 }
1460}
1461
1462impl From<SharedString> for ElementId {
1463 fn from(name: SharedString) -> Self {
1464 ElementId::Name(name)
1465 }
1466}
1467
1468impl From<&'static str> for ElementId {
1469 fn from(name: &'static str) -> Self {
1470 ElementId::Name(name.into())
1471 }
1472}