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