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, AnyAction, AssetCache, ElementBox, Entity, FontSystem, ModelHandle, ReadModel,
 10    ReadView, Scene, View, ViewHandle,
 11};
 12use pathfinder_geometry::vector::{vec2f, Vector2F};
 13use serde_json::json;
 14use std::{
 15    collections::{HashMap, HashSet},
 16    ops::{Deref, DerefMut},
 17    sync::Arc,
 18};
 19
 20pub struct Presenter {
 21    window_id: usize,
 22    rendered_views: HashMap<usize, ElementBox>,
 23    parents: HashMap<usize, usize>,
 24    font_cache: Arc<FontCache>,
 25    text_layout_cache: TextLayoutCache,
 26    asset_cache: Arc<AssetCache>,
 27    last_mouse_moved_event: Option<Event>,
 28    titlebar_height: f32,
 29}
 30
 31impl Presenter {
 32    pub fn new(
 33        window_id: usize,
 34        titlebar_height: f32,
 35        font_cache: Arc<FontCache>,
 36        text_layout_cache: TextLayoutCache,
 37        asset_cache: Arc<AssetCache>,
 38        cx: &mut MutableAppContext,
 39    ) -> Self {
 40        Self {
 41            window_id,
 42            rendered_views: cx.render_views(window_id, titlebar_height),
 43            parents: HashMap::new(),
 44            font_cache,
 45            text_layout_cache,
 46            asset_cache,
 47            last_mouse_moved_event: None,
 48            titlebar_height,
 49        }
 50    }
 51
 52    pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
 53        let mut view_id = app.focused_view_id(self.window_id).unwrap();
 54        let mut path = vec![view_id];
 55        while let Some(parent_id) = self.parents.get(&view_id).copied() {
 56            path.push(parent_id);
 57            view_id = parent_id;
 58        }
 59        path.reverse();
 60        path
 61    }
 62
 63    pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, cx: &mut MutableAppContext) {
 64        for view_id in invalidation.removed {
 65            invalidation.updated.remove(&view_id);
 66            self.rendered_views.remove(&view_id);
 67            self.parents.remove(&view_id);
 68        }
 69        for view_id in invalidation.updated {
 70            self.rendered_views.insert(
 71                view_id,
 72                cx.render_view(self.window_id, view_id, self.titlebar_height, false)
 73                    .unwrap(),
 74            );
 75        }
 76    }
 77
 78    pub fn refresh(
 79        &mut self,
 80        invalidation: Option<WindowInvalidation>,
 81        cx: &mut MutableAppContext,
 82    ) {
 83        if let Some(invalidation) = invalidation {
 84            for view_id in invalidation.removed {
 85                self.rendered_views.remove(&view_id);
 86                self.parents.remove(&view_id);
 87            }
 88        }
 89
 90        for (view_id, view) in &mut self.rendered_views {
 91            *view = cx
 92                .render_view(self.window_id, *view_id, self.titlebar_height, true)
 93                .unwrap();
 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 = PaintContext {
109                scene: &mut scene,
110                font_cache: &self.font_cache,
111                text_layout_cache: &self.text_layout_cache,
112                rendered_views: &mut self.rendered_views,
113                app: cx.as_ref(),
114            };
115            paint_cx.paint(
116                root_view_id,
117                Vector2F::zero(),
118                RectF::new(Vector2F::zero(), window_size),
119            );
120            self.text_layout_cache.finish_frame();
121
122            if let Some(event) = self.last_mouse_moved_event.clone() {
123                self.dispatch_event(event, cx)
124            }
125        } else {
126            log::error!("could not find root_view_id for window {}", self.window_id);
127        }
128
129        scene
130    }
131
132    fn layout(&mut self, size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
133        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
134            self.build_layout_context(refreshing, cx)
135                .layout(root_view_id, SizeConstraint::strict(size));
136        }
137    }
138
139    pub fn build_layout_context<'a>(
140        &'a mut self,
141        refreshing: bool,
142        cx: &'a mut MutableAppContext,
143    ) -> LayoutContext<'a> {
144        LayoutContext {
145            rendered_views: &mut self.rendered_views,
146            parents: &mut self.parents,
147            refreshing,
148            font_cache: &self.font_cache,
149            font_system: cx.platform().fonts(),
150            text_layout_cache: &self.text_layout_cache,
151            asset_cache: &self.asset_cache,
152            view_stack: Vec::new(),
153            app: cx,
154        }
155    }
156
157    pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) {
158        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
159            match event {
160                Event::MouseMoved { .. } => {
161                    self.last_mouse_moved_event = Some(event.clone());
162                }
163                Event::LeftMouseDragged { position } => {
164                    self.last_mouse_moved_event = Some(Event::MouseMoved {
165                        position,
166                        left_mouse_down: true,
167                    });
168                }
169                _ => {}
170            }
171
172            let mut event_cx = self.build_event_context(cx);
173            event_cx.dispatch_event(root_view_id, &event);
174
175            let invalidated_views = event_cx.invalidated_views;
176            let dispatch_directives = event_cx.dispatched_actions;
177
178            for view_id in invalidated_views {
179                cx.notify_view(self.window_id, view_id);
180            }
181            for directive in dispatch_directives {
182                cx.dispatch_action_any(self.window_id, &directive.path, directive.action.as_ref());
183            }
184        }
185    }
186
187    pub fn build_event_context<'a>(
188        &'a mut self,
189        cx: &'a mut MutableAppContext,
190    ) -> EventContext<'a> {
191        EventContext {
192            rendered_views: &mut self.rendered_views,
193            dispatched_actions: Default::default(),
194            font_cache: &self.font_cache,
195            text_layout_cache: &self.text_layout_cache,
196            view_stack: Default::default(),
197            invalidated_views: Default::default(),
198            app: cx,
199        }
200    }
201
202    pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
203        cx.root_view_id(self.window_id)
204            .and_then(|root_view_id| self.rendered_views.get(&root_view_id))
205            .map(|root_element| {
206                root_element.debug(&DebugContext {
207                    rendered_views: &self.rendered_views,
208                    font_cache: &self.font_cache,
209                    app: cx,
210                })
211            })
212    }
213}
214
215pub struct DispatchDirective {
216    pub path: Vec<usize>,
217    pub action: Box<dyn AnyAction>,
218}
219
220pub struct LayoutContext<'a> {
221    rendered_views: &'a mut HashMap<usize, ElementBox>,
222    parents: &'a mut HashMap<usize, usize>,
223    view_stack: Vec<usize>,
224    pub refreshing: bool,
225    pub font_cache: &'a Arc<FontCache>,
226    pub font_system: Arc<dyn FontSystem>,
227    pub text_layout_cache: &'a TextLayoutCache,
228    pub asset_cache: &'a AssetCache,
229    pub app: &'a mut MutableAppContext,
230}
231
232impl<'a> LayoutContext<'a> {
233    fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
234        if let Some(parent_id) = self.view_stack.last() {
235            self.parents.insert(view_id, *parent_id);
236        }
237        self.view_stack.push(view_id);
238        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
239        let size = rendered_view.layout(constraint, self);
240        self.rendered_views.insert(view_id, rendered_view);
241        self.view_stack.pop();
242        size
243    }
244}
245
246impl<'a> Deref for LayoutContext<'a> {
247    type Target = MutableAppContext;
248
249    fn deref(&self) -> &Self::Target {
250        self.app
251    }
252}
253
254impl<'a> DerefMut for LayoutContext<'a> {
255    fn deref_mut(&mut self) -> &mut Self::Target {
256        self.app
257    }
258}
259
260impl<'a> ReadView for LayoutContext<'a> {
261    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
262        self.app.read_view(handle)
263    }
264}
265
266impl<'a> ReadModel for LayoutContext<'a> {
267    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
268        self.app.read_model(handle)
269    }
270}
271
272pub struct PaintContext<'a> {
273    rendered_views: &'a mut HashMap<usize, ElementBox>,
274    pub scene: &'a mut Scene,
275    pub font_cache: &'a FontCache,
276    pub text_layout_cache: &'a TextLayoutCache,
277    pub app: &'a AppContext,
278}
279
280impl<'a> PaintContext<'a> {
281    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
282        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
283            tree.paint(origin, visible_bounds, self);
284            self.rendered_views.insert(view_id, tree);
285        }
286    }
287}
288
289impl<'a> Deref for PaintContext<'a> {
290    type Target = AppContext;
291
292    fn deref(&self) -> &Self::Target {
293        self.app
294    }
295}
296
297pub struct EventContext<'a> {
298    rendered_views: &'a mut HashMap<usize, ElementBox>,
299    dispatched_actions: Vec<DispatchDirective>,
300    pub font_cache: &'a FontCache,
301    pub text_layout_cache: &'a TextLayoutCache,
302    pub app: &'a mut MutableAppContext,
303    view_stack: Vec<usize>,
304    invalidated_views: HashSet<usize>,
305}
306
307impl<'a> EventContext<'a> {
308    fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
309        if let Some(mut element) = self.rendered_views.remove(&view_id) {
310            self.view_stack.push(view_id);
311            let result = element.dispatch_event(event, self);
312            self.view_stack.pop();
313            self.rendered_views.insert(view_id, element);
314            result
315        } else {
316            false
317        }
318    }
319
320    pub fn dispatch_action<A: Action>(&mut self, action: A) {
321        self.dispatched_actions.push(DispatchDirective {
322            path: self.view_stack.clone(),
323            action: Box::new(action),
324        });
325    }
326
327    pub fn notify(&mut self) {
328        if let Some(view_id) = self.view_stack.last() {
329            self.invalidated_views.insert(*view_id);
330        }
331    }
332}
333
334impl<'a> Deref for EventContext<'a> {
335    type Target = MutableAppContext;
336
337    fn deref(&self) -> &Self::Target {
338        self.app
339    }
340}
341
342impl<'a> DerefMut for EventContext<'a> {
343    fn deref_mut(&mut self) -> &mut Self::Target {
344        self.app
345    }
346}
347
348pub struct DebugContext<'a> {
349    rendered_views: &'a HashMap<usize, ElementBox>,
350    pub font_cache: &'a FontCache,
351    pub app: &'a AppContext,
352}
353
354#[derive(Clone, Copy, Debug, Eq, PartialEq)]
355pub enum Axis {
356    Horizontal,
357    Vertical,
358}
359
360impl Axis {
361    pub fn invert(self) -> Self {
362        match self {
363            Self::Horizontal => Self::Vertical,
364            Self::Vertical => Self::Horizontal,
365        }
366    }
367}
368
369impl ToJson for Axis {
370    fn to_json(&self) -> serde_json::Value {
371        match self {
372            Axis::Horizontal => json!("horizontal"),
373            Axis::Vertical => json!("vertical"),
374        }
375    }
376}
377
378pub trait Vector2FExt {
379    fn along(self, axis: Axis) -> f32;
380}
381
382impl Vector2FExt for Vector2F {
383    fn along(self, axis: Axis) -> f32 {
384        match axis {
385            Axis::Horizontal => self.x(),
386            Axis::Vertical => self.y(),
387        }
388    }
389}
390
391#[derive(Copy, Clone, Debug)]
392pub struct SizeConstraint {
393    pub min: Vector2F,
394    pub max: Vector2F,
395}
396
397impl SizeConstraint {
398    pub fn new(min: Vector2F, max: Vector2F) -> Self {
399        Self { min, max }
400    }
401
402    pub fn strict(size: Vector2F) -> Self {
403        Self {
404            min: size,
405            max: size,
406        }
407    }
408
409    pub fn strict_along(axis: Axis, max: f32) -> Self {
410        match axis {
411            Axis::Horizontal => Self {
412                min: vec2f(max, 0.0),
413                max: vec2f(max, f32::INFINITY),
414            },
415            Axis::Vertical => Self {
416                min: vec2f(0.0, max),
417                max: vec2f(f32::INFINITY, max),
418            },
419        }
420    }
421
422    pub fn max_along(&self, axis: Axis) -> f32 {
423        match axis {
424            Axis::Horizontal => self.max.x(),
425            Axis::Vertical => self.max.y(),
426        }
427    }
428
429    pub fn min_along(&self, axis: Axis) -> f32 {
430        match axis {
431            Axis::Horizontal => self.min.x(),
432            Axis::Vertical => self.min.y(),
433        }
434    }
435}
436
437impl ToJson for SizeConstraint {
438    fn to_json(&self) -> serde_json::Value {
439        json!({
440            "min": self.min.to_json(),
441            "max": self.max.to_json(),
442        })
443    }
444}
445
446pub struct ChildView {
447    view_id: usize,
448}
449
450impl ChildView {
451    pub fn new(view_id: usize) -> Self {
452        Self { view_id }
453    }
454}
455
456impl Element for ChildView {
457    type LayoutState = ();
458    type PaintState = ();
459
460    fn layout(
461        &mut self,
462        constraint: SizeConstraint,
463        cx: &mut LayoutContext,
464    ) -> (Vector2F, Self::LayoutState) {
465        let size = cx.layout(self.view_id, constraint);
466        (size, ())
467    }
468
469    fn paint(
470        &mut self,
471        bounds: RectF,
472        visible_bounds: RectF,
473        _: &mut Self::LayoutState,
474        cx: &mut PaintContext,
475    ) -> Self::PaintState {
476        cx.paint(self.view_id, bounds.origin(), visible_bounds);
477    }
478
479    fn dispatch_event(
480        &mut self,
481        event: &Event,
482        _: RectF,
483        _: &mut Self::LayoutState,
484        _: &mut Self::PaintState,
485        cx: &mut EventContext,
486    ) -> bool {
487        cx.dispatch_event(self.view_id, event)
488    }
489
490    fn debug(
491        &self,
492        bounds: RectF,
493        _: &Self::LayoutState,
494        _: &Self::PaintState,
495        cx: &DebugContext,
496    ) -> serde_json::Value {
497        json!({
498            "type": "ChildView",
499            "view_id": self.view_id,
500            "bounds": bounds.to_json(),
501            "child": if let Some(view) = cx.rendered_views.get(&self.view_id) {
502                view.debug(cx)
503            } else {
504                json!(null)
505            }
506        })
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    // #[test]
513    // fn test_responder_chain() {
514    //     let settings = settings_rx(None);
515    //     let mut app = App::new().unwrap();
516    //     let workspace = app.add_model(|cx| Workspace::new(Vec::new(), cx));
517    //     let (window_id, workspace_view) =
518    //         app.add_window(|cx| WorkspaceView::new(workspace.clone(), settings, cx));
519
520    //     let invalidations = Rc::new(RefCell::new(Vec::new()));
521    //     let invalidations_ = invalidations.clone();
522    //     app.on_window_invalidated(window_id, move |invalidation, _| {
523    //         invalidations_.borrow_mut().push(invalidation)
524    //     });
525
526    //     let active_pane_id = workspace_view.update(&mut app, |view, cx| {
527    //         cx.focus(view.active_pane());
528    //         view.active_pane().id()
529    //     });
530
531    //     app.update(|app| {
532    //         let mut presenter = Presenter::new(
533    //             window_id,
534    //             Rc::new(FontCache::new()),
535    //             Rc::new(AssetCache::new()),
536    //             app,
537    //         );
538    //         for invalidation in invalidations.borrow().iter().cloned() {
539    //             presenter.update(vec2f(1024.0, 768.0), 2.0, Some(invalidation), app);
540    //         }
541
542    //         assert_eq!(
543    //             presenter.responder_chain(app.cx()).unwrap(),
544    //             vec![workspace_view.id(), active_pane_id]
545    //         );
546    //     });
547    // }
548}