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,
10 text_layout::TextLayoutCache,
11 Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox, Entity,
12 FontSystem, ModelHandle, MouseRegion, MouseRegionId, ReadModel, ReadView, RenderContext,
13 RenderParams, Scene, UpgradeModelHandle, UpgradeViewHandle, View, ViewHandle, WeakModelHandle,
14 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 self.dispatch_event(event, cx)
164 }
165 }
166 } else {
167 log::error!("could not find root_view_id for window {}", self.window_id);
168 }
169
170 scene
171 }
172
173 fn layout(&mut self, window_size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
174 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
175 self.build_layout_context(window_size, refreshing, cx)
176 .layout(root_view_id, SizeConstraint::strict(window_size));
177 }
178 }
179
180 pub fn build_layout_context<'a>(
181 &'a mut self,
182 window_size: Vector2F,
183 refreshing: bool,
184 cx: &'a mut MutableAppContext,
185 ) -> LayoutContext<'a> {
186 LayoutContext {
187 window_id: self.window_id,
188 rendered_views: &mut self.rendered_views,
189 parents: &mut self.parents,
190 font_cache: &self.font_cache,
191 font_system: cx.platform().fonts(),
192 text_layout_cache: &self.text_layout_cache,
193 asset_cache: &self.asset_cache,
194 view_stack: Vec::new(),
195 refreshing,
196 hovered_region_ids: self.hovered_region_ids.clone(),
197 clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
198 right_clicked_region_id: self.right_clicked_region.as_ref().and_then(MouseRegion::id),
199 titlebar_height: self.titlebar_height,
200 window_size,
201 app: cx,
202 }
203 }
204
205 pub fn build_paint_context<'a>(
206 &'a mut self,
207 scene: &'a mut Scene,
208 window_size: Vector2F,
209 cx: &'a mut MutableAppContext,
210 ) -> PaintContext {
211 PaintContext {
212 scene,
213 window_size,
214 font_cache: &self.font_cache,
215 text_layout_cache: &self.text_layout_cache,
216 rendered_views: &mut self.rendered_views,
217 view_stack: Vec::new(),
218 app: cx,
219 }
220 }
221
222 pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) {
223 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
224 let mut invalidated_views = Vec::new();
225 let mut hovered_regions = Vec::new();
226 let mut unhovered_regions = Vec::new();
227 let mut mouse_down_out_handlers = Vec::new();
228 let mut mouse_down_region = None;
229 let mut clicked_region = None;
230 let mut right_mouse_down_region = None;
231 let mut right_clicked_region = None;
232 let mut dragged_region = None;
233
234 match event {
235 Event::LeftMouseDown { position, .. } => {
236 let mut hit = false;
237 for (region, _) in self.mouse_regions.iter().rev() {
238 if region.bounds.contains_point(position) {
239 if !hit {
240 hit = true;
241 invalidated_views.push(region.view_id);
242 mouse_down_region = Some((region.clone(), position));
243 self.clicked_region = Some(region.clone());
244 self.prev_drag_position = Some(position);
245 }
246 } else if let Some(handler) = region.mouse_down_out.clone() {
247 mouse_down_out_handlers.push((handler, region.view_id, position));
248 }
249 }
250 }
251 Event::LeftMouseUp {
252 position,
253 click_count,
254 ..
255 } => {
256 self.prev_drag_position.take();
257 if let Some(region) = self.clicked_region.take() {
258 invalidated_views.push(region.view_id);
259 if region.bounds.contains_point(position) {
260 clicked_region = Some((region, position, click_count));
261 }
262 }
263 }
264 Event::RightMouseDown { position, .. } => {
265 let mut hit = false;
266 for (region, _) in self.mouse_regions.iter().rev() {
267 if region.bounds.contains_point(position) {
268 if !hit {
269 hit = true;
270 invalidated_views.push(region.view_id);
271 right_mouse_down_region = Some((region.clone(), position));
272 self.right_clicked_region = Some(region.clone());
273 }
274 } else if let Some(handler) = region.right_mouse_down_out.clone() {
275 mouse_down_out_handlers.push((handler, region.view_id, position));
276 }
277 }
278 }
279 Event::RightMouseUp {
280 position,
281 click_count,
282 ..
283 } => {
284 if let Some(region) = self.right_clicked_region.take() {
285 invalidated_views.push(region.view_id);
286 if region.bounds.contains_point(position) {
287 right_clicked_region = Some((region, position, click_count));
288 }
289 }
290 }
291 Event::MouseMoved {
292 position,
293 left_mouse_down,
294 } => {
295 self.last_mouse_moved_event = Some(event.clone());
296
297 if !left_mouse_down {
298 let mut style_to_assign = CursorStyle::Arrow;
299 for region in self.cursor_regions.iter().rev() {
300 if region.bounds.contains_point(position) {
301 style_to_assign = region.style;
302 break;
303 }
304 }
305 cx.platform().set_cursor_style(style_to_assign);
306
307 let mut hover_depth = None;
308 for (region, depth) in self.mouse_regions.iter().rev() {
309 if region.bounds.contains_point(position)
310 && hover_depth.map_or(true, |hover_depth| hover_depth == *depth)
311 {
312 hover_depth = Some(*depth);
313 if let Some(region_id) = region.id() {
314 if !self.hovered_region_ids.contains(®ion_id) {
315 invalidated_views.push(region.view_id);
316 hovered_regions.push((region.clone(), position));
317 self.hovered_region_ids.insert(region_id);
318 }
319 }
320 } else {
321 if let Some(region_id) = region.id() {
322 if self.hovered_region_ids.contains(®ion_id) {
323 invalidated_views.push(region.view_id);
324 unhovered_regions.push((region.clone(), position));
325 self.hovered_region_ids.remove(®ion_id);
326 }
327 }
328 }
329 }
330 }
331 }
332 Event::LeftMouseDragged { position } => {
333 if let Some((clicked_region, prev_drag_position)) = self
334 .clicked_region
335 .as_ref()
336 .zip(self.prev_drag_position.as_mut())
337 {
338 dragged_region =
339 Some((clicked_region.clone(), position - *prev_drag_position));
340 *prev_drag_position = position;
341 }
342
343 self.last_mouse_moved_event = Some(Event::MouseMoved {
344 position,
345 left_mouse_down: true,
346 });
347 }
348 _ => {}
349 }
350
351 let mut event_cx = self.build_event_context(cx);
352 let mut handled = false;
353 for (unhovered_region, position) in unhovered_regions {
354 handled = true;
355 if let Some(hover_callback) = unhovered_region.hover {
356 event_cx.with_current_view(unhovered_region.view_id, |event_cx| {
357 hover_callback(position, false, event_cx);
358 })
359 }
360 }
361
362 for (hovered_region, position) in hovered_regions {
363 handled = true;
364 if let Some(hover_callback) = hovered_region.hover {
365 event_cx.with_current_view(hovered_region.view_id, |event_cx| {
366 hover_callback(position, true, event_cx);
367 })
368 }
369 }
370
371 for (handler, view_id, position) in mouse_down_out_handlers {
372 event_cx.with_current_view(view_id, |event_cx| handler(position, event_cx))
373 }
374
375 if let Some((mouse_down_region, position)) = mouse_down_region {
376 handled = true;
377 if let Some(mouse_down_callback) = mouse_down_region.mouse_down {
378 event_cx.with_current_view(mouse_down_region.view_id, |event_cx| {
379 mouse_down_callback(position, event_cx);
380 })
381 }
382 }
383
384 if let Some((clicked_region, position, click_count)) = clicked_region {
385 handled = true;
386 if let Some(click_callback) = clicked_region.click {
387 event_cx.with_current_view(clicked_region.view_id, |event_cx| {
388 click_callback(position, click_count, event_cx);
389 })
390 }
391 }
392
393 if let Some((right_mouse_down_region, position)) = right_mouse_down_region {
394 handled = true;
395 if let Some(right_mouse_down_callback) = right_mouse_down_region.right_mouse_down {
396 event_cx.with_current_view(right_mouse_down_region.view_id, |event_cx| {
397 right_mouse_down_callback(position, event_cx);
398 })
399 }
400 }
401
402 if let Some((right_clicked_region, position, click_count)) = right_clicked_region {
403 handled = true;
404 if let Some(right_click_callback) = right_clicked_region.right_click {
405 event_cx.with_current_view(right_clicked_region.view_id, |event_cx| {
406 right_click_callback(position, click_count, event_cx);
407 })
408 }
409 }
410
411 if let Some((dragged_region, delta)) = dragged_region {
412 handled = true;
413 if let Some(drag_callback) = dragged_region.drag {
414 event_cx.with_current_view(dragged_region.view_id, |event_cx| {
415 drag_callback(delta, event_cx);
416 })
417 }
418 }
419
420 if !handled {
421 event_cx.dispatch_event(root_view_id, &event);
422 }
423
424 invalidated_views.extend(event_cx.invalidated_views);
425 let dispatch_directives = event_cx.dispatched_actions;
426
427 for view_id in invalidated_views {
428 cx.notify_view(self.window_id, view_id);
429 }
430
431 let mut dispatch_path = Vec::new();
432 for directive in dispatch_directives {
433 dispatch_path.clear();
434 if let Some(view_id) = directive.dispatcher_view_id {
435 self.compute_dispatch_path_from(view_id, &mut dispatch_path);
436 }
437 cx.dispatch_action_any(self.window_id, &dispatch_path, directive.action.as_ref());
438 }
439 }
440 }
441
442 pub fn build_event_context<'a>(
443 &'a mut self,
444 cx: &'a mut MutableAppContext,
445 ) -> EventContext<'a> {
446 EventContext {
447 rendered_views: &mut self.rendered_views,
448 dispatched_actions: Default::default(),
449 font_cache: &self.font_cache,
450 text_layout_cache: &self.text_layout_cache,
451 view_stack: Default::default(),
452 invalidated_views: Default::default(),
453 notify_count: 0,
454 window_id: self.window_id,
455 app: cx,
456 }
457 }
458
459 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
460 let view = cx.root_view(self.window_id)?;
461 Some(json!({
462 "root_view": view.debug_json(cx),
463 "root_element": self.rendered_views.get(&view.id())
464 .map(|root_element| {
465 root_element.debug(&DebugContext {
466 rendered_views: &self.rendered_views,
467 font_cache: &self.font_cache,
468 app: cx,
469 })
470 })
471 }))
472 }
473}
474
475pub struct DispatchDirective {
476 pub dispatcher_view_id: Option<usize>,
477 pub action: Box<dyn Action>,
478}
479
480pub struct LayoutContext<'a> {
481 window_id: usize,
482 rendered_views: &'a mut HashMap<usize, ElementBox>,
483 parents: &'a mut HashMap<usize, usize>,
484 view_stack: Vec<usize>,
485 pub font_cache: &'a Arc<FontCache>,
486 pub font_system: Arc<dyn FontSystem>,
487 pub text_layout_cache: &'a TextLayoutCache,
488 pub asset_cache: &'a AssetCache,
489 pub app: &'a mut MutableAppContext,
490 pub refreshing: bool,
491 pub window_size: Vector2F,
492 titlebar_height: f32,
493 hovered_region_ids: HashSet<MouseRegionId>,
494 clicked_region_id: Option<MouseRegionId>,
495 right_clicked_region_id: Option<MouseRegionId>,
496}
497
498impl<'a> LayoutContext<'a> {
499 pub(crate) fn keystrokes_for_action(
500 &self,
501 action: &dyn Action,
502 ) -> Option<SmallVec<[Keystroke; 2]>> {
503 self.app
504 .keystrokes_for_action(self.window_id, &self.view_stack, action)
505 }
506
507 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
508 if let Some(parent_id) = self.view_stack.last() {
509 self.parents.insert(view_id, *parent_id);
510 }
511 self.view_stack.push(view_id);
512 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
513 let size = rendered_view.layout(constraint, self);
514 self.rendered_views.insert(view_id, rendered_view);
515 self.view_stack.pop();
516 size
517 }
518
519 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
520 where
521 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
522 V: View,
523 {
524 handle.update(self.app, |view, cx| {
525 let mut render_cx = RenderContext {
526 app: cx,
527 window_id: handle.window_id(),
528 view_id: handle.id(),
529 view_type: PhantomData,
530 titlebar_height: self.titlebar_height,
531 hovered_region_ids: self.hovered_region_ids.clone(),
532 clicked_region_id: self.clicked_region_id,
533 right_clicked_region_id: self.right_clicked_region_id,
534 refreshing: self.refreshing,
535 };
536 f(view, &mut render_cx)
537 })
538 }
539}
540
541impl<'a> Deref for LayoutContext<'a> {
542 type Target = MutableAppContext;
543
544 fn deref(&self) -> &Self::Target {
545 self.app
546 }
547}
548
549impl<'a> DerefMut for LayoutContext<'a> {
550 fn deref_mut(&mut self) -> &mut Self::Target {
551 self.app
552 }
553}
554
555impl<'a> ReadView for LayoutContext<'a> {
556 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
557 self.app.read_view(handle)
558 }
559}
560
561impl<'a> ReadModel for LayoutContext<'a> {
562 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
563 self.app.read_model(handle)
564 }
565}
566
567impl<'a> UpgradeModelHandle for LayoutContext<'a> {
568 fn upgrade_model_handle<T: Entity>(
569 &self,
570 handle: &WeakModelHandle<T>,
571 ) -> Option<ModelHandle<T>> {
572 self.app.upgrade_model_handle(handle)
573 }
574
575 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
576 self.app.model_handle_is_upgradable(handle)
577 }
578
579 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
580 self.app.upgrade_any_model_handle(handle)
581 }
582}
583
584impl<'a> UpgradeViewHandle for LayoutContext<'a> {
585 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
586 self.app.upgrade_view_handle(handle)
587 }
588
589 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
590 self.app.upgrade_any_view_handle(handle)
591 }
592}
593
594pub struct PaintContext<'a> {
595 rendered_views: &'a mut HashMap<usize, ElementBox>,
596 view_stack: Vec<usize>,
597 pub window_size: Vector2F,
598 pub scene: &'a mut Scene,
599 pub font_cache: &'a FontCache,
600 pub text_layout_cache: &'a TextLayoutCache,
601 pub app: &'a AppContext,
602}
603
604impl<'a> PaintContext<'a> {
605 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
606 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
607 self.view_stack.push(view_id);
608 tree.paint(origin, visible_bounds, self);
609 self.rendered_views.insert(view_id, tree);
610 self.view_stack.pop();
611 }
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 dispatch_any_action(&mut self, action: Box<dyn Action>) {
670 self.dispatched_actions.push(DispatchDirective {
671 dispatcher_view_id: self.view_stack.last().copied(),
672 action,
673 });
674 }
675
676 pub fn dispatch_action<A: Action>(&mut self, action: A) {
677 self.dispatch_any_action(Box::new(action));
678 }
679
680 pub fn notify(&mut self) {
681 self.notify_count += 1;
682 if let Some(view_id) = self.view_stack.last() {
683 self.invalidated_views.insert(*view_id);
684 }
685 }
686
687 pub fn notify_count(&self) -> usize {
688 self.notify_count
689 }
690}
691
692impl<'a> Deref for EventContext<'a> {
693 type Target = MutableAppContext;
694
695 fn deref(&self) -> &Self::Target {
696 self.app
697 }
698}
699
700impl<'a> DerefMut for EventContext<'a> {
701 fn deref_mut(&mut self) -> &mut Self::Target {
702 self.app
703 }
704}
705
706pub struct DebugContext<'a> {
707 rendered_views: &'a HashMap<usize, ElementBox>,
708 pub font_cache: &'a FontCache,
709 pub app: &'a AppContext,
710}
711
712#[derive(Clone, Copy, Debug, Eq, PartialEq)]
713pub enum Axis {
714 Horizontal,
715 Vertical,
716}
717
718impl Axis {
719 pub fn invert(self) -> Self {
720 match self {
721 Self::Horizontal => Self::Vertical,
722 Self::Vertical => Self::Horizontal,
723 }
724 }
725}
726
727impl ToJson for Axis {
728 fn to_json(&self) -> serde_json::Value {
729 match self {
730 Axis::Horizontal => json!("horizontal"),
731 Axis::Vertical => json!("vertical"),
732 }
733 }
734}
735
736pub trait Vector2FExt {
737 fn along(self, axis: Axis) -> f32;
738}
739
740impl Vector2FExt for Vector2F {
741 fn along(self, axis: Axis) -> f32 {
742 match axis {
743 Axis::Horizontal => self.x(),
744 Axis::Vertical => self.y(),
745 }
746 }
747}
748
749#[derive(Copy, Clone, Debug)]
750pub struct SizeConstraint {
751 pub min: Vector2F,
752 pub max: Vector2F,
753}
754
755impl SizeConstraint {
756 pub fn new(min: Vector2F, max: Vector2F) -> Self {
757 Self { min, max }
758 }
759
760 pub fn strict(size: Vector2F) -> Self {
761 Self {
762 min: size,
763 max: size,
764 }
765 }
766
767 pub fn strict_along(axis: Axis, max: f32) -> Self {
768 match axis {
769 Axis::Horizontal => Self {
770 min: vec2f(max, 0.0),
771 max: vec2f(max, f32::INFINITY),
772 },
773 Axis::Vertical => Self {
774 min: vec2f(0.0, max),
775 max: vec2f(f32::INFINITY, max),
776 },
777 }
778 }
779
780 pub fn max_along(&self, axis: Axis) -> f32 {
781 match axis {
782 Axis::Horizontal => self.max.x(),
783 Axis::Vertical => self.max.y(),
784 }
785 }
786
787 pub fn min_along(&self, axis: Axis) -> f32 {
788 match axis {
789 Axis::Horizontal => self.min.x(),
790 Axis::Vertical => self.min.y(),
791 }
792 }
793
794 pub fn constrain(&self, size: Vector2F) -> Vector2F {
795 vec2f(
796 size.x().min(self.max.x()).max(self.min.x()),
797 size.y().min(self.max.y()).max(self.min.y()),
798 )
799 }
800}
801
802impl Default for SizeConstraint {
803 fn default() -> Self {
804 SizeConstraint {
805 min: Vector2F::zero(),
806 max: Vector2F::splat(f32::INFINITY),
807 }
808 }
809}
810
811impl ToJson for SizeConstraint {
812 fn to_json(&self) -> serde_json::Value {
813 json!({
814 "min": self.min.to_json(),
815 "max": self.max.to_json(),
816 })
817 }
818}
819
820pub struct ChildView {
821 view: AnyViewHandle,
822}
823
824impl ChildView {
825 pub fn new(view: impl Into<AnyViewHandle>) -> Self {
826 Self { view: view.into() }
827 }
828}
829
830impl Element for ChildView {
831 type LayoutState = ();
832 type PaintState = ();
833
834 fn layout(
835 &mut self,
836 constraint: SizeConstraint,
837 cx: &mut LayoutContext,
838 ) -> (Vector2F, Self::LayoutState) {
839 let size = cx.layout(self.view.id(), constraint);
840 (size, ())
841 }
842
843 fn paint(
844 &mut self,
845 bounds: RectF,
846 visible_bounds: RectF,
847 _: &mut Self::LayoutState,
848 cx: &mut PaintContext,
849 ) -> Self::PaintState {
850 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
851 }
852
853 fn dispatch_event(
854 &mut self,
855 event: &Event,
856 _: RectF,
857 _: RectF,
858 _: &mut Self::LayoutState,
859 _: &mut Self::PaintState,
860 cx: &mut EventContext,
861 ) -> bool {
862 cx.dispatch_event(self.view.id(), event)
863 }
864
865 fn debug(
866 &self,
867 bounds: RectF,
868 _: &Self::LayoutState,
869 _: &Self::PaintState,
870 cx: &DebugContext,
871 ) -> serde_json::Value {
872 json!({
873 "type": "ChildView",
874 "view_id": self.view.id(),
875 "bounds": bounds.to_json(),
876 "view": self.view.debug_json(cx.app),
877 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
878 view.debug(cx)
879 } else {
880 json!(null)
881 }
882 })
883 }
884}