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