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