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, MouseRegionEvent},
10 text_layout::TextLayoutCache,
11 Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox, Entity,
12 FontSystem, ModelHandle, MouseButtonEvent, MouseMovedEvent, MouseRegion, MouseRegionId,
13 ParentId, ReadModel, ReadView, RenderContext, RenderParams, Scene, UpgradeModelHandle,
14 UpgradeViewHandle, View, ViewHandle, WeakModelHandle, WeakViewHandle,
15};
16use collections::{HashMap, HashSet};
17use pathfinder_geometry::vector::{vec2f, Vector2F};
18use serde_json::json;
19use smallvec::SmallVec;
20use std::{
21 marker::PhantomData,
22 ops::{Deref, DerefMut, Range},
23 sync::Arc,
24};
25
26pub struct Presenter {
27 window_id: usize,
28 pub(crate) rendered_views: HashMap<usize, ElementBox>,
29 cursor_regions: Vec<CursorRegion>,
30 mouse_regions: Vec<(MouseRegion, usize)>,
31 font_cache: Arc<FontCache>,
32 text_layout_cache: TextLayoutCache,
33 asset_cache: Arc<AssetCache>,
34 last_mouse_moved_event: Option<MouseMovedEvent>,
35 hovered_region_ids: HashSet<MouseRegionId>,
36 clicked_region: Option<MouseRegion>,
37 right_clicked_region: Option<MouseRegion>,
38 prev_drag_position: Option<Vector2F>,
39 titlebar_height: f32,
40}
41
42impl Presenter {
43 pub fn new(
44 window_id: usize,
45 titlebar_height: f32,
46 font_cache: Arc<FontCache>,
47 text_layout_cache: TextLayoutCache,
48 asset_cache: Arc<AssetCache>,
49 cx: &mut MutableAppContext,
50 ) -> Self {
51 Self {
52 window_id,
53 rendered_views: cx.render_views(window_id, titlebar_height),
54 cursor_regions: Default::default(),
55 mouse_regions: Default::default(),
56 font_cache,
57 text_layout_cache,
58 asset_cache,
59 last_mouse_moved_event: None,
60 hovered_region_ids: Default::default(),
61 clicked_region: None,
62 right_clicked_region: None,
63 prev_drag_position: None,
64 titlebar_height,
65 }
66 }
67
68 // pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
69 // let mut path = Vec::new();
70 // if let Some(view_id) = app.focused_view_id(self.window_id) {
71 // self.compute_dispatch_path_from(view_id, &mut path)
72 // }
73 // path
74 // }
75
76 // pub(crate) fn compute_dispatch_path_from(&self, mut view_id: usize, path: &mut Vec<usize>) {
77 // path.push(view_id);
78 // while let Some(parent_id) = self.parents.get(&view_id).copied() {
79 // path.push(parent_id);
80 // view_id = parent_id;
81 // }
82 // path.reverse();
83 // }
84
85 pub fn invalidate(
86 &mut self,
87 invalidation: &mut WindowInvalidation,
88 cx: &mut MutableAppContext,
89 ) {
90 cx.start_frame();
91 for view_id in &invalidation.removed {
92 invalidation.updated.remove(view_id);
93 self.rendered_views.remove(view_id);
94 }
95 for view_id in &invalidation.updated {
96 self.rendered_views.insert(
97 *view_id,
98 cx.render_view(RenderParams {
99 window_id: self.window_id,
100 view_id: *view_id,
101 titlebar_height: self.titlebar_height,
102 hovered_region_ids: self.hovered_region_ids.clone(),
103 clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
104 right_clicked_region_id: self
105 .right_clicked_region
106 .as_ref()
107 .and_then(MouseRegion::id),
108 refreshing: false,
109 })
110 .unwrap(),
111 );
112 }
113 }
114
115 pub fn refresh(&mut self, invalidation: &mut WindowInvalidation, cx: &mut MutableAppContext) {
116 self.invalidate(invalidation, cx);
117 for (view_id, view) in &mut self.rendered_views {
118 if !invalidation.updated.contains(view_id) {
119 *view = cx
120 .render_view(RenderParams {
121 window_id: self.window_id,
122 view_id: *view_id,
123 titlebar_height: self.titlebar_height,
124 hovered_region_ids: self.hovered_region_ids.clone(),
125 clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
126 right_clicked_region_id: self
127 .right_clicked_region
128 .as_ref()
129 .and_then(MouseRegion::id),
130 refreshing: true,
131 })
132 .unwrap();
133 }
134 }
135 }
136
137 pub fn build_scene(
138 &mut self,
139 window_size: Vector2F,
140 scale_factor: f32,
141 refreshing: bool,
142 cx: &mut MutableAppContext,
143 ) -> Scene {
144 let mut scene = Scene::new(scale_factor);
145
146 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
147 self.layout(window_size, refreshing, cx);
148 let mut paint_cx = self.build_paint_context(&mut scene, window_size, cx);
149 paint_cx.paint(
150 root_view_id,
151 Vector2F::zero(),
152 RectF::new(Vector2F::zero(), window_size),
153 );
154 self.text_layout_cache.finish_frame();
155 self.cursor_regions = scene.cursor_regions();
156 self.mouse_regions = scene.mouse_regions();
157
158 if cx.window_is_active(self.window_id) {
159 if let Some(event) = self.last_mouse_moved_event.clone() {
160 let mut invalidated_views = Vec::new();
161 self.handle_hover_events(&event, &mut invalidated_views, cx);
162
163 for view_id in invalidated_views {
164 cx.notify_view(self.window_id, view_id);
165 }
166 }
167 }
168 } else {
169 log::error!("could not find root_view_id for window {}", self.window_id);
170 }
171
172 scene
173 }
174
175 fn layout(&mut self, window_size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
176 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
177 self.build_layout_context(window_size, refreshing, cx)
178 .layout(root_view_id, SizeConstraint::strict(window_size));
179 }
180 }
181
182 pub fn build_layout_context<'a>(
183 &'a mut self,
184 window_size: Vector2F,
185 refreshing: bool,
186 cx: &'a mut MutableAppContext,
187 ) -> LayoutContext<'a> {
188 LayoutContext {
189 window_id: self.window_id,
190 rendered_views: &mut self.rendered_views,
191 font_cache: &self.font_cache,
192 font_system: cx.platform().fonts(),
193 text_layout_cache: &self.text_layout_cache,
194 asset_cache: &self.asset_cache,
195 view_stack: Vec::new(),
196 refreshing,
197 hovered_region_ids: self.hovered_region_ids.clone(),
198 clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
199 right_clicked_region_id: self.right_clicked_region.as_ref().and_then(MouseRegion::id),
200 titlebar_height: self.titlebar_height,
201 window_size,
202 app: cx,
203 }
204 }
205
206 pub fn build_paint_context<'a>(
207 &'a mut self,
208 scene: &'a mut Scene,
209 window_size: Vector2F,
210 cx: &'a mut MutableAppContext,
211 ) -> PaintContext {
212 PaintContext {
213 scene,
214 window_size,
215 font_cache: &self.font_cache,
216 text_layout_cache: &self.text_layout_cache,
217 rendered_views: &mut self.rendered_views,
218 view_stack: Vec::new(),
219 app: cx,
220 }
221 }
222
223 pub fn rect_for_text_range(&self, range_utf16: Range<usize>, cx: &AppContext) -> Option<RectF> {
224 cx.focused_view_id(self.window_id).and_then(|view_id| {
225 let cx = MeasurementContext {
226 app: cx,
227 rendered_views: &self.rendered_views,
228 window_id: self.window_id,
229 };
230 cx.rect_for_text_range(view_id, range_utf16)
231 })
232 }
233
234 pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) -> bool {
235 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
236 let mut invalidated_views = Vec::new();
237 let mut mouse_down_out_handlers = Vec::new();
238 let mut mouse_moved_region = None;
239 let mut mouse_down_region = None;
240 let mut clicked_region = None;
241 let mut dragged_region = None;
242
243 match &event {
244 Event::MouseDown(
245 e @ MouseButtonEvent {
246 position, button, ..
247 },
248 ) => {
249 let mut hit = false;
250 for (region, _) in self.mouse_regions.iter().rev() {
251 if region.bounds.contains_point(*position) {
252 if !hit {
253 hit = true;
254 invalidated_views.push(region.view_id);
255 mouse_down_region =
256 Some((region.clone(), MouseRegionEvent::Down(e.clone())));
257 self.clicked_region = Some(region.clone());
258 self.prev_drag_position = Some(*position);
259 }
260 } else if let Some(handler) = region
261 .handlers
262 .get(&(MouseRegionEvent::down_out_disc(), Some(*button)))
263 {
264 mouse_down_out_handlers.push((
265 handler,
266 region.view_id,
267 MouseRegionEvent::DownOut(e.clone()),
268 ));
269 }
270 }
271 }
272
273 &Event::MouseUp(
274 e @ MouseButtonEvent {
275 position, button, ..
276 },
277 ) => {
278 self.prev_drag_position.take();
279 if let Some(region) = self.clicked_region.take() {
280 invalidated_views.push(region.view_id);
281 if region.bounds.contains_point(position) {
282 clicked_region = Some((region, MouseRegionEvent::Click(e.clone())));
283 }
284 }
285
286 if let Some(moved) = &mut self.last_mouse_moved_event {
287 if moved.pressed_button == Some(button) {
288 moved.pressed_button = None;
289 }
290 }
291 }
292
293 Event::MouseMoved(e @ MouseMovedEvent { position, .. }) => {
294 if let Some((clicked_region, prev_drag_position)) = self
295 .clicked_region
296 .as_ref()
297 .zip(self.prev_drag_position.as_mut())
298 {
299 dragged_region = Some((
300 clicked_region.clone(),
301 MouseRegionEvent::Drag(*prev_drag_position, *e),
302 ));
303 *prev_drag_position = *position;
304 }
305
306 for (region, _) in self.mouse_regions.iter().rev() {
307 if region.bounds.contains_point(*position) {
308 invalidated_views.push(region.view_id);
309 mouse_moved_region =
310 Some((region.clone(), MouseRegionEvent::Move(e.clone())));
311 break;
312 }
313 }
314
315 self.last_mouse_moved_event = Some(e.clone());
316 }
317
318 _ => {}
319 }
320
321 let (mut handled, mut event_cx) = if let Event::MouseMoved(e) = &event {
322 self.handle_hover_events(e, &mut invalidated_views, cx)
323 } else {
324 (false, self.build_event_context(cx))
325 };
326
327 for (handler, view_id, region_event) in mouse_down_out_handlers {
328 event_cx.with_current_view(view_id, |event_cx| handler(region_event, event_cx))
329 }
330
331 if let Some((mouse_down_region, region_event)) = mouse_down_region {
332 handled = true;
333 if let Some(mouse_down_callback) =
334 mouse_down_region.handlers.get(®ion_event.handler_key())
335 {
336 event_cx.with_current_view(mouse_down_region.view_id, |event_cx| {
337 mouse_down_callback(region_event, event_cx);
338 })
339 }
340 }
341
342 if let Some((move_moved_region, region_event)) = mouse_moved_region {
343 handled = true;
344 if let Some(mouse_moved_callback) =
345 move_moved_region.handlers.get(®ion_event.handler_key())
346 {
347 event_cx.with_current_view(move_moved_region.view_id, |event_cx| {
348 mouse_moved_callback(region_event, event_cx);
349 })
350 }
351 }
352
353 if let Some((clicked_region, region_event)) = clicked_region {
354 handled = true;
355 if let Some(click_callback) =
356 clicked_region.handlers.get(®ion_event.handler_key())
357 {
358 event_cx.with_current_view(clicked_region.view_id, |event_cx| {
359 click_callback(region_event, event_cx);
360 })
361 }
362 }
363
364 if let Some((dragged_region, region_event)) = dragged_region {
365 handled = true;
366 if let Some(drag_callback) =
367 dragged_region.handlers.get(®ion_event.handler_key())
368 {
369 event_cx.with_current_view(dragged_region.view_id, |event_cx| {
370 drag_callback(region_event, event_cx);
371 })
372 }
373 }
374
375 if !handled {
376 handled = event_cx.dispatch_event(root_view_id, &event);
377 }
378
379 invalidated_views.extend(event_cx.invalidated_views);
380
381 for view_id in invalidated_views {
382 cx.notify_view(self.window_id, view_id);
383 }
384
385 handled
386 } else {
387 false
388 }
389 }
390
391 fn handle_hover_events<'a>(
392 &'a mut self,
393 e @ MouseMovedEvent {
394 position,
395 pressed_button,
396 ..
397 }: &MouseMovedEvent,
398 invalidated_views: &mut Vec<usize>,
399 cx: &'a mut MutableAppContext,
400 ) -> (bool, EventContext<'a>) {
401 let mut hover_regions = Vec::new();
402
403 if pressed_button.is_none() {
404 let mut style_to_assign = CursorStyle::Arrow;
405 for region in self.cursor_regions.iter().rev() {
406 if region.bounds.contains_point(*position) {
407 style_to_assign = region.style;
408 break;
409 }
410 }
411 cx.platform().set_cursor_style(style_to_assign);
412
413 let mut hover_depth = None;
414 for (region, depth) in self.mouse_regions.iter().rev() {
415 if region.bounds.contains_point(*position)
416 && hover_depth.map_or(true, |hover_depth| hover_depth == *depth)
417 {
418 hover_depth = Some(*depth);
419 if let Some(region_id) = region.id() {
420 if !self.hovered_region_ids.contains(®ion_id) {
421 invalidated_views.push(region.view_id);
422 hover_regions.push((region.clone(), MouseRegionEvent::Hover(true, *e)));
423 self.hovered_region_ids.insert(region_id);
424 }
425 }
426 } else if let Some(region_id) = region.id() {
427 if self.hovered_region_ids.contains(®ion_id) {
428 invalidated_views.push(region.view_id);
429 hover_regions.push((region.clone(), MouseRegionEvent::Hover(false, *e)));
430 self.hovered_region_ids.remove(®ion_id);
431 }
432 }
433 }
434 }
435
436 let mut event_cx = self.build_event_context(cx);
437 let mut handled = false;
438
439 for (hover_region, region_event) in hover_regions {
440 handled = true;
441 if let Some(hover_callback) = hover_region.handlers.get(®ion_event.handler_key()) {
442 event_cx.with_current_view(hover_region.view_id, |event_cx| {
443 hover_callback(region_event, event_cx);
444 })
445 }
446 }
447
448 (handled, event_cx)
449 }
450
451 pub fn build_event_context<'a>(
452 &'a mut self,
453 cx: &'a mut MutableAppContext,
454 ) -> EventContext<'a> {
455 EventContext {
456 rendered_views: &mut self.rendered_views,
457 font_cache: &self.font_cache,
458 text_layout_cache: &self.text_layout_cache,
459 view_stack: Default::default(),
460 invalidated_views: Default::default(),
461 notify_count: 0,
462 window_id: self.window_id,
463 app: cx,
464 }
465 }
466
467 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
468 let view = cx.root_view(self.window_id)?;
469 Some(json!({
470 "root_view": view.debug_json(cx),
471 "root_element": self.rendered_views.get(&view.id())
472 .map(|root_element| {
473 root_element.debug(&DebugContext {
474 rendered_views: &self.rendered_views,
475 font_cache: &self.font_cache,
476 app: cx,
477 })
478 })
479 }))
480 }
481}
482
483pub struct LayoutContext<'a> {
484 window_id: usize,
485 rendered_views: &'a mut HashMap<usize, ElementBox>,
486 view_stack: Vec<usize>,
487 pub font_cache: &'a Arc<FontCache>,
488 pub font_system: Arc<dyn FontSystem>,
489 pub text_layout_cache: &'a TextLayoutCache,
490 pub asset_cache: &'a AssetCache,
491 pub app: &'a mut MutableAppContext,
492 pub refreshing: bool,
493 pub window_size: Vector2F,
494 titlebar_height: f32,
495 hovered_region_ids: HashSet<MouseRegionId>,
496 clicked_region_id: Option<MouseRegionId>,
497 right_clicked_region_id: Option<MouseRegionId>,
498}
499
500impl<'a> LayoutContext<'a> {
501 pub(crate) fn keystrokes_for_action(
502 &self,
503 action: &dyn Action,
504 ) -> Option<SmallVec<[Keystroke; 2]>> {
505 self.app
506 .keystrokes_for_action(self.window_id, &self.view_stack, action)
507 }
508
509 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
510 let print_error = |view_id| {
511 format!(
512 "{} with id {}",
513 self.app.name_for_view(self.window_id, view_id).unwrap(),
514 view_id,
515 )
516 };
517 match (
518 self.view_stack.last(),
519 self.app.parents.get(&(self.window_id, view_id)),
520 ) {
521 (Some(layout_parent), Some(ParentId::View(app_parent))) => {
522 if layout_parent != app_parent {
523 panic!(
524 "View {} was laid out with parent {} when it was constructed with parent {}",
525 print_error(view_id),
526 print_error(*layout_parent),
527 print_error(*app_parent))
528 }
529 }
530 (None, Some(ParentId::View(app_parent))) => panic!(
531 "View {} was laid out without a parent when it was constructed with parent {}",
532 print_error(view_id),
533 print_error(*app_parent)
534 ),
535 (Some(layout_parent), Some(ParentId::Root)) => panic!(
536 "View {} was laid out with parent {} when it was constructed as a window root",
537 print_error(view_id),
538 print_error(*layout_parent),
539 ),
540 (_, None) => panic!(
541 "View {} did not have a registered parent in the app context",
542 print_error(view_id),
543 ),
544 _ => {}
545 }
546
547 self.view_stack.push(view_id);
548 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
549 let size = rendered_view.layout(constraint, self);
550 self.rendered_views.insert(view_id, rendered_view);
551 self.view_stack.pop();
552 size
553 }
554
555 pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
556 where
557 F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
558 V: View,
559 {
560 handle.update(self.app, |view, cx| {
561 let mut render_cx = RenderContext {
562 app: cx,
563 window_id: handle.window_id(),
564 view_id: handle.id(),
565 view_type: PhantomData,
566 titlebar_height: self.titlebar_height,
567 hovered_region_ids: self.hovered_region_ids.clone(),
568 clicked_region_id: self.clicked_region_id,
569 right_clicked_region_id: self.right_clicked_region_id,
570 refreshing: self.refreshing,
571 };
572 f(view, &mut render_cx)
573 })
574 }
575}
576
577impl<'a> Deref for LayoutContext<'a> {
578 type Target = MutableAppContext;
579
580 fn deref(&self) -> &Self::Target {
581 self.app
582 }
583}
584
585impl<'a> DerefMut for LayoutContext<'a> {
586 fn deref_mut(&mut self) -> &mut Self::Target {
587 self.app
588 }
589}
590
591impl<'a> ReadView for LayoutContext<'a> {
592 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
593 self.app.read_view(handle)
594 }
595}
596
597impl<'a> ReadModel for LayoutContext<'a> {
598 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
599 self.app.read_model(handle)
600 }
601}
602
603impl<'a> UpgradeModelHandle for LayoutContext<'a> {
604 fn upgrade_model_handle<T: Entity>(
605 &self,
606 handle: &WeakModelHandle<T>,
607 ) -> Option<ModelHandle<T>> {
608 self.app.upgrade_model_handle(handle)
609 }
610
611 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
612 self.app.model_handle_is_upgradable(handle)
613 }
614
615 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
616 self.app.upgrade_any_model_handle(handle)
617 }
618}
619
620impl<'a> UpgradeViewHandle for LayoutContext<'a> {
621 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
622 self.app.upgrade_view_handle(handle)
623 }
624
625 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
626 self.app.upgrade_any_view_handle(handle)
627 }
628}
629
630pub struct PaintContext<'a> {
631 rendered_views: &'a mut HashMap<usize, ElementBox>,
632 view_stack: Vec<usize>,
633 pub window_size: Vector2F,
634 pub scene: &'a mut Scene,
635 pub font_cache: &'a FontCache,
636 pub text_layout_cache: &'a TextLayoutCache,
637 pub app: &'a AppContext,
638}
639
640impl<'a> PaintContext<'a> {
641 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
642 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
643 self.view_stack.push(view_id);
644 tree.paint(origin, visible_bounds, self);
645 self.rendered_views.insert(view_id, tree);
646 self.view_stack.pop();
647 }
648 }
649
650 #[inline]
651 pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
652 where
653 F: FnOnce(&mut Self),
654 {
655 self.scene.push_layer(clip_bounds);
656 f(self);
657 self.scene.pop_layer();
658 }
659
660 pub fn current_view_id(&self) -> usize {
661 *self.view_stack.last().unwrap()
662 }
663}
664
665impl<'a> Deref for PaintContext<'a> {
666 type Target = AppContext;
667
668 fn deref(&self) -> &Self::Target {
669 self.app
670 }
671}
672
673pub struct EventContext<'a> {
674 rendered_views: &'a mut HashMap<usize, ElementBox>,
675 pub font_cache: &'a FontCache,
676 pub text_layout_cache: &'a TextLayoutCache,
677 pub app: &'a mut MutableAppContext,
678 pub window_id: usize,
679 pub notify_count: usize,
680 view_stack: Vec<usize>,
681 invalidated_views: HashSet<usize>,
682}
683
684impl<'a> EventContext<'a> {
685 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
686 if let Some(mut element) = self.rendered_views.remove(&view_id) {
687 let result =
688 self.with_current_view(view_id, |this| element.dispatch_event(event, this));
689 self.rendered_views.insert(view_id, element);
690 result
691 } else {
692 false
693 }
694 }
695
696 fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
697 where
698 F: FnOnce(&mut Self) -> T,
699 {
700 self.view_stack.push(view_id);
701 let result = f(self);
702 self.view_stack.pop();
703 result
704 }
705
706 pub fn window_id(&self) -> usize {
707 self.window_id
708 }
709
710 pub fn view_id(&self) -> Option<usize> {
711 self.view_stack.last().copied()
712 }
713
714 pub fn is_parent_view_focused(&self) -> bool {
715 if let Some(parent_view_id) = self.view_stack.last() {
716 self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
717 } else {
718 false
719 }
720 }
721
722 pub fn focus_parent_view(&mut self) {
723 if let Some(parent_view_id) = self.view_stack.last() {
724 self.app.focus(self.window_id, Some(*parent_view_id))
725 }
726 }
727
728 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
729 self.app
730 .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
731 }
732
733 pub fn dispatch_action<A: Action>(&mut self, action: A) {
734 self.dispatch_any_action(Box::new(action));
735 }
736
737 pub fn notify(&mut self) {
738 self.notify_count += 1;
739 if let Some(view_id) = self.view_stack.last() {
740 self.invalidated_views.insert(*view_id);
741 }
742 }
743
744 pub fn notify_count(&self) -> usize {
745 self.notify_count
746 }
747}
748
749impl<'a> Deref for EventContext<'a> {
750 type Target = MutableAppContext;
751
752 fn deref(&self) -> &Self::Target {
753 self.app
754 }
755}
756
757impl<'a> DerefMut for EventContext<'a> {
758 fn deref_mut(&mut self) -> &mut Self::Target {
759 self.app
760 }
761}
762
763pub struct MeasurementContext<'a> {
764 app: &'a AppContext,
765 rendered_views: &'a HashMap<usize, ElementBox>,
766 pub window_id: usize,
767}
768
769impl<'a> Deref for MeasurementContext<'a> {
770 type Target = AppContext;
771
772 fn deref(&self) -> &Self::Target {
773 self.app
774 }
775}
776
777impl<'a> MeasurementContext<'a> {
778 fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
779 let element = self.rendered_views.get(&view_id)?;
780 element.rect_for_text_range(range_utf16, self)
781 }
782}
783
784pub struct DebugContext<'a> {
785 rendered_views: &'a HashMap<usize, ElementBox>,
786 pub font_cache: &'a FontCache,
787 pub app: &'a AppContext,
788}
789
790#[derive(Clone, Copy, Debug, Eq, PartialEq)]
791pub enum Axis {
792 Horizontal,
793 Vertical,
794}
795
796impl Axis {
797 pub fn invert(self) -> Self {
798 match self {
799 Self::Horizontal => Self::Vertical,
800 Self::Vertical => Self::Horizontal,
801 }
802 }
803}
804
805impl ToJson for Axis {
806 fn to_json(&self) -> serde_json::Value {
807 match self {
808 Axis::Horizontal => json!("horizontal"),
809 Axis::Vertical => json!("vertical"),
810 }
811 }
812}
813
814pub trait Vector2FExt {
815 fn along(self, axis: Axis) -> f32;
816}
817
818impl Vector2FExt for Vector2F {
819 fn along(self, axis: Axis) -> f32 {
820 match axis {
821 Axis::Horizontal => self.x(),
822 Axis::Vertical => self.y(),
823 }
824 }
825}
826
827#[derive(Copy, Clone, Debug)]
828pub struct SizeConstraint {
829 pub min: Vector2F,
830 pub max: Vector2F,
831}
832
833impl SizeConstraint {
834 pub fn new(min: Vector2F, max: Vector2F) -> Self {
835 Self { min, max }
836 }
837
838 pub fn strict(size: Vector2F) -> Self {
839 Self {
840 min: size,
841 max: size,
842 }
843 }
844
845 pub fn strict_along(axis: Axis, max: f32) -> Self {
846 match axis {
847 Axis::Horizontal => Self {
848 min: vec2f(max, 0.0),
849 max: vec2f(max, f32::INFINITY),
850 },
851 Axis::Vertical => Self {
852 min: vec2f(0.0, max),
853 max: vec2f(f32::INFINITY, max),
854 },
855 }
856 }
857
858 pub fn max_along(&self, axis: Axis) -> f32 {
859 match axis {
860 Axis::Horizontal => self.max.x(),
861 Axis::Vertical => self.max.y(),
862 }
863 }
864
865 pub fn min_along(&self, axis: Axis) -> f32 {
866 match axis {
867 Axis::Horizontal => self.min.x(),
868 Axis::Vertical => self.min.y(),
869 }
870 }
871
872 pub fn constrain(&self, size: Vector2F) -> Vector2F {
873 vec2f(
874 size.x().min(self.max.x()).max(self.min.x()),
875 size.y().min(self.max.y()).max(self.min.y()),
876 )
877 }
878}
879
880impl Default for SizeConstraint {
881 fn default() -> Self {
882 SizeConstraint {
883 min: Vector2F::zero(),
884 max: Vector2F::splat(f32::INFINITY),
885 }
886 }
887}
888
889impl ToJson for SizeConstraint {
890 fn to_json(&self) -> serde_json::Value {
891 json!({
892 "min": self.min.to_json(),
893 "max": self.max.to_json(),
894 })
895 }
896}
897
898pub struct ChildView {
899 view: AnyViewHandle,
900}
901
902impl ChildView {
903 pub fn new(view: impl Into<AnyViewHandle>) -> Self {
904 Self { view: view.into() }
905 }
906}
907
908impl Element for ChildView {
909 type LayoutState = ();
910 type PaintState = ();
911
912 fn layout(
913 &mut self,
914 constraint: SizeConstraint,
915 cx: &mut LayoutContext,
916 ) -> (Vector2F, Self::LayoutState) {
917 let size = cx.layout(self.view.id(), constraint);
918 (size, ())
919 }
920
921 fn paint(
922 &mut self,
923 bounds: RectF,
924 visible_bounds: RectF,
925 _: &mut Self::LayoutState,
926 cx: &mut PaintContext,
927 ) -> Self::PaintState {
928 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
929 }
930
931 fn dispatch_event(
932 &mut self,
933 event: &Event,
934 _: RectF,
935 _: RectF,
936 _: &mut Self::LayoutState,
937 _: &mut Self::PaintState,
938 cx: &mut EventContext,
939 ) -> bool {
940 cx.dispatch_event(self.view.id(), event)
941 }
942
943 fn rect_for_text_range(
944 &self,
945 range_utf16: Range<usize>,
946 _: RectF,
947 _: RectF,
948 _: &Self::LayoutState,
949 _: &Self::PaintState,
950 cx: &MeasurementContext,
951 ) -> Option<RectF> {
952 cx.rect_for_text_range(self.view.id(), range_utf16)
953 }
954
955 fn debug(
956 &self,
957 bounds: RectF,
958 _: &Self::LayoutState,
959 _: &Self::PaintState,
960 cx: &DebugContext,
961 ) -> serde_json::Value {
962 json!({
963 "type": "ChildView",
964 "view_id": self.view.id(),
965 "bounds": bounds.to_json(),
966 "view": self.view.debug_json(cx.app),
967 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
968 view.debug(cx)
969 } else {
970 json!(null)
971 }
972 })
973 }
974}