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