1use crate::{
2 app::{AppContext, MutableAppContext, WindowInvalidation},
3 elements::Element,
4 font_cache::FontCache,
5 geometry::rect::RectF,
6 json::{self, ToJson},
7 platform::{CursorStyle, Event},
8 text_layout::TextLayoutCache,
9 Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox,
10 ElementStateContext, Entity, FontSystem, ModelHandle, ReadModel, ReadView, Scene,
11 UpgradeModelHandle, UpgradeViewHandle, View, ViewHandle, WeakModelHandle, WeakViewHandle,
12};
13use pathfinder_geometry::vector::{vec2f, Vector2F};
14use serde_json::json;
15use std::{
16 collections::{HashMap, HashSet},
17 ops::{Deref, DerefMut},
18 sync::Arc,
19};
20
21pub struct Presenter {
22 window_id: usize,
23 pub(crate) rendered_views: HashMap<usize, ElementBox>,
24 parents: HashMap<usize, usize>,
25 cursor_styles: Vec<(RectF, CursorStyle)>,
26 font_cache: Arc<FontCache>,
27 text_layout_cache: TextLayoutCache,
28 asset_cache: Arc<AssetCache>,
29 last_mouse_moved_event: Option<Event>,
30 titlebar_height: f32,
31}
32
33impl Presenter {
34 pub fn new(
35 window_id: usize,
36 titlebar_height: f32,
37 font_cache: Arc<FontCache>,
38 text_layout_cache: TextLayoutCache,
39 asset_cache: Arc<AssetCache>,
40 cx: &mut MutableAppContext,
41 ) -> Self {
42 Self {
43 window_id,
44 rendered_views: cx.render_views(window_id, titlebar_height),
45 parents: HashMap::new(),
46 cursor_styles: Default::default(),
47 font_cache,
48 text_layout_cache,
49 asset_cache,
50 last_mouse_moved_event: None,
51 titlebar_height,
52 }
53 }
54
55 pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
56 if let Some(view_id) = app.focused_view_id(self.window_id) {
57 self.dispatch_path_from(view_id)
58 } else {
59 Vec::new()
60 }
61 }
62
63 pub(crate) fn dispatch_path_from(&self, mut view_id: usize) -> Vec<usize> {
64 let mut path = Vec::new();
65 path.push(view_id);
66 while let Some(parent_id) = self.parents.get(&view_id).copied() {
67 path.push(parent_id);
68 view_id = parent_id;
69 }
70 path.reverse();
71 path
72 }
73
74 pub fn invalidate(
75 &mut self,
76 invalidation: &mut WindowInvalidation,
77 cx: &mut MutableAppContext,
78 ) {
79 cx.start_frame();
80 for view_id in &invalidation.removed {
81 invalidation.updated.remove(&view_id);
82 self.rendered_views.remove(&view_id);
83 self.parents.remove(&view_id);
84 }
85 for view_id in &invalidation.updated {
86 self.rendered_views.insert(
87 *view_id,
88 cx.render_view(self.window_id, *view_id, self.titlebar_height, false)
89 .unwrap(),
90 );
91 }
92 }
93
94 pub fn refresh(&mut self, invalidation: &mut WindowInvalidation, cx: &mut MutableAppContext) {
95 self.invalidate(invalidation, cx);
96 for (view_id, view) in &mut self.rendered_views {
97 if !invalidation.updated.contains(view_id) {
98 *view = cx
99 .render_view(self.window_id, *view_id, self.titlebar_height, true)
100 .unwrap();
101 }
102 }
103 }
104
105 pub fn build_scene(
106 &mut self,
107 window_size: Vector2F,
108 scale_factor: f32,
109 refreshing: bool,
110 cx: &mut MutableAppContext,
111 ) -> Scene {
112 let mut scene = Scene::new(scale_factor);
113
114 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
115 self.layout(window_size, refreshing, cx);
116 let mut paint_cx = self.build_paint_context(&mut scene, cx);
117 paint_cx.paint(
118 root_view_id,
119 Vector2F::zero(),
120 RectF::new(Vector2F::zero(), window_size),
121 );
122 self.text_layout_cache.finish_frame();
123 self.cursor_styles = scene.cursor_styles();
124
125 if let Some(event) = self.last_mouse_moved_event.clone() {
126 self.dispatch_event(event, cx)
127 }
128 } else {
129 log::error!("could not find root_view_id for window {}", self.window_id);
130 }
131
132 scene
133 }
134
135 fn layout(&mut self, size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
136 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
137 self.build_layout_context(refreshing, cx)
138 .layout(root_view_id, SizeConstraint::strict(size));
139 }
140 }
141
142 pub fn build_layout_context<'a>(
143 &'a mut self,
144 refreshing: bool,
145 cx: &'a mut MutableAppContext,
146 ) -> LayoutContext<'a> {
147 LayoutContext {
148 rendered_views: &mut self.rendered_views,
149 parents: &mut self.parents,
150 refreshing,
151 font_cache: &self.font_cache,
152 font_system: cx.platform().fonts(),
153 text_layout_cache: &self.text_layout_cache,
154 asset_cache: &self.asset_cache,
155 view_stack: Vec::new(),
156 app: cx,
157 }
158 }
159
160 pub fn build_paint_context<'a>(
161 &'a mut self,
162 scene: &'a mut Scene,
163 cx: &'a mut MutableAppContext,
164 ) -> PaintContext {
165 PaintContext {
166 scene,
167 font_cache: &self.font_cache,
168 text_layout_cache: &self.text_layout_cache,
169 rendered_views: &mut self.rendered_views,
170 app: cx,
171 }
172 }
173
174 pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) {
175 if let Some(root_view_id) = cx.root_view_id(self.window_id) {
176 match event {
177 Event::MouseMoved {
178 position,
179 left_mouse_down,
180 } => {
181 self.last_mouse_moved_event = Some(event.clone());
182
183 if !left_mouse_down {
184 let mut style_to_assign = CursorStyle::Arrow;
185 for (bounds, style) in self.cursor_styles.iter().rev() {
186 if bounds.contains_point(position) {
187 style_to_assign = *style;
188 break;
189 }
190 }
191 cx.platform().set_cursor_style(style_to_assign);
192 }
193 }
194 Event::LeftMouseDragged { position } => {
195 self.last_mouse_moved_event = Some(Event::MouseMoved {
196 position,
197 left_mouse_down: true,
198 });
199 }
200 _ => {}
201 }
202
203 let mut event_cx = self.build_event_context(cx);
204 event_cx.dispatch_event(root_view_id, &event);
205
206 let invalidated_views = event_cx.invalidated_views;
207 let dispatch_directives = event_cx.dispatched_actions;
208
209 for view_id in invalidated_views {
210 cx.notify_view(self.window_id, view_id);
211 }
212 for directive in dispatch_directives {
213 cx.dispatch_action_any(self.window_id, &directive.path, directive.action.as_ref());
214 }
215 }
216 }
217
218 pub fn build_event_context<'a>(
219 &'a mut self,
220 cx: &'a mut MutableAppContext,
221 ) -> EventContext<'a> {
222 EventContext {
223 rendered_views: &mut self.rendered_views,
224 dispatched_actions: Default::default(),
225 font_cache: &self.font_cache,
226 text_layout_cache: &self.text_layout_cache,
227 view_stack: Default::default(),
228 invalidated_views: Default::default(),
229 notify_count: 0,
230 app: cx,
231 }
232 }
233
234 pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
235 let view = cx.root_view(self.window_id)?;
236 Some(json!({
237 "root_view": view.debug_json(cx),
238 "root_element": self.rendered_views.get(&view.id())
239 .map(|root_element| {
240 root_element.debug(&DebugContext {
241 rendered_views: &self.rendered_views,
242 font_cache: &self.font_cache,
243 app: cx,
244 })
245 })
246 }))
247 }
248}
249
250pub struct DispatchDirective {
251 pub path: Vec<usize>,
252 pub action: Box<dyn Action>,
253}
254
255pub struct LayoutContext<'a> {
256 rendered_views: &'a mut HashMap<usize, ElementBox>,
257 parents: &'a mut HashMap<usize, usize>,
258 view_stack: Vec<usize>,
259 pub refreshing: bool,
260 pub font_cache: &'a Arc<FontCache>,
261 pub font_system: Arc<dyn FontSystem>,
262 pub text_layout_cache: &'a TextLayoutCache,
263 pub asset_cache: &'a AssetCache,
264 pub app: &'a mut MutableAppContext,
265}
266
267impl<'a> LayoutContext<'a> {
268 fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
269 if let Some(parent_id) = self.view_stack.last() {
270 self.parents.insert(view_id, *parent_id);
271 }
272 self.view_stack.push(view_id);
273 let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
274 let size = rendered_view.layout(constraint, self);
275 self.rendered_views.insert(view_id, rendered_view);
276 self.view_stack.pop();
277 size
278 }
279}
280
281impl<'a> Deref for LayoutContext<'a> {
282 type Target = MutableAppContext;
283
284 fn deref(&self) -> &Self::Target {
285 self.app
286 }
287}
288
289impl<'a> DerefMut for LayoutContext<'a> {
290 fn deref_mut(&mut self) -> &mut Self::Target {
291 self.app
292 }
293}
294
295impl<'a> ReadView for LayoutContext<'a> {
296 fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
297 self.app.read_view(handle)
298 }
299}
300
301impl<'a> ReadModel for LayoutContext<'a> {
302 fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
303 self.app.read_model(handle)
304 }
305}
306
307impl<'a> UpgradeModelHandle for LayoutContext<'a> {
308 fn upgrade_model_handle<T: Entity>(
309 &self,
310 handle: &WeakModelHandle<T>,
311 ) -> Option<ModelHandle<T>> {
312 self.app.upgrade_model_handle(handle)
313 }
314
315 fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
316 self.app.model_handle_is_upgradable(handle)
317 }
318
319 fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
320 self.app.upgrade_any_model_handle(handle)
321 }
322}
323
324impl<'a> UpgradeViewHandle for LayoutContext<'a> {
325 fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
326 self.app.upgrade_view_handle(handle)
327 }
328
329 fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
330 self.app.upgrade_any_view_handle(handle)
331 }
332}
333
334impl<'a> ElementStateContext for LayoutContext<'a> {
335 fn current_view_id(&self) -> usize {
336 *self.view_stack.last().unwrap()
337 }
338}
339
340pub struct PaintContext<'a> {
341 rendered_views: &'a mut HashMap<usize, ElementBox>,
342 pub scene: &'a mut Scene,
343 pub font_cache: &'a FontCache,
344 pub text_layout_cache: &'a TextLayoutCache,
345 pub app: &'a AppContext,
346}
347
348impl<'a> PaintContext<'a> {
349 fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
350 if let Some(mut tree) = self.rendered_views.remove(&view_id) {
351 tree.paint(origin, visible_bounds, self);
352 self.rendered_views.insert(view_id, tree);
353 }
354 }
355}
356
357impl<'a> Deref for PaintContext<'a> {
358 type Target = AppContext;
359
360 fn deref(&self) -> &Self::Target {
361 self.app
362 }
363}
364
365pub struct EventContext<'a> {
366 rendered_views: &'a mut HashMap<usize, ElementBox>,
367 dispatched_actions: Vec<DispatchDirective>,
368 pub font_cache: &'a FontCache,
369 pub text_layout_cache: &'a TextLayoutCache,
370 pub app: &'a mut MutableAppContext,
371 pub notify_count: usize,
372 view_stack: Vec<usize>,
373 invalidated_views: HashSet<usize>,
374}
375
376impl<'a> EventContext<'a> {
377 fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
378 if let Some(mut element) = self.rendered_views.remove(&view_id) {
379 self.view_stack.push(view_id);
380 let result = element.dispatch_event(event, self);
381 self.view_stack.pop();
382 self.rendered_views.insert(view_id, element);
383 result
384 } else {
385 false
386 }
387 }
388
389 pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
390 self.dispatched_actions.push(DispatchDirective {
391 path: self.view_stack.clone(),
392 action,
393 });
394 }
395
396 pub fn dispatch_action<A: Action>(&mut self, action: A) {
397 self.dispatch_any_action(Box::new(action));
398 }
399
400 pub fn notify(&mut self) {
401 self.notify_count += 1;
402 if let Some(view_id) = self.view_stack.last() {
403 self.invalidated_views.insert(*view_id);
404 }
405 }
406
407 pub fn notify_count(&self) -> usize {
408 self.notify_count
409 }
410}
411
412impl<'a> Deref for EventContext<'a> {
413 type Target = MutableAppContext;
414
415 fn deref(&self) -> &Self::Target {
416 self.app
417 }
418}
419
420impl<'a> DerefMut for EventContext<'a> {
421 fn deref_mut(&mut self) -> &mut Self::Target {
422 self.app
423 }
424}
425
426pub struct DebugContext<'a> {
427 rendered_views: &'a HashMap<usize, ElementBox>,
428 pub font_cache: &'a FontCache,
429 pub app: &'a AppContext,
430}
431
432#[derive(Clone, Copy, Debug, Eq, PartialEq)]
433pub enum Axis {
434 Horizontal,
435 Vertical,
436}
437
438impl Axis {
439 pub fn invert(self) -> Self {
440 match self {
441 Self::Horizontal => Self::Vertical,
442 Self::Vertical => Self::Horizontal,
443 }
444 }
445}
446
447impl ToJson for Axis {
448 fn to_json(&self) -> serde_json::Value {
449 match self {
450 Axis::Horizontal => json!("horizontal"),
451 Axis::Vertical => json!("vertical"),
452 }
453 }
454}
455
456pub trait Vector2FExt {
457 fn along(self, axis: Axis) -> f32;
458}
459
460impl Vector2FExt for Vector2F {
461 fn along(self, axis: Axis) -> f32 {
462 match axis {
463 Axis::Horizontal => self.x(),
464 Axis::Vertical => self.y(),
465 }
466 }
467}
468
469#[derive(Copy, Clone, Debug)]
470pub struct SizeConstraint {
471 pub min: Vector2F,
472 pub max: Vector2F,
473}
474
475impl SizeConstraint {
476 pub fn new(min: Vector2F, max: Vector2F) -> Self {
477 Self { min, max }
478 }
479
480 pub fn strict(size: Vector2F) -> Self {
481 Self {
482 min: size,
483 max: size,
484 }
485 }
486
487 pub fn strict_along(axis: Axis, max: f32) -> Self {
488 match axis {
489 Axis::Horizontal => Self {
490 min: vec2f(max, 0.0),
491 max: vec2f(max, f32::INFINITY),
492 },
493 Axis::Vertical => Self {
494 min: vec2f(0.0, max),
495 max: vec2f(f32::INFINITY, max),
496 },
497 }
498 }
499
500 pub fn max_along(&self, axis: Axis) -> f32 {
501 match axis {
502 Axis::Horizontal => self.max.x(),
503 Axis::Vertical => self.max.y(),
504 }
505 }
506
507 pub fn min_along(&self, axis: Axis) -> f32 {
508 match axis {
509 Axis::Horizontal => self.min.x(),
510 Axis::Vertical => self.min.y(),
511 }
512 }
513
514 pub fn constrain(&self, size: Vector2F) -> Vector2F {
515 vec2f(
516 size.x().min(self.max.x()).max(self.min.x()),
517 size.y().min(self.max.y()).max(self.min.y()),
518 )
519 }
520}
521
522impl ToJson for SizeConstraint {
523 fn to_json(&self) -> serde_json::Value {
524 json!({
525 "min": self.min.to_json(),
526 "max": self.max.to_json(),
527 })
528 }
529}
530
531pub struct ChildView {
532 view: AnyViewHandle,
533}
534
535impl ChildView {
536 pub fn new(view: impl Into<AnyViewHandle>) -> Self {
537 Self { view: view.into() }
538 }
539}
540
541impl Element for ChildView {
542 type LayoutState = ();
543 type PaintState = ();
544
545 fn layout(
546 &mut self,
547 constraint: SizeConstraint,
548 cx: &mut LayoutContext,
549 ) -> (Vector2F, Self::LayoutState) {
550 let size = cx.layout(self.view.id(), constraint);
551 (size, ())
552 }
553
554 fn paint(
555 &mut self,
556 bounds: RectF,
557 visible_bounds: RectF,
558 _: &mut Self::LayoutState,
559 cx: &mut PaintContext,
560 ) -> Self::PaintState {
561 cx.paint(self.view.id(), bounds.origin(), visible_bounds);
562 }
563
564 fn dispatch_event(
565 &mut self,
566 event: &Event,
567 _: RectF,
568 _: RectF,
569 _: &mut Self::LayoutState,
570 _: &mut Self::PaintState,
571 cx: &mut EventContext,
572 ) -> bool {
573 cx.dispatch_event(self.view.id(), event)
574 }
575
576 fn debug(
577 &self,
578 bounds: RectF,
579 _: &Self::LayoutState,
580 _: &Self::PaintState,
581 cx: &DebugContext,
582 ) -> serde_json::Value {
583 json!({
584 "type": "ChildView",
585 "view_id": self.view.id(),
586 "bounds": bounds.to_json(),
587 "view": self.view.debug_json(cx.app),
588 "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
589 view.debug(cx)
590 } else {
591 json!(null)
592 }
593 })
594 }
595}