1use crate::{
2 app::{AppContext, MutableAppContext, WindowInvalidation},
3 elements::Element,
4 font_cache::FontCache,
5 geometry::rect::RectF,
6 json::{self, ToJson},
7 keymap::Keystroke,
8 platform::{CursorStyle, Event},
9 scene::{CursorRegion, MouseRegionEvent},
10 text_layout::TextLayoutCache,
11 Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox, Entity,
12 FontSystem, ModelHandle, MouseButtonEvent, MouseMovedEvent, MouseRegion, MouseRegionId,
13 ParentId, ReadModel, ReadView, RenderContext, RenderParams, Scene, UpgradeModelHandle,
14 UpgradeViewHandle, View, ViewHandle, WeakModelHandle, WeakViewHandle,
15};
16use collections::{HashMap, HashSet};
17use pathfinder_geometry::vector::{vec2f, Vector2F};
18use serde_json::json;
19use smallvec::SmallVec;
20use std::{
21 marker::PhantomData,
22 ops::{Deref, DerefMut, Range},
23 sync::Arc,
24};
25
26pub struct Presenter {
27 window_id: usize,
28 pub(crate) rendered_views: HashMap<usize, ElementBox>,
29 cursor_regions: Vec<CursorRegion>,
30 mouse_regions: Vec<(MouseRegion, usize)>,
31 font_cache: Arc<FontCache>,
32 text_layout_cache: TextLayoutCache,
33 asset_cache: Arc<AssetCache>,
34 last_mouse_moved_event: Option<Event>,
35 hovered_region_ids: HashSet<MouseRegionId>,
36 clicked_region: Option<MouseRegion>,
37 right_clicked_region: Option<MouseRegion>,
38 prev_drag_position: Option<Vector2F>,
39 titlebar_height: f32,
40}
41
42impl Presenter {
43 pub fn new(
44 window_id: usize,
45 titlebar_height: f32,
46 font_cache: Arc<FontCache>,
47 text_layout_cache: TextLayoutCache,
48 asset_cache: Arc<AssetCache>,
49 cx: &mut MutableAppContext,
50 ) -> Self {
51 Self {
52 window_id,
53 rendered_views: cx.render_views(window_id, titlebar_height),
54 cursor_regions: Default::default(),
55 mouse_regions: Default::default(),
56 font_cache,
57 text_layout_cache,
58 asset_cache,
59 last_mouse_moved_event: None,
60 hovered_region_ids: Default::default(),
61 clicked_region: None,
62 right_clicked_region: None,
63 prev_drag_position: None,
64 titlebar_height,
65 }
66 }
67
68 // pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
69 // let mut path = Vec::new();
70 // if let Some(view_id) = app.focused_view_id(self.window_id) {
71 // self.compute_dispatch_path_from(view_id, &mut path)
72 // }
73 // path
74 // }
75
76 // pub(crate) fn compute_dispatch_path_from(&self, mut view_id: usize, path: &mut Vec<usize>) {
77 // path.push(view_id);
78 // while let Some(parent_id) = self.parents.get(&view_id).copied() {
79 // path.push(parent_id);
80 // view_id = parent_id;
81 // }
82 // path.reverse();
83 // }
84
85 pub fn invalidate(
86 &mut self,
87 invalidation: &mut WindowInvalidation,
88 cx: &mut MutableAppContext,
89 ) {
90 cx.start_frame();
91 for view_id in &invalidation.removed {
92 invalidation.updated.remove(&view_id);
93 self.rendered_views.remove(&view_id);
94 }
95 for view_id in &invalidation.updated {
96 self.rendered_views.insert(
97 *view_id,
98 cx.render_view(RenderParams {
99 window_id: self.window_id,
100 view_id: *view_id,
101 titlebar_height: self.titlebar_height,
102 hovered_region_ids: self.hovered_region_ids.clone(),
103 clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
104 right_clicked_region_id: self
105 .right_clicked_region
106 .as_ref()
107 .and_then(MouseRegion::id),
108 refreshing: false,
109 })
110 .unwrap(),
111 );
112 }
113 }
114
115 pub fn refresh(&mut self, invalidation: &mut WindowInvalidation, cx: &mut MutableAppContext) {
116 self.invalidate(invalidation, cx);
117 for (view_id, view) in &mut self.rendered_views {
118 if !invalidation.updated.contains(view_id) {
119 *view = cx
120 .render_view(RenderParams {
121 window_id: self.window_id,
122 view_id: *view_id,
123 titlebar_height: self.titlebar_height,
124 hovered_region_ids: self.hovered_region_ids.clone(),
125 clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
126 right_clicked_region_id: self
127 .right_clicked_region
128 .as_ref()
129 .and_then(MouseRegion::id),
130 refreshing: true,
131 })
132 .unwrap();
133 }
134 }
135 }
136
137 pub fn build_scene(
138 &mut self,
139 window_size: Vector2F,
140 scale_factor: f32,
141 refreshing: bool,
142 cx: &mut MutableAppContext,
143 ) -> Scene {
144 let mut scene = Scene::new(scale_factor);
145
146 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
147 self.layout(window_size, refreshing, cx);
148 let mut paint_cx = self.build_paint_context(&mut scene, window_size, cx);
149 paint_cx.paint(
150 root_view_id,
151 Vector2F::zero(),
152 RectF::new(Vector2F::zero(), window_size),
153 );
154 self.text_layout_cache.finish_frame();
155 self.cursor_regions = scene.cursor_regions();
156 self.mouse_regions = scene.mouse_regions();
157
158 if cx.window_is_active(self.window_id) {
159 if let Some(event) = self.last_mouse_moved_event.clone() {
160 let mut invalidated_views = Vec::new();
161 self.handle_hover_events(&event, &mut invalidated_views, cx);
162
163 for view_id in invalidated_views {
164 cx.notify_view(self.window_id, view_id);
165 }
166 }
167 }
168 } else {
169 log::error!("could not find root_view_id for window {}", self.window_id);
170 }
171
172 scene
173 }
174
175 fn layout(&mut self, window_size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
176 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
177 self.build_layout_context(window_size, refreshing, cx)
178 .layout(root_view_id, SizeConstraint::strict(window_size));
179 }
180 }
181
182 pub fn build_layout_context<'a>(
183 &'a mut self,
184 window_size: Vector2F,
185 refreshing: bool,
186 cx: &'a mut MutableAppContext,
187 ) -> LayoutContext<'a> {
188 LayoutContext {
189 window_id: self.window_id,
190 rendered_views: &mut self.rendered_views,
191 font_cache: &self.font_cache,
192 font_system: cx.platform().fonts(),
193 text_layout_cache: &self.text_layout_cache,
194 asset_cache: &self.asset_cache,
195 view_stack: Vec::new(),
196 refreshing,
197 hovered_region_ids: self.hovered_region_ids.clone(),
198 clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
199 right_clicked_region_id: self.right_clicked_region.as_ref().and_then(MouseRegion::id),
200 titlebar_height: self.titlebar_height,
201 window_size,
202 app: cx,
203 }
204 }
205
206 pub fn build_paint_context<'a>(
207 &'a mut self,
208 scene: &'a mut Scene,
209 window_size: Vector2F,
210 cx: &'a mut MutableAppContext,
211 ) -> PaintContext {
212 PaintContext {
213 scene,
214 window_size,
215 font_cache: &self.font_cache,
216 text_layout_cache: &self.text_layout_cache,
217 rendered_views: &mut self.rendered_views,
218 view_stack: Vec::new(),
219 app: cx,
220 }
221 }
222
223 pub fn rect_for_text_range(&self, range_utf16: Range<usize>, cx: &AppContext) -> Option<RectF> {
224 cx.focused_view_id(self.window_id).and_then(|view_id| {
225 let cx = MeasurementContext {
226 app: cx,
227 rendered_views: &self.rendered_views,
228 window_id: self.window_id,
229 };
230 cx.rect_for_text_range(view_id, range_utf16)
231 })
232 }
233
234 pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) -> bool {
235 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
236 let mut invalidated_views = Vec::new();
237 let mut mouse_down_out_handlers = Vec::new();
238 let mut mouse_down_region = None;
239 let mut clicked_region = None;
240 let mut dragged_region = None;
241
242 match &event {
243 Event::MouseDown(
244 e @ MouseButtonEvent {
245 position, button, ..
246 },
247 ) => {
248 let mut hit = false;
249 for (region, _) in self.mouse_regions.iter().rev() {
250 if region.bounds.contains_point(*position) {
251 if !hit {
252 hit = true;
253 invalidated_views.push(region.view_id);
254 mouse_down_region =
255 Some((region.clone(), MouseRegionEvent::Down(e.clone())));
256 self.clicked_region = Some(region.clone());
257 self.prev_drag_position = Some(*position);
258 }
259 } else if let Some(handler) = region
260 .handlers
261 .get(&(MouseRegionEvent::down_out_disc(), Some(*button)))
262 {
263 mouse_down_out_handlers.push((
264 handler,
265 region.view_id,
266 MouseRegionEvent::DownOut(e.clone()),
267 ));
268 }
269 }
270 }
271 Event::MouseUp(e @ MouseButtonEvent { position, .. }) => {
272 self.prev_drag_position.take();
273 if let Some(region) = self.clicked_region.take() {
274 invalidated_views.push(region.view_id);
275 if region.bounds.contains_point(*position) {
276 clicked_region = Some((region, MouseRegionEvent::Click(e.clone())));
277 }
278 }
279 }
280 Event::MouseMoved(e @ MouseMovedEvent { position, .. }) => {
281 if let Some((clicked_region, prev_drag_position)) = self
282 .clicked_region
283 .as_ref()
284 .zip(self.prev_drag_position.as_mut())
285 {
286 dragged_region = Some((
287 clicked_region.clone(),
288 MouseRegionEvent::Drag(*prev_drag_position, e.clone()),
289 ));
290 *prev_drag_position = *position;
291 }
292
293 self.last_mouse_moved_event = Some(event.clone());
294 }
295 _ => {}
296 }
297
298 let (mut handled, mut event_cx) =
299 self.handle_hover_events(&event, &mut invalidated_views, cx);
300
301 for (handler, view_id, region_event) in mouse_down_out_handlers {
302 event_cx.with_current_view(view_id, |event_cx| handler(region_event, event_cx))
303 }
304
305 if let Some((mouse_down_region, region_event)) = mouse_down_region {
306 handled = true;
307 if let Some(mouse_down_callback) =
308 mouse_down_region.handlers.get(®ion_event.handler_key())
309 {
310 event_cx.with_current_view(mouse_down_region.view_id, |event_cx| {
311 mouse_down_callback(region_event, event_cx);
312 })
313 }
314 }
315
316 if let Some((clicked_region, region_event)) = clicked_region {
317 handled = true;
318 if let Some(click_callback) =
319 clicked_region.handlers.get(®ion_event.handler_key())
320 {
321 event_cx.with_current_view(clicked_region.view_id, |event_cx| {
322 click_callback(region_event, event_cx);
323 })
324 }
325 }
326
327 if let Some((dragged_region, region_event)) = dragged_region {
328 handled = true;
329 if let Some(drag_callback) =
330 dragged_region.handlers.get(®ion_event.handler_key())
331 {
332 event_cx.with_current_view(dragged_region.view_id, |event_cx| {
333 drag_callback(region_event, event_cx);
334 })
335 }
336 }
337
338 if !handled {
339 handled = event_cx.dispatch_event(root_view_id, &event);
340 }
341
342 invalidated_views.extend(event_cx.invalidated_views);
343
344 for view_id in invalidated_views {
345 cx.notify_view(self.window_id, view_id);
346 }
347
348 handled
349 } else {
350 false
351 }
352 }
353
354 fn handle_hover_events<'a>(
355 &'a mut self,
356 event: &Event,
357 invalidated_views: &mut Vec<usize>,
358 cx: &'a mut MutableAppContext,
359 ) -> (bool, EventContext<'a>) {
360 let mut hover_regions = Vec::new();
361 if let Event::MouseMoved(
362 e @ MouseMovedEvent {
363 position,
364 pressed_button,
365 ..
366 },
367 ) = event
368 {
369 if let None = pressed_button {
370 let mut style_to_assign = CursorStyle::Arrow;
371 for region in self.cursor_regions.iter().rev() {
372 if region.bounds.contains_point(*position) {
373 style_to_assign = region.style;
374 break;
375 }
376 }
377 cx.platform().set_cursor_style(style_to_assign);
378
379 let mut hover_depth = None;
380 for (region, depth) in self.mouse_regions.iter().rev() {
381 if region.bounds.contains_point(*position)
382 && hover_depth.map_or(true, |hover_depth| hover_depth == *depth)
383 {
384 hover_depth = Some(*depth);
385 if let Some(region_id) = region.id() {
386 if !self.hovered_region_ids.contains(®ion_id) {
387 invalidated_views.push(region.view_id);
388 hover_regions.push((
389 region.clone(),
390 MouseRegionEvent::Hover(true, e.clone()),
391 ));
392 self.hovered_region_ids.insert(region_id);
393 }
394 }
395 } else {
396 if let Some(region_id) = region.id() {
397 if self.hovered_region_ids.contains(®ion_id) {
398 invalidated_views.push(region.view_id);
399 hover_regions.push((
400 region.clone(),
401 MouseRegionEvent::Hover(false, e.clone()),
402 ));
403 self.hovered_region_ids.remove(®ion_id);
404 }
405 }
406 }
407 }
408 }
409 }
410
411 let mut event_cx = self.build_event_context(cx);
412 let mut handled = false;
413
414 for (hover_region, region_event) in hover_regions {
415 handled = true;
416 if let Some(hover_callback) = hover_region.handlers.get(®ion_event.handler_key()) {
417 event_cx.with_current_view(hover_region.view_id, |event_cx| {
418 hover_callback(region_event, event_cx);
419 })
420 }
421 }
422
423 (handled, event_cx)
424 }
425
426 pub fn build_event_context<'a>(
427 &'a mut self,
428 cx: &'a mut MutableAppContext,
429 ) -> EventContext<'a> {
430 EventContext {
431 rendered_views: &mut self.rendered_views,
432 font_cache: &self.font_cache,
433 text_layout_cache: &self.text_layout_cache,
434 view_stack: Default::default(),
435 invalidated_views: Default::default(),
436 notify_count: 0,
437 window_id: self.window_id,
438 app: cx,
439 }
440 }
441
442 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
443 let view = cx.root_view(self.window_id)?;
444 Some(json!({
445 "root_view": view.debug_json(cx),
446 "root_element": self.rendered_views.get(&view.id())
447 .map(|root_element| {
448 root_element.debug(&DebugContext {
449 rendered_views: &self.rendered_views,
450 font_cache: &self.font_cache,
451 app: cx,
452 })
453 })
454 }))
455 }
456}
457
458pub struct LayoutContext<'a> {
459 window_id: usize,
460 rendered_views: &'a mut HashMap<usize, ElementBox>,
461 view_stack: Vec<usize>,
462 pub font_cache: &'a Arc<FontCache>,
463 pub font_system: Arc<dyn FontSystem>,
464 pub text_layout_cache: &'a TextLayoutCache,
465 pub asset_cache: &'a AssetCache,
466 pub app: &'a mut MutableAppContext,
467 pub refreshing: bool,
468 pub window_size: Vector2F,
469 titlebar_height: f32,
470 hovered_region_ids: HashSet<MouseRegionId>,
471 clicked_region_id: Option<MouseRegionId>,
472 right_clicked_region_id: Option<MouseRegionId>,
473}
474
475impl<'a> LayoutContext<'a> {
476 pub(crate) fn keystrokes_for_action(
477 &self,
478 action: &dyn Action,
479 ) -> Option<SmallVec<[Keystroke; 2]>> {
480 self.app
481 .keystrokes_for_action(self.window_id, &self.view_stack, action)
482 }
483
484 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
485 let print_error = |view_id| {
486 format!(
487 "{} with id {}",
488 self.app.name_for_view(self.window_id, view_id).unwrap(),
489 view_id,
490 )
491 };
492 match (
493 self.view_stack.last(),
494 self.app.parents.get(&(self.window_id, view_id)),
495 ) {
496 (Some(layout_parent), Some(ParentId::View(app_parent))) => {
497 if layout_parent != app_parent {
498 panic!(
499 "View {} was laid out with parent {} when it was constructed with parent {}",
500 print_error(view_id),
501 print_error(*layout_parent),
502 print_error(*app_parent))
503 }
504 }
505 (None, Some(ParentId::View(app_parent))) => panic!(
506 "View {} was laid out without a parent when it was constructed with parent {}",
507 print_error(view_id),
508 print_error(*app_parent)
509 ),
510 (Some(layout_parent), Some(ParentId::Root)) => panic!(
511 "View {} was laid out with parent {} when it was constructed as a window root",
512 print_error(view_id),
513 print_error(*layout_parent),
514 ),
515 (_, None) => panic!(
516 "View {} did not have a registered parent in the app context",
517 print_error(view_id),
518 ),
519 _ => {}
520 }
521
522 self.view_stack.push(view_id);
523 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
524 let size = rendered_view.layout(constraint, self);
525 self.rendered_views.insert(view_id, rendered_view);
526 self.view_stack.pop();
527 size
528 }
529
530 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
531 where
532 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
533 V: View,
534 {
535 handle.update(self.app, |view, cx| {
536 let mut render_cx = RenderContext {
537 app: cx,
538 window_id: handle.window_id(),
539 view_id: handle.id(),
540 view_type: PhantomData,
541 titlebar_height: self.titlebar_height,
542 hovered_region_ids: self.hovered_region_ids.clone(),
543 clicked_region_id: self.clicked_region_id,
544 right_clicked_region_id: self.right_clicked_region_id,
545 refreshing: self.refreshing,
546 };
547 f(view, &mut render_cx)
548 })
549 }
550}
551
552impl<'a> Deref for LayoutContext<'a> {
553 type Target = MutableAppContext;
554
555 fn deref(&self) -> &Self::Target {
556 self.app
557 }
558}
559
560impl<'a> DerefMut for LayoutContext<'a> {
561 fn deref_mut(&mut self) -> &mut Self::Target {
562 self.app
563 }
564}
565
566impl<'a> ReadView for LayoutContext<'a> {
567 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
568 self.app.read_view(handle)
569 }
570}
571
572impl<'a> ReadModel for LayoutContext<'a> {
573 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
574 self.app.read_model(handle)
575 }
576}
577
578impl<'a> UpgradeModelHandle for LayoutContext<'a> {
579 fn upgrade_model_handle<T: Entity>(
580 &self,
581 handle: &WeakModelHandle<T>,
582 ) -> Option<ModelHandle<T>> {
583 self.app.upgrade_model_handle(handle)
584 }
585
586 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
587 self.app.model_handle_is_upgradable(handle)
588 }
589
590 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
591 self.app.upgrade_any_model_handle(handle)
592 }
593}
594
595impl<'a> UpgradeViewHandle for LayoutContext<'a> {
596 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
597 self.app.upgrade_view_handle(handle)
598 }
599
600 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
601 self.app.upgrade_any_view_handle(handle)
602 }
603}
604
605pub struct PaintContext<'a> {
606 rendered_views: &'a mut HashMap<usize, ElementBox>,
607 view_stack: Vec<usize>,
608 pub window_size: Vector2F,
609 pub scene: &'a mut Scene,
610 pub font_cache: &'a FontCache,
611 pub text_layout_cache: &'a TextLayoutCache,
612 pub app: &'a AppContext,
613}
614
615impl<'a> PaintContext<'a> {
616 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
617 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
618 self.view_stack.push(view_id);
619 tree.paint(origin, visible_bounds, self);
620 self.rendered_views.insert(view_id, tree);
621 self.view_stack.pop();
622 }
623 }
624
625 #[inline]
626 pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
627 where
628 F: FnOnce(&mut Self) -> (),
629 {
630 self.scene.push_layer(clip_bounds);
631 f(self);
632 self.scene.pop_layer();
633 }
634
635 pub fn current_view_id(&self) -> usize {
636 *self.view_stack.last().unwrap()
637 }
638}
639
640impl<'a> Deref for PaintContext<'a> {
641 type Target = AppContext;
642
643 fn deref(&self) -> &Self::Target {
644 self.app
645 }
646}
647
648pub struct EventContext<'a> {
649 rendered_views: &'a mut HashMap<usize, ElementBox>,
650 pub font_cache: &'a FontCache,
651 pub text_layout_cache: &'a TextLayoutCache,
652 pub app: &'a mut MutableAppContext,
653 pub window_id: usize,
654 pub notify_count: usize,
655 view_stack: Vec<usize>,
656 invalidated_views: HashSet<usize>,
657}
658
659impl<'a> EventContext<'a> {
660 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
661 if let Some(mut element) = self.rendered_views.remove(&view_id) {
662 let result =
663 self.with_current_view(view_id, |this| element.dispatch_event(event, this));
664 self.rendered_views.insert(view_id, element);
665 result
666 } else {
667 false
668 }
669 }
670
671 fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
672 where
673 F: FnOnce(&mut Self) -> T,
674 {
675 self.view_stack.push(view_id);
676 let result = f(self);
677 self.view_stack.pop();
678 result
679 }
680
681 pub fn window_id(&self) -> usize {
682 self.window_id
683 }
684
685 pub fn view_id(&self) -> Option<usize> {
686 self.view_stack.last().copied()
687 }
688
689 pub fn is_parent_view_focused(&self) -> bool {
690 if let Some(parent_view_id) = self.view_stack.last() {
691 self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
692 } else {
693 false
694 }
695 }
696
697 pub fn focus_parent_view(&mut self) {
698 if let Some(parent_view_id) = self.view_stack.last() {
699 self.app.focus(self.window_id, Some(*parent_view_id))
700 }
701 }
702
703 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
704 self.app
705 .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
706 }
707
708 pub fn dispatch_action<A: Action>(&mut self, action: A) {
709 self.dispatch_any_action(Box::new(action));
710 }
711
712 pub fn notify(&mut self) {
713 self.notify_count += 1;
714 if let Some(view_id) = self.view_stack.last() {
715 self.invalidated_views.insert(*view_id);
716 }
717 }
718
719 pub fn notify_count(&self) -> usize {
720 self.notify_count
721 }
722}
723
724impl<'a> Deref for EventContext<'a> {
725 type Target = MutableAppContext;
726
727 fn deref(&self) -> &Self::Target {
728 self.app
729 }
730}
731
732impl<'a> DerefMut for EventContext<'a> {
733 fn deref_mut(&mut self) -> &mut Self::Target {
734 self.app
735 }
736}
737
738pub struct MeasurementContext<'a> {
739 app: &'a AppContext,
740 rendered_views: &'a HashMap<usize, ElementBox>,
741 pub window_id: usize,
742}
743
744impl<'a> Deref for MeasurementContext<'a> {
745 type Target = AppContext;
746
747 fn deref(&self) -> &Self::Target {
748 self.app
749 }
750}
751
752impl<'a> MeasurementContext<'a> {
753 fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
754 let element = self.rendered_views.get(&view_id)?;
755 element.rect_for_text_range(range_utf16, self)
756 }
757}
758
759pub struct DebugContext<'a> {
760 rendered_views: &'a HashMap<usize, ElementBox>,
761 pub font_cache: &'a FontCache,
762 pub app: &'a AppContext,
763}
764
765#[derive(Clone, Copy, Debug, Eq, PartialEq)]
766pub enum Axis {
767 Horizontal,
768 Vertical,
769}
770
771impl Axis {
772 pub fn invert(self) -> Self {
773 match self {
774 Self::Horizontal => Self::Vertical,
775 Self::Vertical => Self::Horizontal,
776 }
777 }
778}
779
780impl ToJson for Axis {
781 fn to_json(&self) -> serde_json::Value {
782 match self {
783 Axis::Horizontal => json!("horizontal"),
784 Axis::Vertical => json!("vertical"),
785 }
786 }
787}
788
789pub trait Vector2FExt {
790 fn along(self, axis: Axis) -> f32;
791}
792
793impl Vector2FExt for Vector2F {
794 fn along(self, axis: Axis) -> f32 {
795 match axis {
796 Axis::Horizontal => self.x(),
797 Axis::Vertical => self.y(),
798 }
799 }
800}
801
802#[derive(Copy, Clone, Debug)]
803pub struct SizeConstraint {
804 pub min: Vector2F,
805 pub max: Vector2F,
806}
807
808impl SizeConstraint {
809 pub fn new(min: Vector2F, max: Vector2F) -> Self {
810 Self { min, max }
811 }
812
813 pub fn strict(size: Vector2F) -> Self {
814 Self {
815 min: size,
816 max: size,
817 }
818 }
819
820 pub fn strict_along(axis: Axis, max: f32) -> Self {
821 match axis {
822 Axis::Horizontal => Self {
823 min: vec2f(max, 0.0),
824 max: vec2f(max, f32::INFINITY),
825 },
826 Axis::Vertical => Self {
827 min: vec2f(0.0, max),
828 max: vec2f(f32::INFINITY, max),
829 },
830 }
831 }
832
833 pub fn max_along(&self, axis: Axis) -> f32 {
834 match axis {
835 Axis::Horizontal => self.max.x(),
836 Axis::Vertical => self.max.y(),
837 }
838 }
839
840 pub fn min_along(&self, axis: Axis) -> f32 {
841 match axis {
842 Axis::Horizontal => self.min.x(),
843 Axis::Vertical => self.min.y(),
844 }
845 }
846
847 pub fn constrain(&self, size: Vector2F) -> Vector2F {
848 vec2f(
849 size.x().min(self.max.x()).max(self.min.x()),
850 size.y().min(self.max.y()).max(self.min.y()),
851 )
852 }
853}
854
855impl Default for SizeConstraint {
856 fn default() -> Self {
857 SizeConstraint {
858 min: Vector2F::zero(),
859 max: Vector2F::splat(f32::INFINITY),
860 }
861 }
862}
863
864impl ToJson for SizeConstraint {
865 fn to_json(&self) -> serde_json::Value {
866 json!({
867 "min": self.min.to_json(),
868 "max": self.max.to_json(),
869 })
870 }
871}
872
873pub struct ChildView {
874 view: AnyViewHandle,
875}
876
877impl ChildView {
878 pub fn new(view: impl Into<AnyViewHandle>) -> Self {
879 Self { view: view.into() }
880 }
881}
882
883impl Element for ChildView {
884 type LayoutState = ();
885 type PaintState = ();
886
887 fn layout(
888 &mut self,
889 constraint: SizeConstraint,
890 cx: &mut LayoutContext,
891 ) -> (Vector2F, Self::LayoutState) {
892 let size = cx.layout(self.view.id(), constraint);
893 (size, ())
894 }
895
896 fn paint(
897 &mut self,
898 bounds: RectF,
899 visible_bounds: RectF,
900 _: &mut Self::LayoutState,
901 cx: &mut PaintContext,
902 ) -> Self::PaintState {
903 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
904 }
905
906 fn dispatch_event(
907 &mut self,
908 event: &Event,
909 _: RectF,
910 _: RectF,
911 _: &mut Self::LayoutState,
912 _: &mut Self::PaintState,
913 cx: &mut EventContext,
914 ) -> bool {
915 cx.dispatch_event(self.view.id(), event)
916 }
917
918 fn rect_for_text_range(
919 &self,
920 range_utf16: Range<usize>,
921 _: RectF,
922 _: RectF,
923 _: &Self::LayoutState,
924 _: &Self::PaintState,
925 cx: &MeasurementContext,
926 ) -> Option<RectF> {
927 cx.rect_for_text_range(self.view.id(), range_utf16)
928 }
929
930 fn debug(
931 &self,
932 bounds: RectF,
933 _: &Self::LayoutState,
934 _: &Self::PaintState,
935 cx: &DebugContext,
936 ) -> serde_json::Value {
937 json!({
938 "type": "ChildView",
939 "view_id": self.view.id(),
940 "bounds": bounds.to_json(),
941 "view": self.view.debug_json(cx.app),
942 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
943 view.debug(cx)
944 } else {
945 json!(null)
946 }
947 })
948 }
949}