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