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());
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());
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 in unhovered_regions {
352 if let Some(hover_callback) = unhovered_region.hover {
353 handled = true;
354 event_cx.with_current_view(unhovered_region.view_id, |event_cx| {
355 hover_callback(false, event_cx);
356 })
357 }
358 }
359
360 for hovered_region in hovered_regions {
361 if let Some(hover_callback) = hovered_region.hover {
362 handled = true;
363 event_cx.with_current_view(hovered_region.view_id, |event_cx| {
364 hover_callback(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 if let Some(mouse_down_callback) = mouse_down_region.mouse_down {
375 handled = true;
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 if let Some(click_callback) = clicked_region.click {
384 handled = true;
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 if let Some(right_mouse_down_callback) = right_mouse_down_region.right_mouse_down {
393 handled = true;
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 if let Some(right_click_callback) = right_clicked_region.right_click {
402 handled = true;
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 if let Some(drag_callback) = dragged_region.drag {
411 handled = true;
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 app: cx,
453 }
454 }
455
456 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
457 let view = cx.root_view(self.window_id)?;
458 Some(json!({
459 "root_view": view.debug_json(cx),
460 "root_element": self.rendered_views.get(&view.id())
461 .map(|root_element| {
462 root_element.debug(&DebugContext {
463 rendered_views: &self.rendered_views,
464 font_cache: &self.font_cache,
465 app: cx,
466 })
467 })
468 }))
469 }
470}
471
472pub struct DispatchDirective {
473 pub dispatcher_view_id: Option<usize>,
474 pub action: Box<dyn Action>,
475}
476
477pub struct LayoutContext<'a> {
478 window_id: usize,
479 rendered_views: &'a mut HashMap<usize, ElementBox>,
480 parents: &'a mut HashMap<usize, usize>,
481 view_stack: Vec<usize>,
482 pub font_cache: &'a Arc<FontCache>,
483 pub font_system: Arc<dyn FontSystem>,
484 pub text_layout_cache: &'a TextLayoutCache,
485 pub asset_cache: &'a AssetCache,
486 pub app: &'a mut MutableAppContext,
487 pub refreshing: bool,
488 pub window_size: Vector2F,
489 titlebar_height: f32,
490 hovered_region_ids: HashSet<MouseRegionId>,
491 clicked_region_id: Option<MouseRegionId>,
492 right_clicked_region_id: Option<MouseRegionId>,
493}
494
495impl<'a> LayoutContext<'a> {
496 pub(crate) fn keystrokes_for_action(
497 &self,
498 action: &dyn Action,
499 ) -> Option<SmallVec<[Keystroke; 2]>> {
500 self.app
501 .keystrokes_for_action(self.window_id, &self.view_stack, action)
502 }
503
504 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
505 if let Some(parent_id) = self.view_stack.last() {
506 self.parents.insert(view_id, *parent_id);
507 }
508 self.view_stack.push(view_id);
509 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
510 let size = rendered_view.layout(constraint, self);
511 self.rendered_views.insert(view_id, rendered_view);
512 self.view_stack.pop();
513 size
514 }
515
516 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
517 where
518 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
519 V: View,
520 {
521 handle.update(self.app, |view, cx| {
522 let mut render_cx = RenderContext {
523 app: cx,
524 window_id: handle.window_id(),
525 view_id: handle.id(),
526 view_type: PhantomData,
527 titlebar_height: self.titlebar_height,
528 hovered_region_ids: self.hovered_region_ids.clone(),
529 clicked_region_id: self.clicked_region_id,
530 right_clicked_region_id: self.right_clicked_region_id,
531 refreshing: self.refreshing,
532 };
533 f(view, &mut render_cx)
534 })
535 }
536}
537
538impl<'a> Deref for LayoutContext<'a> {
539 type Target = MutableAppContext;
540
541 fn deref(&self) -> &Self::Target {
542 self.app
543 }
544}
545
546impl<'a> DerefMut for LayoutContext<'a> {
547 fn deref_mut(&mut self) -> &mut Self::Target {
548 self.app
549 }
550}
551
552impl<'a> ReadView for LayoutContext<'a> {
553 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
554 self.app.read_view(handle)
555 }
556}
557
558impl<'a> ReadModel for LayoutContext<'a> {
559 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
560 self.app.read_model(handle)
561 }
562}
563
564impl<'a> UpgradeModelHandle for LayoutContext<'a> {
565 fn upgrade_model_handle<T: Entity>(
566 &self,
567 handle: &WeakModelHandle<T>,
568 ) -> Option<ModelHandle<T>> {
569 self.app.upgrade_model_handle(handle)
570 }
571
572 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
573 self.app.model_handle_is_upgradable(handle)
574 }
575
576 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
577 self.app.upgrade_any_model_handle(handle)
578 }
579}
580
581impl<'a> UpgradeViewHandle for LayoutContext<'a> {
582 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
583 self.app.upgrade_view_handle(handle)
584 }
585
586 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
587 self.app.upgrade_any_view_handle(handle)
588 }
589}
590
591pub struct PaintContext<'a> {
592 rendered_views: &'a mut HashMap<usize, ElementBox>,
593 view_stack: Vec<usize>,
594 pub scene: &'a mut Scene,
595 pub font_cache: &'a FontCache,
596 pub text_layout_cache: &'a TextLayoutCache,
597 pub app: &'a AppContext,
598}
599
600impl<'a> PaintContext<'a> {
601 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
602 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
603 self.view_stack.push(view_id);
604 tree.paint(origin, visible_bounds, self);
605 self.rendered_views.insert(view_id, tree);
606 self.view_stack.pop();
607 }
608 }
609
610 pub fn current_view_id(&self) -> usize {
611 *self.view_stack.last().unwrap()
612 }
613}
614
615impl<'a> Deref for PaintContext<'a> {
616 type Target = AppContext;
617
618 fn deref(&self) -> &Self::Target {
619 self.app
620 }
621}
622
623pub struct EventContext<'a> {
624 rendered_views: &'a mut HashMap<usize, ElementBox>,
625 dispatched_actions: Vec<DispatchDirective>,
626 pub font_cache: &'a FontCache,
627 pub text_layout_cache: &'a TextLayoutCache,
628 pub app: &'a mut MutableAppContext,
629 pub notify_count: usize,
630 view_stack: Vec<usize>,
631 invalidated_views: HashSet<usize>,
632}
633
634impl<'a> EventContext<'a> {
635 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
636 if let Some(mut element) = self.rendered_views.remove(&view_id) {
637 let result =
638 self.with_current_view(view_id, |this| element.dispatch_event(event, this));
639 self.rendered_views.insert(view_id, element);
640 result
641 } else {
642 false
643 }
644 }
645
646 fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
647 where
648 F: FnOnce(&mut Self) -> T,
649 {
650 self.view_stack.push(view_id);
651 let result = f(self);
652 self.view_stack.pop();
653 result
654 }
655
656 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
657 self.dispatched_actions.push(DispatchDirective {
658 dispatcher_view_id: self.view_stack.last().copied(),
659 action,
660 });
661 }
662
663 pub fn dispatch_action<A: Action>(&mut self, action: A) {
664 self.dispatch_any_action(Box::new(action));
665 }
666
667 pub fn notify(&mut self) {
668 self.notify_count += 1;
669 if let Some(view_id) = self.view_stack.last() {
670 self.invalidated_views.insert(*view_id);
671 }
672 }
673
674 pub fn notify_count(&self) -> usize {
675 self.notify_count
676 }
677}
678
679impl<'a> Deref for EventContext<'a> {
680 type Target = MutableAppContext;
681
682 fn deref(&self) -> &Self::Target {
683 self.app
684 }
685}
686
687impl<'a> DerefMut for EventContext<'a> {
688 fn deref_mut(&mut self) -> &mut Self::Target {
689 self.app
690 }
691}
692
693pub struct DebugContext<'a> {
694 rendered_views: &'a HashMap<usize, ElementBox>,
695 pub font_cache: &'a FontCache,
696 pub app: &'a AppContext,
697}
698
699#[derive(Clone, Copy, Debug, Eq, PartialEq)]
700pub enum Axis {
701 Horizontal,
702 Vertical,
703}
704
705impl Axis {
706 pub fn invert(self) -> Self {
707 match self {
708 Self::Horizontal => Self::Vertical,
709 Self::Vertical => Self::Horizontal,
710 }
711 }
712}
713
714impl ToJson for Axis {
715 fn to_json(&self) -> serde_json::Value {
716 match self {
717 Axis::Horizontal => json!("horizontal"),
718 Axis::Vertical => json!("vertical"),
719 }
720 }
721}
722
723pub trait Vector2FExt {
724 fn along(self, axis: Axis) -> f32;
725}
726
727impl Vector2FExt for Vector2F {
728 fn along(self, axis: Axis) -> f32 {
729 match axis {
730 Axis::Horizontal => self.x(),
731 Axis::Vertical => self.y(),
732 }
733 }
734}
735
736#[derive(Copy, Clone, Debug)]
737pub struct SizeConstraint {
738 pub min: Vector2F,
739 pub max: Vector2F,
740}
741
742impl SizeConstraint {
743 pub fn new(min: Vector2F, max: Vector2F) -> Self {
744 Self { min, max }
745 }
746
747 pub fn strict(size: Vector2F) -> Self {
748 Self {
749 min: size,
750 max: size,
751 }
752 }
753
754 pub fn strict_along(axis: Axis, max: f32) -> Self {
755 match axis {
756 Axis::Horizontal => Self {
757 min: vec2f(max, 0.0),
758 max: vec2f(max, f32::INFINITY),
759 },
760 Axis::Vertical => Self {
761 min: vec2f(0.0, max),
762 max: vec2f(f32::INFINITY, max),
763 },
764 }
765 }
766
767 pub fn max_along(&self, axis: Axis) -> f32 {
768 match axis {
769 Axis::Horizontal => self.max.x(),
770 Axis::Vertical => self.max.y(),
771 }
772 }
773
774 pub fn min_along(&self, axis: Axis) -> f32 {
775 match axis {
776 Axis::Horizontal => self.min.x(),
777 Axis::Vertical => self.min.y(),
778 }
779 }
780
781 pub fn constrain(&self, size: Vector2F) -> Vector2F {
782 vec2f(
783 size.x().min(self.max.x()).max(self.min.x()),
784 size.y().min(self.max.y()).max(self.min.y()),
785 )
786 }
787}
788
789impl Default for SizeConstraint {
790 fn default() -> Self {
791 SizeConstraint {
792 min: Vector2F::zero(),
793 max: Vector2F::splat(f32::INFINITY),
794 }
795 }
796}
797
798impl ToJson for SizeConstraint {
799 fn to_json(&self) -> serde_json::Value {
800 json!({
801 "min": self.min.to_json(),
802 "max": self.max.to_json(),
803 })
804 }
805}
806
807pub struct ChildView {
808 view: AnyViewHandle,
809}
810
811impl ChildView {
812 pub fn new(view: impl Into<AnyViewHandle>) -> Self {
813 Self { view: view.into() }
814 }
815}
816
817impl Element for ChildView {
818 type LayoutState = ();
819 type PaintState = ();
820
821 fn layout(
822 &mut self,
823 constraint: SizeConstraint,
824 cx: &mut LayoutContext,
825 ) -> (Vector2F, Self::LayoutState) {
826 let size = cx.layout(self.view.id(), constraint);
827 (size, ())
828 }
829
830 fn paint(
831 &mut self,
832 bounds: RectF,
833 visible_bounds: RectF,
834 _: &mut Self::LayoutState,
835 cx: &mut PaintContext,
836 ) -> Self::PaintState {
837 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
838 }
839
840 fn dispatch_event(
841 &mut self,
842 event: &Event,
843 _: RectF,
844 _: RectF,
845 _: &mut Self::LayoutState,
846 _: &mut Self::PaintState,
847 cx: &mut EventContext,
848 ) -> bool {
849 cx.dispatch_event(self.view.id(), event)
850 }
851
852 fn debug(
853 &self,
854 bounds: RectF,
855 _: &Self::LayoutState,
856 _: &Self::PaintState,
857 cx: &DebugContext,
858 ) -> serde_json::Value {
859 json!({
860 "type": "ChildView",
861 "view_id": self.view.id(),
862 "bounds": bounds.to_json(),
863 "view": self.view.debug_json(cx.app),
864 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
865 view.debug(cx)
866 } else {
867 json!(null)
868 }
869 })
870 }
871}