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