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        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 Action>,
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    fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
304        self.app.upgrade_any_view_handle(handle)
305    }
306}
307
308impl<'a> ElementStateContext for LayoutContext<'a> {
309    fn current_view_id(&self) -> usize {
310        *self.view_stack.last().unwrap()
311    }
312}
313
314pub struct PaintContext<'a> {
315    rendered_views: &'a mut HashMap<usize, ElementBox>,
316    pub scene: &'a mut Scene,
317    pub font_cache: &'a FontCache,
318    pub text_layout_cache: &'a TextLayoutCache,
319    pub app: &'a AppContext,
320}
321
322impl<'a> PaintContext<'a> {
323    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
324        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
325            tree.paint(origin, visible_bounds, self);
326            self.rendered_views.insert(view_id, tree);
327        }
328    }
329}
330
331impl<'a> Deref for PaintContext<'a> {
332    type Target = AppContext;
333
334    fn deref(&self) -> &Self::Target {
335        self.app
336    }
337}
338
339pub struct EventContext<'a> {
340    rendered_views: &'a mut HashMap<usize, ElementBox>,
341    dispatched_actions: Vec<DispatchDirective>,
342    pub font_cache: &'a FontCache,
343    pub text_layout_cache: &'a TextLayoutCache,
344    pub app: &'a mut MutableAppContext,
345    pub notify_count: usize,
346    view_stack: Vec<usize>,
347    invalidated_views: HashSet<usize>,
348}
349
350impl<'a> EventContext<'a> {
351    fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
352        if let Some(mut element) = self.rendered_views.remove(&view_id) {
353            self.view_stack.push(view_id);
354            let result = element.dispatch_event(event, self);
355            self.view_stack.pop();
356            self.rendered_views.insert(view_id, element);
357            result
358        } else {
359            false
360        }
361    }
362
363    pub fn dispatch_action<A: Action>(&mut self, action: A) {
364        self.dispatched_actions.push(DispatchDirective {
365            path: self.view_stack.clone(),
366            action: Box::new(action),
367        });
368    }
369
370    pub fn notify(&mut self) {
371        self.notify_count += 1;
372        if let Some(view_id) = self.view_stack.last() {
373            self.invalidated_views.insert(*view_id);
374        }
375    }
376
377    pub fn notify_count(&self) -> usize {
378        self.notify_count
379    }
380}
381
382impl<'a> Deref for EventContext<'a> {
383    type Target = MutableAppContext;
384
385    fn deref(&self) -> &Self::Target {
386        self.app
387    }
388}
389
390impl<'a> DerefMut for EventContext<'a> {
391    fn deref_mut(&mut self) -> &mut Self::Target {
392        self.app
393    }
394}
395
396pub struct DebugContext<'a> {
397    rendered_views: &'a HashMap<usize, ElementBox>,
398    pub font_cache: &'a FontCache,
399    pub app: &'a AppContext,
400}
401
402#[derive(Clone, Copy, Debug, Eq, PartialEq)]
403pub enum Axis {
404    Horizontal,
405    Vertical,
406}
407
408impl Axis {
409    pub fn invert(self) -> Self {
410        match self {
411            Self::Horizontal => Self::Vertical,
412            Self::Vertical => Self::Horizontal,
413        }
414    }
415}
416
417impl ToJson for Axis {
418    fn to_json(&self) -> serde_json::Value {
419        match self {
420            Axis::Horizontal => json!("horizontal"),
421            Axis::Vertical => json!("vertical"),
422        }
423    }
424}
425
426pub trait Vector2FExt {
427    fn along(self, axis: Axis) -> f32;
428}
429
430impl Vector2FExt for Vector2F {
431    fn along(self, axis: Axis) -> f32 {
432        match axis {
433            Axis::Horizontal => self.x(),
434            Axis::Vertical => self.y(),
435        }
436    }
437}
438
439#[derive(Copy, Clone, Debug)]
440pub struct SizeConstraint {
441    pub min: Vector2F,
442    pub max: Vector2F,
443}
444
445impl SizeConstraint {
446    pub fn new(min: Vector2F, max: Vector2F) -> Self {
447        Self { min, max }
448    }
449
450    pub fn strict(size: Vector2F) -> Self {
451        Self {
452            min: size,
453            max: size,
454        }
455    }
456
457    pub fn strict_along(axis: Axis, max: f32) -> Self {
458        match axis {
459            Axis::Horizontal => Self {
460                min: vec2f(max, 0.0),
461                max: vec2f(max, f32::INFINITY),
462            },
463            Axis::Vertical => Self {
464                min: vec2f(0.0, max),
465                max: vec2f(f32::INFINITY, max),
466            },
467        }
468    }
469
470    pub fn max_along(&self, axis: Axis) -> f32 {
471        match axis {
472            Axis::Horizontal => self.max.x(),
473            Axis::Vertical => self.max.y(),
474        }
475    }
476
477    pub fn min_along(&self, axis: Axis) -> f32 {
478        match axis {
479            Axis::Horizontal => self.min.x(),
480            Axis::Vertical => self.min.y(),
481        }
482    }
483
484    pub fn constrain(&self, size: Vector2F) -> Vector2F {
485        vec2f(
486            size.x().min(self.max.x()).max(self.min.x()),
487            size.y().min(self.max.y()).max(self.min.y()),
488        )
489    }
490}
491
492impl ToJson for SizeConstraint {
493    fn to_json(&self) -> serde_json::Value {
494        json!({
495            "min": self.min.to_json(),
496            "max": self.max.to_json(),
497        })
498    }
499}
500
501pub struct ChildView {
502    view: AnyViewHandle,
503}
504
505impl ChildView {
506    pub fn new(view: impl Into<AnyViewHandle>) -> Self {
507        Self { view: view.into() }
508    }
509}
510
511impl Element for ChildView {
512    type LayoutState = ();
513    type PaintState = ();
514
515    fn layout(
516        &mut self,
517        constraint: SizeConstraint,
518        cx: &mut LayoutContext,
519    ) -> (Vector2F, Self::LayoutState) {
520        let size = cx.layout(self.view.id(), constraint);
521        (size, ())
522    }
523
524    fn paint(
525        &mut self,
526        bounds: RectF,
527        visible_bounds: RectF,
528        _: &mut Self::LayoutState,
529        cx: &mut PaintContext,
530    ) -> Self::PaintState {
531        cx.paint(self.view.id(), bounds.origin(), visible_bounds);
532    }
533
534    fn dispatch_event(
535        &mut self,
536        event: &Event,
537        _: RectF,
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}