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