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