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