presenter.rs

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