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