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