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