presenter.rs

  1use crate::{
  2    app::{AppContext, MutableAppContext, WindowInvalidation},
  3    elements::Element,
  4    fonts::FontCache,
  5    platform::Event,
  6    text_layout::TextLayoutCache,
  7    AssetCache, Scene,
  8};
  9use pathfinder_geometry::vector::{vec2f, Vector2F};
 10use std::{any::Any, collections::HashMap, sync::Arc};
 11
 12pub struct Presenter {
 13    window_id: usize,
 14    rendered_views: HashMap<usize, Box<dyn Element>>,
 15    parents: HashMap<usize, usize>,
 16    font_cache: Arc<FontCache>,
 17    text_layout_cache: TextLayoutCache,
 18    asset_cache: Arc<AssetCache>,
 19}
 20
 21impl Presenter {
 22    pub fn new(
 23        window_id: usize,
 24        font_cache: Arc<FontCache>,
 25        asset_cache: Arc<AssetCache>,
 26        app: &MutableAppContext,
 27    ) -> Self {
 28        Self {
 29            window_id,
 30            rendered_views: app.render_views(window_id).unwrap(),
 31            parents: HashMap::new(),
 32            font_cache,
 33            text_layout_cache: TextLayoutCache::new(),
 34            asset_cache,
 35        }
 36    }
 37
 38    pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
 39        let mut view_id = app.focused_view_id(self.window_id).unwrap();
 40        let mut path = vec![view_id];
 41        while let Some(parent_id) = self.parents.get(&view_id).copied() {
 42            path.push(parent_id);
 43            view_id = parent_id;
 44        }
 45        path.reverse();
 46        path
 47    }
 48
 49    pub fn invalidate(&mut self, invalidation: WindowInvalidation, app: &AppContext) {
 50        for view_id in invalidation.updated {
 51            self.rendered_views
 52                .insert(view_id, app.render_view(self.window_id, view_id).unwrap());
 53        }
 54        for view_id in invalidation.removed {
 55            self.rendered_views.remove(&view_id);
 56            self.parents.remove(&view_id);
 57        }
 58    }
 59
 60    pub fn build_scene(
 61        &mut self,
 62        window_size: Vector2F,
 63        scale_factor: f32,
 64        app: &mut MutableAppContext,
 65    ) -> Scene {
 66        let mut scene = Scene::new(scale_factor);
 67
 68        if let Some(root_view_id) = app.root_view_id(self.window_id) {
 69            self.layout(window_size, app.downgrade());
 70            self.after_layout(app);
 71            let mut paint_ctx = PaintContext {
 72                scene: &mut scene,
 73                font_cache: &self.font_cache,
 74                text_layout_cache: &self.text_layout_cache,
 75                rendered_views: &mut self.rendered_views,
 76            };
 77            paint_ctx.paint(root_view_id, Vector2F::zero(), app.downgrade());
 78            self.text_layout_cache.finish_frame();
 79        } else {
 80            log::error!("could not find root_view_id for window {}", self.window_id);
 81        }
 82
 83        scene
 84    }
 85
 86    fn layout(&mut self, size: Vector2F, app: &AppContext) {
 87        if let Some(root_view_id) = app.root_view_id(self.window_id) {
 88            let mut layout_ctx = LayoutContext {
 89                rendered_views: &mut self.rendered_views,
 90                parents: &mut self.parents,
 91                font_cache: &self.font_cache,
 92                text_layout_cache: &self.text_layout_cache,
 93                asset_cache: &self.asset_cache,
 94                view_stack: Vec::new(),
 95            };
 96            layout_ctx.layout(root_view_id, SizeConstraint::strict(size), app);
 97        }
 98    }
 99
100    fn after_layout(&mut self, app: &mut MutableAppContext) {
101        if let Some(root_view_id) = app.root_view_id(self.window_id) {
102            let mut ctx = AfterLayoutContext {
103                rendered_views: &mut self.rendered_views,
104                font_cache: &self.font_cache,
105                text_layout_cache: &self.text_layout_cache,
106            };
107            ctx.after_layout(root_view_id, app);
108        }
109    }
110
111    pub fn responder_chain(&self, app: &AppContext) -> Option<Vec<usize>> {
112        app.focused_view_id(self.window_id).map(|mut view_id| {
113            let mut chain = vec![view_id];
114            while let Some(parent_id) = self.parents.get(&view_id) {
115                view_id = *parent_id;
116                chain.push(view_id);
117            }
118            chain.reverse();
119            chain
120        })
121    }
122
123    pub fn dispatch_event(&self, event: Event, app: &AppContext) -> Vec<ActionToDispatch> {
124        let mut event_ctx = EventContext {
125            rendered_views: &self.rendered_views,
126            actions: Vec::new(),
127            font_cache: &self.font_cache,
128            text_layout_cache: &self.text_layout_cache,
129            view_stack: Vec::new(),
130        };
131        if let Some(root_view_id) = app.root_view_id(self.window_id) {
132            event_ctx.dispatch_event_on_view(root_view_id, &event, app);
133        }
134        event_ctx.actions
135    }
136}
137
138pub struct ActionToDispatch {
139    pub path: Vec<usize>,
140    pub name: &'static str,
141    pub arg: Box<dyn Any>,
142}
143
144pub struct LayoutContext<'a> {
145    rendered_views: &'a mut HashMap<usize, Box<dyn Element>>,
146    parents: &'a mut HashMap<usize, usize>,
147    pub font_cache: &'a FontCache,
148    pub text_layout_cache: &'a TextLayoutCache,
149    pub asset_cache: &'a AssetCache,
150    view_stack: Vec<usize>,
151}
152
153impl<'a> LayoutContext<'a> {
154    fn layout(&mut self, view_id: usize, constraint: SizeConstraint, app: &AppContext) -> Vector2F {
155        if let Some(parent_id) = self.view_stack.last() {
156            self.parents.insert(view_id, *parent_id);
157        }
158        self.view_stack.push(view_id);
159        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
160        let size = rendered_view.layout(constraint, self, app);
161        self.rendered_views.insert(view_id, rendered_view);
162        self.view_stack.pop();
163        size
164    }
165}
166
167pub struct AfterLayoutContext<'a> {
168    rendered_views: &'a mut HashMap<usize, Box<dyn Element>>,
169    pub font_cache: &'a FontCache,
170    pub text_layout_cache: &'a TextLayoutCache,
171}
172
173impl<'a> AfterLayoutContext<'a> {
174    fn after_layout(&mut self, view_id: usize, app: &mut MutableAppContext) {
175        if let Some(mut view) = self.rendered_views.remove(&view_id) {
176            view.after_layout(self, app);
177            self.rendered_views.insert(view_id, view);
178        }
179    }
180}
181
182pub struct PaintContext<'a> {
183    rendered_views: &'a mut HashMap<usize, Box<dyn Element>>,
184    pub scene: &'a mut Scene,
185    pub font_cache: &'a FontCache,
186    pub text_layout_cache: &'a TextLayoutCache,
187}
188
189impl<'a> PaintContext<'a> {
190    fn paint(&mut self, view_id: usize, origin: Vector2F, app: &AppContext) {
191        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
192            tree.paint(origin, self, app);
193            self.rendered_views.insert(view_id, tree);
194        }
195    }
196}
197
198pub struct EventContext<'a> {
199    rendered_views: &'a HashMap<usize, Box<dyn Element>>,
200    actions: Vec<ActionToDispatch>,
201    pub font_cache: &'a FontCache,
202    pub text_layout_cache: &'a TextLayoutCache,
203    view_stack: Vec<usize>,
204}
205
206impl<'a> EventContext<'a> {
207    pub fn dispatch_event_on_view(
208        &mut self,
209        view_id: usize,
210        event: &Event,
211        app: &AppContext,
212    ) -> bool {
213        if let Some(element) = self.rendered_views.get(&view_id) {
214            self.view_stack.push(view_id);
215            let result = element.dispatch_event(event, self, app);
216            self.view_stack.pop();
217            result
218        } else {
219            false
220        }
221    }
222
223    pub fn dispatch_action<A: 'static + Any>(&mut self, name: &'static str, arg: A) {
224        self.actions.push(ActionToDispatch {
225            path: self.view_stack.clone(),
226            name,
227            arg: Box::new(arg),
228        });
229    }
230}
231
232#[derive(Clone, Copy, Debug, Eq, PartialEq)]
233pub enum Axis {
234    Horizontal,
235    Vertical,
236}
237
238impl Axis {
239    pub fn invert(self) -> Self {
240        match self {
241            Self::Horizontal => Self::Vertical,
242            Self::Vertical => Self::Horizontal,
243        }
244    }
245}
246
247pub trait Vector2FExt {
248    fn along(self, axis: Axis) -> f32;
249}
250
251impl Vector2FExt for Vector2F {
252    fn along(self, axis: Axis) -> f32 {
253        match axis {
254            Axis::Horizontal => self.x(),
255            Axis::Vertical => self.y(),
256        }
257    }
258}
259
260#[derive(Copy, Clone, Debug)]
261pub struct SizeConstraint {
262    pub min: Vector2F,
263    pub max: Vector2F,
264}
265
266impl SizeConstraint {
267    pub fn new(min: Vector2F, max: Vector2F) -> Self {
268        Self { min, max }
269    }
270
271    pub fn strict(size: Vector2F) -> Self {
272        Self {
273            min: size,
274            max: size,
275        }
276    }
277
278    pub fn strict_along(axis: Axis, max: f32) -> Self {
279        match axis {
280            Axis::Horizontal => Self {
281                min: vec2f(max, 0.0),
282                max: vec2f(max, f32::INFINITY),
283            },
284            Axis::Vertical => Self {
285                min: vec2f(0.0, max),
286                max: vec2f(f32::INFINITY, max),
287            },
288        }
289    }
290
291    pub fn max_along(&self, axis: Axis) -> f32 {
292        match axis {
293            Axis::Horizontal => self.max.x(),
294            Axis::Vertical => self.max.y(),
295        }
296    }
297}
298
299pub struct ChildView {
300    view_id: usize,
301    size: Option<Vector2F>,
302    origin: Option<Vector2F>,
303}
304
305impl ChildView {
306    pub fn new(view_id: usize) -> Self {
307        Self {
308            view_id,
309            size: None,
310            origin: None,
311        }
312    }
313}
314
315impl Element for ChildView {
316    fn layout(
317        &mut self,
318        constraint: SizeConstraint,
319        ctx: &mut LayoutContext,
320        app: &AppContext,
321    ) -> Vector2F {
322        let size = ctx.layout(self.view_id, constraint, app);
323        self.size = Some(size);
324        size
325    }
326
327    fn after_layout(&mut self, ctx: &mut AfterLayoutContext, app: &mut MutableAppContext) {
328        ctx.after_layout(self.view_id, app);
329    }
330
331    fn paint(&mut self, origin: Vector2F, ctx: &mut PaintContext, app: &AppContext) {
332        self.origin = Some(origin);
333        ctx.paint(self.view_id, origin, app);
334    }
335
336    fn dispatch_event(&self, event: &Event, ctx: &mut EventContext, app: &AppContext) -> bool {
337        ctx.dispatch_event_on_view(self.view_id, event, app)
338    }
339
340    fn size(&self) -> Option<Vector2F> {
341        self.size
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    // #[test]
348    // fn test_responder_chain() {
349    //     let settings = settings_rx(None);
350    //     let mut app = App::new().unwrap();
351    //     let workspace = app.add_model(|ctx| Workspace::new(Vec::new(), ctx));
352    //     let (window_id, workspace_view) =
353    //         app.add_window(|ctx| WorkspaceView::new(workspace.clone(), settings, ctx));
354
355    //     let invalidations = Rc::new(RefCell::new(Vec::new()));
356    //     let invalidations_ = invalidations.clone();
357    //     app.on_window_invalidated(window_id, move |invalidation, _| {
358    //         invalidations_.borrow_mut().push(invalidation)
359    //     });
360
361    //     let active_pane_id = workspace_view.update(&mut app, |view, ctx| {
362    //         ctx.focus(view.active_pane());
363    //         view.active_pane().id()
364    //     });
365
366    //     app.update(|app| {
367    //         let mut presenter = Presenter::new(
368    //             window_id,
369    //             Rc::new(FontCache::new()),
370    //             Rc::new(AssetCache::new()),
371    //             app,
372    //         );
373    //         for invalidation in invalidations.borrow().iter().cloned() {
374    //             presenter.update(vec2f(1024.0, 768.0), 2.0, Some(invalidation), app);
375    //         }
376
377    //         assert_eq!(
378    //             presenter.responder_chain(app.ctx()).unwrap(),
379    //             vec![workspace_view.id(), active_pane_id]
380    //         );
381    //     });
382    // }
383}