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