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