presenter.rs

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