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