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