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    scene::CursorRegion,
  9    text_layout::TextLayoutCache,
 10    Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox, Entity,
 11    FontSystem, ModelHandle, MouseRegion, MouseRegionId, ReadModel, ReadView, RenderContext,
 12    RenderParams, Scene, UpgradeModelHandle, UpgradeViewHandle, View, ViewHandle, WeakModelHandle,
 13    WeakViewHandle,
 14};
 15use pathfinder_geometry::vector::{vec2f, Vector2F};
 16use serde_json::json;
 17use std::{
 18    collections::{HashMap, HashSet},
 19    marker::PhantomData,
 20    ops::{Deref, DerefMut},
 21    sync::Arc,
 22};
 23
 24pub struct Presenter {
 25    window_id: usize,
 26    pub(crate) rendered_views: HashMap<usize, ElementBox>,
 27    parents: HashMap<usize, usize>,
 28    cursor_regions: Vec<CursorRegion>,
 29    mouse_regions: Vec<MouseRegion>,
 30    font_cache: Arc<FontCache>,
 31    text_layout_cache: TextLayoutCache,
 32    asset_cache: Arc<AssetCache>,
 33    last_mouse_moved_event: Option<Event>,
 34    hovered_region_ids: HashSet<MouseRegionId>,
 35    clicked_region: Option<MouseRegion>,
 36    prev_drag_position: Option<Vector2F>,
 37    titlebar_height: f32,
 38}
 39
 40impl Presenter {
 41    pub fn new(
 42        window_id: usize,
 43        titlebar_height: f32,
 44        font_cache: Arc<FontCache>,
 45        text_layout_cache: TextLayoutCache,
 46        asset_cache: Arc<AssetCache>,
 47        cx: &mut MutableAppContext,
 48    ) -> Self {
 49        Self {
 50            window_id,
 51            rendered_views: cx.render_views(window_id, titlebar_height),
 52            parents: HashMap::new(),
 53            cursor_regions: Default::default(),
 54            mouse_regions: Default::default(),
 55            font_cache,
 56            text_layout_cache,
 57            asset_cache,
 58            last_mouse_moved_event: None,
 59            hovered_region_ids: Default::default(),
 60            clicked_region: None,
 61            prev_drag_position: None,
 62            titlebar_height,
 63        }
 64    }
 65
 66    pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
 67        if let Some(view_id) = app.focused_view_id(self.window_id) {
 68            self.dispatch_path_from(view_id)
 69        } else {
 70            Vec::new()
 71        }
 72    }
 73
 74    pub(crate) fn dispatch_path_from(&self, mut view_id: usize) -> Vec<usize> {
 75        let mut path = Vec::new();
 76        path.push(view_id);
 77        while let Some(parent_id) = self.parents.get(&view_id).copied() {
 78            path.push(parent_id);
 79            view_id = parent_id;
 80        }
 81        path.reverse();
 82        path
 83    }
 84
 85    pub fn invalidate(
 86        &mut self,
 87        invalidation: &mut WindowInvalidation,
 88        cx: &mut MutableAppContext,
 89    ) {
 90        cx.start_frame();
 91        for view_id in &invalidation.removed {
 92            invalidation.updated.remove(&view_id);
 93            self.rendered_views.remove(&view_id);
 94            self.parents.remove(&view_id);
 95        }
 96        for view_id in &invalidation.updated {
 97            self.rendered_views.insert(
 98                *view_id,
 99                cx.render_view(RenderParams {
100                    window_id: self.window_id,
101                    view_id: *view_id,
102                    titlebar_height: self.titlebar_height,
103                    hovered_region_ids: self.hovered_region_ids.clone(),
104                    clicked_region_id: self.clicked_region.as_ref().map(MouseRegion::id),
105                    refreshing: false,
106                })
107                .unwrap(),
108            );
109        }
110    }
111
112    pub fn refresh(&mut self, invalidation: &mut WindowInvalidation, cx: &mut MutableAppContext) {
113        self.invalidate(invalidation, cx);
114        for (view_id, view) in &mut self.rendered_views {
115            if !invalidation.updated.contains(view_id) {
116                *view = cx
117                    .render_view(RenderParams {
118                        window_id: self.window_id,
119                        view_id: *view_id,
120                        titlebar_height: self.titlebar_height,
121                        hovered_region_ids: self.hovered_region_ids.clone(),
122                        clicked_region_id: self.clicked_region.as_ref().map(MouseRegion::id),
123                        refreshing: true,
124                    })
125                    .unwrap();
126            }
127        }
128    }
129
130    pub fn build_scene(
131        &mut self,
132        window_size: Vector2F,
133        scale_factor: f32,
134        refreshing: bool,
135        cx: &mut MutableAppContext,
136    ) -> Scene {
137        let mut scene = Scene::new(scale_factor);
138
139        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
140            self.layout(window_size, refreshing, cx);
141            let mut paint_cx = self.build_paint_context(&mut scene, cx);
142            paint_cx.paint(
143                root_view_id,
144                Vector2F::zero(),
145                RectF::new(Vector2F::zero(), window_size),
146            );
147            self.text_layout_cache.finish_frame();
148            self.cursor_regions = scene.cursor_regions();
149            self.mouse_regions = scene.mouse_regions();
150
151            if cx.window_is_active(self.window_id) {
152                if let Some(event) = self.last_mouse_moved_event.clone() {
153                    self.dispatch_event(event, cx)
154                }
155            }
156        } else {
157            log::error!("could not find root_view_id for window {}", self.window_id);
158        }
159
160        scene
161    }
162
163    fn layout(&mut self, size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
164        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
165            self.build_layout_context(refreshing, cx)
166                .layout(root_view_id, SizeConstraint::strict(size));
167        }
168    }
169
170    pub fn build_layout_context<'a>(
171        &'a mut self,
172        refreshing: bool,
173        cx: &'a mut MutableAppContext,
174    ) -> LayoutContext<'a> {
175        LayoutContext {
176            rendered_views: &mut self.rendered_views,
177            parents: &mut self.parents,
178            font_cache: &self.font_cache,
179            font_system: cx.platform().fonts(),
180            text_layout_cache: &self.text_layout_cache,
181            asset_cache: &self.asset_cache,
182            view_stack: Vec::new(),
183            refreshing,
184            hovered_region_ids: self.hovered_region_ids.clone(),
185            clicked_region_id: self.clicked_region.as_ref().map(MouseRegion::id),
186            titlebar_height: self.titlebar_height,
187            app: cx,
188        }
189    }
190
191    pub fn build_paint_context<'a>(
192        &'a mut self,
193        scene: &'a mut Scene,
194        cx: &'a mut MutableAppContext,
195    ) -> PaintContext {
196        PaintContext {
197            scene,
198            font_cache: &self.font_cache,
199            text_layout_cache: &self.text_layout_cache,
200            rendered_views: &mut self.rendered_views,
201            view_stack: Vec::new(),
202            app: cx,
203        }
204    }
205
206    pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) {
207        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
208            let mut invalidated_views = Vec::new();
209            let mut hovered_regions = Vec::new();
210            let mut unhovered_regions = Vec::new();
211            let mut clicked_region = None;
212            let mut dragged_region = None;
213
214            match event {
215                Event::LeftMouseDown { position, .. } => {
216                    for region in self.mouse_regions.iter().rev() {
217                        if region.bounds.contains_point(position) {
218                            invalidated_views.push(region.view_id);
219                            self.clicked_region = Some(region.clone());
220                            self.prev_drag_position = Some(position);
221                            break;
222                        }
223                    }
224                }
225                Event::LeftMouseUp {
226                    position,
227                    click_count,
228                    ..
229                } => {
230                    self.prev_drag_position.take();
231                    if let Some(region) = self.clicked_region.take() {
232                        invalidated_views.push(region.view_id);
233                        if region.bounds.contains_point(position) {
234                            clicked_region = Some((region, position, click_count));
235                        }
236                    }
237                }
238                Event::MouseMoved {
239                    position,
240                    left_mouse_down,
241                } => {
242                    self.last_mouse_moved_event = Some(event.clone());
243
244                    if !left_mouse_down {
245                        let mut style_to_assign = CursorStyle::Arrow;
246                        for region in self.cursor_regions.iter().rev() {
247                            if region.bounds.contains_point(position) {
248                                style_to_assign = region.style;
249                                break;
250                            }
251                        }
252                        cx.platform().set_cursor_style(style_to_assign);
253
254                        for region in self.mouse_regions.iter().rev() {
255                            let region_id = region.id();
256                            if region.bounds.contains_point(position) {
257                                if !self.hovered_region_ids.contains(&region_id) {
258                                    invalidated_views.push(region.view_id);
259                                    hovered_regions.push(region.clone());
260                                    self.hovered_region_ids.insert(region_id);
261                                }
262                            } else {
263                                if self.hovered_region_ids.contains(&region_id) {
264                                    invalidated_views.push(region.view_id);
265                                    unhovered_regions.push(region.clone());
266                                    self.hovered_region_ids.remove(&region_id);
267                                }
268                            }
269                        }
270                    }
271                }
272                Event::LeftMouseDragged { position } => {
273                    if let Some((clicked_region, prev_drag_position)) = self
274                        .clicked_region
275                        .as_ref()
276                        .zip(self.prev_drag_position.as_mut())
277                    {
278                        dragged_region =
279                            Some((clicked_region.clone(), position - *prev_drag_position));
280                        *prev_drag_position = position;
281                    }
282
283                    self.last_mouse_moved_event = Some(Event::MouseMoved {
284                        position,
285                        left_mouse_down: true,
286                    });
287                }
288                _ => {}
289            }
290
291            let mut event_cx = self.build_event_context(cx);
292            for unhovered_region in unhovered_regions {
293                if let Some(hover_callback) = unhovered_region.hover {
294                    event_cx.with_current_view(unhovered_region.view_id, |event_cx| {
295                        hover_callback(false, event_cx);
296                    })
297                }
298            }
299
300            for hovered_region in hovered_regions {
301                if let Some(hover_callback) = hovered_region.hover {
302                    event_cx.with_current_view(hovered_region.view_id, |event_cx| {
303                        hover_callback(true, event_cx);
304                    })
305                }
306            }
307
308            if let Some((clicked_region, position, click_count)) = clicked_region {
309                if let Some(click_callback) = clicked_region.click {
310                    event_cx.with_current_view(clicked_region.view_id, |event_cx| {
311                        click_callback(position, click_count, event_cx);
312                    })
313                }
314            }
315
316            if let Some((dragged_region, delta)) = dragged_region {
317                if let Some(drag_callback) = dragged_region.drag {
318                    event_cx.with_current_view(dragged_region.view_id, |event_cx| {
319                        drag_callback(delta, event_cx);
320                    })
321                }
322            }
323
324            event_cx.dispatch_event(root_view_id, &event);
325
326            invalidated_views.extend(event_cx.invalidated_views);
327            let dispatch_directives = event_cx.dispatched_actions;
328
329            for view_id in invalidated_views {
330                cx.notify_view(self.window_id, view_id);
331            }
332            for directive in dispatch_directives {
333                cx.dispatch_action_any(self.window_id, &directive.path, directive.action.as_ref());
334            }
335        }
336    }
337
338    pub fn build_event_context<'a>(
339        &'a mut self,
340        cx: &'a mut MutableAppContext,
341    ) -> EventContext<'a> {
342        EventContext {
343            rendered_views: &mut self.rendered_views,
344            dispatched_actions: Default::default(),
345            font_cache: &self.font_cache,
346            text_layout_cache: &self.text_layout_cache,
347            view_stack: Default::default(),
348            invalidated_views: Default::default(),
349            notify_count: 0,
350            app: cx,
351        }
352    }
353
354    pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
355        let view = cx.root_view(self.window_id)?;
356        Some(json!({
357            "root_view": view.debug_json(cx),
358            "root_element": self.rendered_views.get(&view.id())
359                .map(|root_element| {
360                    root_element.debug(&DebugContext {
361                        rendered_views: &self.rendered_views,
362                        font_cache: &self.font_cache,
363                        app: cx,
364                    })
365                })
366        }))
367    }
368}
369
370pub struct DispatchDirective {
371    pub path: Vec<usize>,
372    pub action: Box<dyn Action>,
373}
374
375pub struct LayoutContext<'a> {
376    rendered_views: &'a mut HashMap<usize, ElementBox>,
377    parents: &'a mut HashMap<usize, usize>,
378    view_stack: Vec<usize>,
379    pub font_cache: &'a Arc<FontCache>,
380    pub font_system: Arc<dyn FontSystem>,
381    pub text_layout_cache: &'a TextLayoutCache,
382    pub asset_cache: &'a AssetCache,
383    pub app: &'a mut MutableAppContext,
384    pub refreshing: bool,
385    titlebar_height: f32,
386    hovered_region_ids: HashSet<MouseRegionId>,
387    clicked_region_id: Option<MouseRegionId>,
388}
389
390impl<'a> LayoutContext<'a> {
391    fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
392        if let Some(parent_id) = self.view_stack.last() {
393            self.parents.insert(view_id, *parent_id);
394        }
395        self.view_stack.push(view_id);
396        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
397        let size = rendered_view.layout(constraint, self);
398        self.rendered_views.insert(view_id, rendered_view);
399        self.view_stack.pop();
400        size
401    }
402
403    pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
404    where
405        F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
406        V: View,
407    {
408        handle.update(self.app, |view, cx| {
409            let mut render_cx = RenderContext {
410                app: cx,
411                window_id: handle.window_id(),
412                view_id: handle.id(),
413                view_type: PhantomData,
414                titlebar_height: self.titlebar_height,
415                hovered_region_ids: self.hovered_region_ids.clone(),
416                clicked_region_id: self.clicked_region_id,
417                refreshing: self.refreshing,
418            };
419            f(view, &mut render_cx)
420        })
421    }
422}
423
424impl<'a> Deref for LayoutContext<'a> {
425    type Target = MutableAppContext;
426
427    fn deref(&self) -> &Self::Target {
428        self.app
429    }
430}
431
432impl<'a> DerefMut for LayoutContext<'a> {
433    fn deref_mut(&mut self) -> &mut Self::Target {
434        self.app
435    }
436}
437
438impl<'a> ReadView for LayoutContext<'a> {
439    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
440        self.app.read_view(handle)
441    }
442}
443
444impl<'a> ReadModel for LayoutContext<'a> {
445    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
446        self.app.read_model(handle)
447    }
448}
449
450impl<'a> UpgradeModelHandle for LayoutContext<'a> {
451    fn upgrade_model_handle<T: Entity>(
452        &self,
453        handle: &WeakModelHandle<T>,
454    ) -> Option<ModelHandle<T>> {
455        self.app.upgrade_model_handle(handle)
456    }
457
458    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
459        self.app.model_handle_is_upgradable(handle)
460    }
461
462    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
463        self.app.upgrade_any_model_handle(handle)
464    }
465}
466
467impl<'a> UpgradeViewHandle for LayoutContext<'a> {
468    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
469        self.app.upgrade_view_handle(handle)
470    }
471
472    fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
473        self.app.upgrade_any_view_handle(handle)
474    }
475}
476
477pub struct PaintContext<'a> {
478    rendered_views: &'a mut HashMap<usize, ElementBox>,
479    view_stack: Vec<usize>,
480    pub scene: &'a mut Scene,
481    pub font_cache: &'a FontCache,
482    pub text_layout_cache: &'a TextLayoutCache,
483    pub app: &'a AppContext,
484}
485
486impl<'a> PaintContext<'a> {
487    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
488        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
489            self.view_stack.push(view_id);
490            tree.paint(origin, visible_bounds, self);
491            self.rendered_views.insert(view_id, tree);
492            self.view_stack.pop();
493        }
494    }
495
496    pub fn current_view_id(&self) -> usize {
497        *self.view_stack.last().unwrap()
498    }
499}
500
501impl<'a> Deref for PaintContext<'a> {
502    type Target = AppContext;
503
504    fn deref(&self) -> &Self::Target {
505        self.app
506    }
507}
508
509pub struct EventContext<'a> {
510    rendered_views: &'a mut HashMap<usize, ElementBox>,
511    dispatched_actions: Vec<DispatchDirective>,
512    pub font_cache: &'a FontCache,
513    pub text_layout_cache: &'a TextLayoutCache,
514    pub app: &'a mut MutableAppContext,
515    pub notify_count: usize,
516    view_stack: Vec<usize>,
517    invalidated_views: HashSet<usize>,
518}
519
520impl<'a> EventContext<'a> {
521    fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
522        if let Some(mut element) = self.rendered_views.remove(&view_id) {
523            let result =
524                self.with_current_view(view_id, |this| element.dispatch_event(event, this));
525            self.rendered_views.insert(view_id, element);
526            result
527        } else {
528            false
529        }
530    }
531
532    fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
533    where
534        F: FnOnce(&mut Self) -> T,
535    {
536        self.view_stack.push(view_id);
537        let result = f(self);
538        self.view_stack.pop();
539        result
540    }
541
542    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
543        self.dispatched_actions.push(DispatchDirective {
544            path: self.view_stack.clone(),
545            action,
546        });
547    }
548
549    pub fn dispatch_action<A: Action>(&mut self, action: A) {
550        self.dispatch_any_action(Box::new(action));
551    }
552
553    pub fn notify(&mut self) {
554        self.notify_count += 1;
555        if let Some(view_id) = self.view_stack.last() {
556            self.invalidated_views.insert(*view_id);
557        }
558    }
559
560    pub fn notify_count(&self) -> usize {
561        self.notify_count
562    }
563}
564
565impl<'a> Deref for EventContext<'a> {
566    type Target = MutableAppContext;
567
568    fn deref(&self) -> &Self::Target {
569        self.app
570    }
571}
572
573impl<'a> DerefMut for EventContext<'a> {
574    fn deref_mut(&mut self) -> &mut Self::Target {
575        self.app
576    }
577}
578
579pub struct DebugContext<'a> {
580    rendered_views: &'a HashMap<usize, ElementBox>,
581    pub font_cache: &'a FontCache,
582    pub app: &'a AppContext,
583}
584
585#[derive(Clone, Copy, Debug, Eq, PartialEq)]
586pub enum Axis {
587    Horizontal,
588    Vertical,
589}
590
591impl Axis {
592    pub fn invert(self) -> Self {
593        match self {
594            Self::Horizontal => Self::Vertical,
595            Self::Vertical => Self::Horizontal,
596        }
597    }
598}
599
600impl ToJson for Axis {
601    fn to_json(&self) -> serde_json::Value {
602        match self {
603            Axis::Horizontal => json!("horizontal"),
604            Axis::Vertical => json!("vertical"),
605        }
606    }
607}
608
609pub trait Vector2FExt {
610    fn along(self, axis: Axis) -> f32;
611}
612
613impl Vector2FExt for Vector2F {
614    fn along(self, axis: Axis) -> f32 {
615        match axis {
616            Axis::Horizontal => self.x(),
617            Axis::Vertical => self.y(),
618        }
619    }
620}
621
622#[derive(Copy, Clone, Debug)]
623pub struct SizeConstraint {
624    pub min: Vector2F,
625    pub max: Vector2F,
626}
627
628impl SizeConstraint {
629    pub fn new(min: Vector2F, max: Vector2F) -> Self {
630        Self { min, max }
631    }
632
633    pub fn strict(size: Vector2F) -> Self {
634        Self {
635            min: size,
636            max: size,
637        }
638    }
639
640    pub fn strict_along(axis: Axis, max: f32) -> Self {
641        match axis {
642            Axis::Horizontal => Self {
643                min: vec2f(max, 0.0),
644                max: vec2f(max, f32::INFINITY),
645            },
646            Axis::Vertical => Self {
647                min: vec2f(0.0, max),
648                max: vec2f(f32::INFINITY, max),
649            },
650        }
651    }
652
653    pub fn max_along(&self, axis: Axis) -> f32 {
654        match axis {
655            Axis::Horizontal => self.max.x(),
656            Axis::Vertical => self.max.y(),
657        }
658    }
659
660    pub fn min_along(&self, axis: Axis) -> f32 {
661        match axis {
662            Axis::Horizontal => self.min.x(),
663            Axis::Vertical => self.min.y(),
664        }
665    }
666
667    pub fn constrain(&self, size: Vector2F) -> Vector2F {
668        vec2f(
669            size.x().min(self.max.x()).max(self.min.x()),
670            size.y().min(self.max.y()).max(self.min.y()),
671        )
672    }
673}
674
675impl ToJson for SizeConstraint {
676    fn to_json(&self) -> serde_json::Value {
677        json!({
678            "min": self.min.to_json(),
679            "max": self.max.to_json(),
680        })
681    }
682}
683
684pub struct ChildView {
685    view: AnyViewHandle,
686}
687
688impl ChildView {
689    pub fn new(view: impl Into<AnyViewHandle>) -> Self {
690        Self { view: view.into() }
691    }
692}
693
694impl Element for ChildView {
695    type LayoutState = ();
696    type PaintState = ();
697
698    fn layout(
699        &mut self,
700        constraint: SizeConstraint,
701        cx: &mut LayoutContext,
702    ) -> (Vector2F, Self::LayoutState) {
703        let size = cx.layout(self.view.id(), constraint);
704        (size, ())
705    }
706
707    fn paint(
708        &mut self,
709        bounds: RectF,
710        visible_bounds: RectF,
711        _: &mut Self::LayoutState,
712        cx: &mut PaintContext,
713    ) -> Self::PaintState {
714        cx.paint(self.view.id(), bounds.origin(), visible_bounds);
715    }
716
717    fn dispatch_event(
718        &mut self,
719        event: &Event,
720        _: RectF,
721        _: RectF,
722        _: &mut Self::LayoutState,
723        _: &mut Self::PaintState,
724        cx: &mut EventContext,
725    ) -> bool {
726        cx.dispatch_event(self.view.id(), event)
727    }
728
729    fn debug(
730        &self,
731        bounds: RectF,
732        _: &Self::LayoutState,
733        _: &Self::PaintState,
734        cx: &DebugContext,
735    ) -> serde_json::Value {
736        json!({
737            "type": "ChildView",
738            "view_id": self.view.id(),
739            "bounds": bounds.to_json(),
740            "view": self.view.debug_json(cx.app),
741            "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
742                view.debug(cx)
743            } else {
744                json!(null)
745            }
746        })
747    }
748}