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