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