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),
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 pressed_button.is_none() {
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
389 .push((region.clone(), MouseRegionEvent::Hover(true, *e)));
390 self.hovered_region_ids.insert(region_id);
391 }
392 }
393 } else if let Some(region_id) = region.id() {
394 if self.hovered_region_ids.contains(®ion_id) {
395 invalidated_views.push(region.view_id);
396 hover_regions
397 .push((region.clone(), MouseRegionEvent::Hover(false, *e)));
398 self.hovered_region_ids.remove(®ion_id);
399 }
400 }
401 }
402 }
403 }
404
405 let mut event_cx = self.build_event_context(cx);
406 let mut handled = false;
407
408 for (hover_region, region_event) in hover_regions {
409 handled = true;
410 if let Some(hover_callback) = hover_region.handlers.get(®ion_event.handler_key()) {
411 event_cx.with_current_view(hover_region.view_id, |event_cx| {
412 hover_callback(region_event, event_cx);
413 })
414 }
415 }
416
417 (handled, event_cx)
418 }
419
420 pub fn build_event_context<'a>(
421 &'a mut self,
422 cx: &'a mut MutableAppContext,
423 ) -> EventContext<'a> {
424 EventContext {
425 rendered_views: &mut self.rendered_views,
426 font_cache: &self.font_cache,
427 text_layout_cache: &self.text_layout_cache,
428 view_stack: Default::default(),
429 invalidated_views: Default::default(),
430 notify_count: 0,
431 window_id: self.window_id,
432 app: cx,
433 }
434 }
435
436 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
437 let view = cx.root_view(self.window_id)?;
438 Some(json!({
439 "root_view": view.debug_json(cx),
440 "root_element": self.rendered_views.get(&view.id())
441 .map(|root_element| {
442 root_element.debug(&DebugContext {
443 rendered_views: &self.rendered_views,
444 font_cache: &self.font_cache,
445 app: cx,
446 })
447 })
448 }))
449 }
450}
451
452pub struct LayoutContext<'a> {
453 window_id: usize,
454 rendered_views: &'a mut HashMap<usize, ElementBox>,
455 view_stack: Vec<usize>,
456 pub font_cache: &'a Arc<FontCache>,
457 pub font_system: Arc<dyn FontSystem>,
458 pub text_layout_cache: &'a TextLayoutCache,
459 pub asset_cache: &'a AssetCache,
460 pub app: &'a mut MutableAppContext,
461 pub refreshing: bool,
462 pub window_size: Vector2F,
463 titlebar_height: f32,
464 hovered_region_ids: HashSet<MouseRegionId>,
465 clicked_region_id: Option<MouseRegionId>,
466 right_clicked_region_id: Option<MouseRegionId>,
467}
468
469impl<'a> LayoutContext<'a> {
470 pub(crate) fn keystrokes_for_action(
471 &self,
472 action: &dyn Action,
473 ) -> Option<SmallVec<[Keystroke; 2]>> {
474 self.app
475 .keystrokes_for_action(self.window_id, &self.view_stack, action)
476 }
477
478 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
479 let print_error = |view_id| {
480 format!(
481 "{} with id {}",
482 self.app.name_for_view(self.window_id, view_id).unwrap(),
483 view_id,
484 )
485 };
486 match (
487 self.view_stack.last(),
488 self.app.parents.get(&(self.window_id, view_id)),
489 ) {
490 (Some(layout_parent), Some(ParentId::View(app_parent))) => {
491 if layout_parent != app_parent {
492 panic!(
493 "View {} was laid out with parent {} when it was constructed with parent {}",
494 print_error(view_id),
495 print_error(*layout_parent),
496 print_error(*app_parent))
497 }
498 }
499 (None, Some(ParentId::View(app_parent))) => panic!(
500 "View {} was laid out without a parent when it was constructed with parent {}",
501 print_error(view_id),
502 print_error(*app_parent)
503 ),
504 (Some(layout_parent), Some(ParentId::Root)) => panic!(
505 "View {} was laid out with parent {} when it was constructed as a window root",
506 print_error(view_id),
507 print_error(*layout_parent),
508 ),
509 (_, None) => panic!(
510 "View {} did not have a registered parent in the app context",
511 print_error(view_id),
512 ),
513 _ => {}
514 }
515
516 self.view_stack.push(view_id);
517 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
518 let size = rendered_view.layout(constraint, self);
519 self.rendered_views.insert(view_id, rendered_view);
520 self.view_stack.pop();
521 size
522 }
523
524 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
525 where
526 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
527 V: View,
528 {
529 handle.update(self.app, |view, cx| {
530 let mut render_cx = RenderContext {
531 app: cx,
532 window_id: handle.window_id(),
533 view_id: handle.id(),
534 view_type: PhantomData,
535 titlebar_height: self.titlebar_height,
536 hovered_region_ids: self.hovered_region_ids.clone(),
537 clicked_region_id: self.clicked_region_id,
538 right_clicked_region_id: self.right_clicked_region_id,
539 refreshing: self.refreshing,
540 };
541 f(view, &mut render_cx)
542 })
543 }
544}
545
546impl<'a> Deref for LayoutContext<'a> {
547 type Target = MutableAppContext;
548
549 fn deref(&self) -> &Self::Target {
550 self.app
551 }
552}
553
554impl<'a> DerefMut for LayoutContext<'a> {
555 fn deref_mut(&mut self) -> &mut Self::Target {
556 self.app
557 }
558}
559
560impl<'a> ReadView for LayoutContext<'a> {
561 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
562 self.app.read_view(handle)
563 }
564}
565
566impl<'a> ReadModel for LayoutContext<'a> {
567 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
568 self.app.read_model(handle)
569 }
570}
571
572impl<'a> UpgradeModelHandle for LayoutContext<'a> {
573 fn upgrade_model_handle<T: Entity>(
574 &self,
575 handle: &WeakModelHandle<T>,
576 ) -> Option<ModelHandle<T>> {
577 self.app.upgrade_model_handle(handle)
578 }
579
580 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
581 self.app.model_handle_is_upgradable(handle)
582 }
583
584 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
585 self.app.upgrade_any_model_handle(handle)
586 }
587}
588
589impl<'a> UpgradeViewHandle for LayoutContext<'a> {
590 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
591 self.app.upgrade_view_handle(handle)
592 }
593
594 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
595 self.app.upgrade_any_view_handle(handle)
596 }
597}
598
599pub struct PaintContext<'a> {
600 rendered_views: &'a mut HashMap<usize, ElementBox>,
601 view_stack: Vec<usize>,
602 pub window_size: Vector2F,
603 pub scene: &'a mut Scene,
604 pub font_cache: &'a FontCache,
605 pub text_layout_cache: &'a TextLayoutCache,
606 pub app: &'a AppContext,
607}
608
609impl<'a> PaintContext<'a> {
610 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
611 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
612 self.view_stack.push(view_id);
613 tree.paint(origin, visible_bounds, self);
614 self.rendered_views.insert(view_id, tree);
615 self.view_stack.pop();
616 }
617 }
618
619 #[inline]
620 pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
621 where
622 F: FnOnce(&mut Self),
623 {
624 self.scene.push_layer(clip_bounds);
625 f(self);
626 self.scene.pop_layer();
627 }
628
629 pub fn current_view_id(&self) -> usize {
630 *self.view_stack.last().unwrap()
631 }
632}
633
634impl<'a> Deref for PaintContext<'a> {
635 type Target = AppContext;
636
637 fn deref(&self) -> &Self::Target {
638 self.app
639 }
640}
641
642pub struct EventContext<'a> {
643 rendered_views: &'a mut HashMap<usize, ElementBox>,
644 pub font_cache: &'a FontCache,
645 pub text_layout_cache: &'a TextLayoutCache,
646 pub app: &'a mut MutableAppContext,
647 pub window_id: usize,
648 pub notify_count: usize,
649 view_stack: Vec<usize>,
650 invalidated_views: HashSet<usize>,
651}
652
653impl<'a> EventContext<'a> {
654 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
655 if let Some(mut element) = self.rendered_views.remove(&view_id) {
656 let result =
657 self.with_current_view(view_id, |this| element.dispatch_event(event, this));
658 self.rendered_views.insert(view_id, element);
659 result
660 } else {
661 false
662 }
663 }
664
665 fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
666 where
667 F: FnOnce(&mut Self) -> T,
668 {
669 self.view_stack.push(view_id);
670 let result = f(self);
671 self.view_stack.pop();
672 result
673 }
674
675 pub fn window_id(&self) -> usize {
676 self.window_id
677 }
678
679 pub fn view_id(&self) -> Option<usize> {
680 self.view_stack.last().copied()
681 }
682
683 pub fn is_parent_view_focused(&self) -> bool {
684 if let Some(parent_view_id) = self.view_stack.last() {
685 self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
686 } else {
687 false
688 }
689 }
690
691 pub fn focus_parent_view(&mut self) {
692 if let Some(parent_view_id) = self.view_stack.last() {
693 self.app.focus(self.window_id, Some(*parent_view_id))
694 }
695 }
696
697 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
698 self.app
699 .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
700 }
701
702 pub fn dispatch_action<A: Action>(&mut self, action: A) {
703 self.dispatch_any_action(Box::new(action));
704 }
705
706 pub fn notify(&mut self) {
707 self.notify_count += 1;
708 if let Some(view_id) = self.view_stack.last() {
709 self.invalidated_views.insert(*view_id);
710 }
711 }
712
713 pub fn notify_count(&self) -> usize {
714 self.notify_count
715 }
716}
717
718impl<'a> Deref for EventContext<'a> {
719 type Target = MutableAppContext;
720
721 fn deref(&self) -> &Self::Target {
722 self.app
723 }
724}
725
726impl<'a> DerefMut for EventContext<'a> {
727 fn deref_mut(&mut self) -> &mut Self::Target {
728 self.app
729 }
730}
731
732pub struct MeasurementContext<'a> {
733 app: &'a AppContext,
734 rendered_views: &'a HashMap<usize, ElementBox>,
735 pub window_id: usize,
736}
737
738impl<'a> Deref for MeasurementContext<'a> {
739 type Target = AppContext;
740
741 fn deref(&self) -> &Self::Target {
742 self.app
743 }
744}
745
746impl<'a> MeasurementContext<'a> {
747 fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
748 let element = self.rendered_views.get(&view_id)?;
749 element.rect_for_text_range(range_utf16, self)
750 }
751}
752
753pub struct DebugContext<'a> {
754 rendered_views: &'a HashMap<usize, ElementBox>,
755 pub font_cache: &'a FontCache,
756 pub app: &'a AppContext,
757}
758
759#[derive(Clone, Copy, Debug, Eq, PartialEq)]
760pub enum Axis {
761 Horizontal,
762 Vertical,
763}
764
765impl Axis {
766 pub fn invert(self) -> Self {
767 match self {
768 Self::Horizontal => Self::Vertical,
769 Self::Vertical => Self::Horizontal,
770 }
771 }
772}
773
774impl ToJson for Axis {
775 fn to_json(&self) -> serde_json::Value {
776 match self {
777 Axis::Horizontal => json!("horizontal"),
778 Axis::Vertical => json!("vertical"),
779 }
780 }
781}
782
783pub trait Vector2FExt {
784 fn along(self, axis: Axis) -> f32;
785}
786
787impl Vector2FExt for Vector2F {
788 fn along(self, axis: Axis) -> f32 {
789 match axis {
790 Axis::Horizontal => self.x(),
791 Axis::Vertical => self.y(),
792 }
793 }
794}
795
796#[derive(Copy, Clone, Debug)]
797pub struct SizeConstraint {
798 pub min: Vector2F,
799 pub max: Vector2F,
800}
801
802impl SizeConstraint {
803 pub fn new(min: Vector2F, max: Vector2F) -> Self {
804 Self { min, max }
805 }
806
807 pub fn strict(size: Vector2F) -> Self {
808 Self {
809 min: size,
810 max: size,
811 }
812 }
813
814 pub fn strict_along(axis: Axis, max: f32) -> Self {
815 match axis {
816 Axis::Horizontal => Self {
817 min: vec2f(max, 0.0),
818 max: vec2f(max, f32::INFINITY),
819 },
820 Axis::Vertical => Self {
821 min: vec2f(0.0, max),
822 max: vec2f(f32::INFINITY, max),
823 },
824 }
825 }
826
827 pub fn max_along(&self, axis: Axis) -> f32 {
828 match axis {
829 Axis::Horizontal => self.max.x(),
830 Axis::Vertical => self.max.y(),
831 }
832 }
833
834 pub fn min_along(&self, axis: Axis) -> f32 {
835 match axis {
836 Axis::Horizontal => self.min.x(),
837 Axis::Vertical => self.min.y(),
838 }
839 }
840
841 pub fn constrain(&self, size: Vector2F) -> Vector2F {
842 vec2f(
843 size.x().min(self.max.x()).max(self.min.x()),
844 size.y().min(self.max.y()).max(self.min.y()),
845 )
846 }
847}
848
849impl Default for SizeConstraint {
850 fn default() -> Self {
851 SizeConstraint {
852 min: Vector2F::zero(),
853 max: Vector2F::splat(f32::INFINITY),
854 }
855 }
856}
857
858impl ToJson for SizeConstraint {
859 fn to_json(&self) -> serde_json::Value {
860 json!({
861 "min": self.min.to_json(),
862 "max": self.max.to_json(),
863 })
864 }
865}
866
867pub struct ChildView {
868 view: AnyViewHandle,
869}
870
871impl ChildView {
872 pub fn new(view: impl Into<AnyViewHandle>) -> Self {
873 Self { view: view.into() }
874 }
875}
876
877impl Element for ChildView {
878 type LayoutState = ();
879 type PaintState = ();
880
881 fn layout(
882 &mut self,
883 constraint: SizeConstraint,
884 cx: &mut LayoutContext,
885 ) -> (Vector2F, Self::LayoutState) {
886 let size = cx.layout(self.view.id(), constraint);
887 (size, ())
888 }
889
890 fn paint(
891 &mut self,
892 bounds: RectF,
893 visible_bounds: RectF,
894 _: &mut Self::LayoutState,
895 cx: &mut PaintContext,
896 ) -> Self::PaintState {
897 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
898 }
899
900 fn dispatch_event(
901 &mut self,
902 event: &Event,
903 _: RectF,
904 _: RectF,
905 _: &mut Self::LayoutState,
906 _: &mut Self::PaintState,
907 cx: &mut EventContext,
908 ) -> bool {
909 cx.dispatch_event(self.view.id(), event)
910 }
911
912 fn rect_for_text_range(
913 &self,
914 range_utf16: Range<usize>,
915 _: RectF,
916 _: RectF,
917 _: &Self::LayoutState,
918 _: &Self::PaintState,
919 cx: &MeasurementContext,
920 ) -> Option<RectF> {
921 cx.rect_for_text_range(self.view.id(), range_utf16)
922 }
923
924 fn debug(
925 &self,
926 bounds: RectF,
927 _: &Self::LayoutState,
928 _: &Self::PaintState,
929 cx: &DebugContext,
930 ) -> serde_json::Value {
931 json!({
932 "type": "ChildView",
933 "view_id": self.view.id(),
934 "bounds": bounds.to_json(),
935 "view": self.view.debug_json(cx.app),
936 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
937 view.debug(cx)
938 } else {
939 json!(null)
940 }
941 })
942 }
943}