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