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