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