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