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