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, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox,
 10    Entity, FontSystem, ModelHandle, ReadModel, ReadView, Scene, UpgradeModelHandle,
 11    UpgradeViewHandle, View, ViewHandle, 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    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
285        self.app.upgrade_any_model_handle(handle)
286    }
287}
288
289impl<'a> UpgradeViewHandle for LayoutContext<'a> {
290    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
291        self.app.upgrade_view_handle(handle)
292    }
293}
294
295pub struct PaintContext<'a> {
296    rendered_views: &'a mut HashMap<usize, ElementBox>,
297    pub scene: &'a mut Scene,
298    pub font_cache: &'a FontCache,
299    pub text_layout_cache: &'a TextLayoutCache,
300    pub app: &'a AppContext,
301}
302
303impl<'a> PaintContext<'a> {
304    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
305        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
306            tree.paint(origin, visible_bounds, self);
307            self.rendered_views.insert(view_id, tree);
308        }
309    }
310}
311
312impl<'a> Deref for PaintContext<'a> {
313    type Target = AppContext;
314
315    fn deref(&self) -> &Self::Target {
316        self.app
317    }
318}
319
320pub struct EventContext<'a> {
321    rendered_views: &'a mut HashMap<usize, ElementBox>,
322    dispatched_actions: Vec<DispatchDirective>,
323    pub font_cache: &'a FontCache,
324    pub text_layout_cache: &'a TextLayoutCache,
325    pub app: &'a mut MutableAppContext,
326    pub notify_count: usize,
327    view_stack: Vec<usize>,
328    invalidated_views: HashSet<usize>,
329}
330
331impl<'a> EventContext<'a> {
332    fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
333        if let Some(mut element) = self.rendered_views.remove(&view_id) {
334            self.view_stack.push(view_id);
335            let result = element.dispatch_event(event, self);
336            self.view_stack.pop();
337            self.rendered_views.insert(view_id, element);
338            result
339        } else {
340            false
341        }
342    }
343
344    pub fn dispatch_action<A: Action>(&mut self, action: A) {
345        self.dispatched_actions.push(DispatchDirective {
346            path: self.view_stack.clone(),
347            action: Box::new(action),
348        });
349    }
350
351    pub fn notify(&mut self) {
352        self.notify_count += 1;
353        if let Some(view_id) = self.view_stack.last() {
354            self.invalidated_views.insert(*view_id);
355        }
356    }
357
358    pub fn notify_count(&self) -> usize {
359        self.notify_count
360    }
361}
362
363impl<'a> Deref for EventContext<'a> {
364    type Target = MutableAppContext;
365
366    fn deref(&self) -> &Self::Target {
367        self.app
368    }
369}
370
371impl<'a> DerefMut for EventContext<'a> {
372    fn deref_mut(&mut self) -> &mut Self::Target {
373        self.app
374    }
375}
376
377pub struct DebugContext<'a> {
378    rendered_views: &'a HashMap<usize, ElementBox>,
379    pub font_cache: &'a FontCache,
380    pub app: &'a AppContext,
381}
382
383#[derive(Clone, Copy, Debug, Eq, PartialEq)]
384pub enum Axis {
385    Horizontal,
386    Vertical,
387}
388
389impl Axis {
390    pub fn invert(self) -> Self {
391        match self {
392            Self::Horizontal => Self::Vertical,
393            Self::Vertical => Self::Horizontal,
394        }
395    }
396}
397
398impl ToJson for Axis {
399    fn to_json(&self) -> serde_json::Value {
400        match self {
401            Axis::Horizontal => json!("horizontal"),
402            Axis::Vertical => json!("vertical"),
403        }
404    }
405}
406
407pub trait Vector2FExt {
408    fn along(self, axis: Axis) -> f32;
409}
410
411impl Vector2FExt for Vector2F {
412    fn along(self, axis: Axis) -> f32 {
413        match axis {
414            Axis::Horizontal => self.x(),
415            Axis::Vertical => self.y(),
416        }
417    }
418}
419
420#[derive(Copy, Clone, Debug)]
421pub struct SizeConstraint {
422    pub min: Vector2F,
423    pub max: Vector2F,
424}
425
426impl SizeConstraint {
427    pub fn new(min: Vector2F, max: Vector2F) -> Self {
428        Self { min, max }
429    }
430
431    pub fn strict(size: Vector2F) -> Self {
432        Self {
433            min: size,
434            max: size,
435        }
436    }
437
438    pub fn strict_along(axis: Axis, max: f32) -> Self {
439        match axis {
440            Axis::Horizontal => Self {
441                min: vec2f(max, 0.0),
442                max: vec2f(max, f32::INFINITY),
443            },
444            Axis::Vertical => Self {
445                min: vec2f(0.0, max),
446                max: vec2f(f32::INFINITY, max),
447            },
448        }
449    }
450
451    pub fn max_along(&self, axis: Axis) -> f32 {
452        match axis {
453            Axis::Horizontal => self.max.x(),
454            Axis::Vertical => self.max.y(),
455        }
456    }
457
458    pub fn min_along(&self, axis: Axis) -> f32 {
459        match axis {
460            Axis::Horizontal => self.min.x(),
461            Axis::Vertical => self.min.y(),
462        }
463    }
464
465    pub fn constrain(&self, size: Vector2F) -> Vector2F {
466        vec2f(
467            size.x().min(self.max.x()).max(self.min.x()),
468            size.y().min(self.max.y()).max(self.min.y()),
469        )
470    }
471}
472
473impl ToJson for SizeConstraint {
474    fn to_json(&self) -> serde_json::Value {
475        json!({
476            "min": self.min.to_json(),
477            "max": self.max.to_json(),
478        })
479    }
480}
481
482pub struct ChildView {
483    view_id: usize,
484}
485
486impl ChildView {
487    pub fn new(view: impl Into<AnyViewHandle>) -> Self {
488        Self {
489            view_id: view.into().id(),
490        }
491    }
492}
493
494impl Element for ChildView {
495    type LayoutState = ();
496    type PaintState = ();
497
498    fn layout(
499        &mut self,
500        constraint: SizeConstraint,
501        cx: &mut LayoutContext,
502    ) -> (Vector2F, Self::LayoutState) {
503        let size = cx.layout(self.view_id, constraint);
504        (size, ())
505    }
506
507    fn paint(
508        &mut self,
509        bounds: RectF,
510        visible_bounds: RectF,
511        _: &mut Self::LayoutState,
512        cx: &mut PaintContext,
513    ) -> Self::PaintState {
514        cx.paint(self.view_id, bounds.origin(), visible_bounds);
515    }
516
517    fn dispatch_event(
518        &mut self,
519        event: &Event,
520        _: RectF,
521        _: &mut Self::LayoutState,
522        _: &mut Self::PaintState,
523        cx: &mut EventContext,
524    ) -> bool {
525        cx.dispatch_event(self.view_id, event)
526    }
527
528    fn debug(
529        &self,
530        bounds: RectF,
531        _: &Self::LayoutState,
532        _: &Self::PaintState,
533        cx: &DebugContext,
534    ) -> serde_json::Value {
535        json!({
536            "type": "ChildView",
537            "view_id": self.view_id,
538            "bounds": bounds.to_json(),
539            "child": if let Some(view) = cx.rendered_views.get(&self.view_id) {
540                view.debug(cx)
541            } else {
542                json!(null)
543            }
544        })
545    }
546}
547
548#[cfg(test)]
549mod tests {
550    // #[test]
551    // fn test_responder_chain() {
552    //     let settings = settings_rx(None);
553    //     let mut app = App::new().unwrap();
554    //     let workspace = app.add_model(|cx| Workspace::new(Vec::new(), cx));
555    //     let (window_id, workspace_view) =
556    //         app.add_window(|cx| WorkspaceView::new(workspace.clone(), settings, cx));
557
558    //     let invalidations = Rc::new(RefCell::new(Vec::new()));
559    //     let invalidations_ = invalidations.clone();
560    //     app.on_window_invalidated(window_id, move |invalidation, _| {
561    //         invalidations_.borrow_mut().push(invalidation)
562    //     });
563
564    //     let active_pane_id = workspace_view.update(&mut app, |view, cx| {
565    //         cx.focus(view.active_pane());
566    //         view.active_pane().id()
567    //     });
568
569    //     app.update(|app| {
570    //         let mut presenter = Presenter::new(
571    //             window_id,
572    //             Rc::new(FontCache::new()),
573    //             Rc::new(AssetCache::new()),
574    //             app,
575    //         );
576    //         for invalidation in invalidations.borrow().iter().cloned() {
577    //             presenter.update(vec2f(1024.0, 768.0), 2.0, Some(invalidation), app);
578    //         }
579
580    //         assert_eq!(
581    //             presenter.responder_chain(app.cx()).unwrap(),
582    //             vec![workspace_view.id(), active_pane_id]
583    //         );
584    //     });
585    // }
586}