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