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