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