presenter.rs

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