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