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