presenter.rs

  1use crate::{
  2    app::{AppContext, MutableAppContext, WindowInvalidation},
  3    elements::Element,
  4    font_cache::FontCache,
  5    json::{self, ToJson},
  6    platform::Event,
  7    text_layout::TextLayoutCache,
  8    Action, AnyAction, AssetCache, ElementBox, Scene,
  9};
 10use pathfinder_geometry::vector::{vec2f, Vector2F};
 11use serde_json::json;
 12use std::{
 13    collections::{HashMap, HashSet},
 14    sync::Arc,
 15};
 16
 17pub struct Presenter {
 18    window_id: usize,
 19    rendered_views: HashMap<usize, ElementBox>,
 20    parents: HashMap<usize, usize>,
 21    font_cache: Arc<FontCache>,
 22    text_layout_cache: TextLayoutCache,
 23    asset_cache: Arc<AssetCache>,
 24    last_mouse_moved_event: Option<Event>,
 25    titlebar_height: f32,
 26}
 27
 28impl Presenter {
 29    pub fn new(
 30        window_id: usize,
 31        titlebar_height: f32,
 32        font_cache: Arc<FontCache>,
 33        text_layout_cache: TextLayoutCache,
 34        asset_cache: Arc<AssetCache>,
 35        cx: &MutableAppContext,
 36    ) -> Self {
 37        Self {
 38            window_id,
 39            rendered_views: cx.render_views(window_id, titlebar_height),
 40            parents: HashMap::new(),
 41            font_cache,
 42            text_layout_cache,
 43            asset_cache,
 44            last_mouse_moved_event: None,
 45            titlebar_height,
 46        }
 47    }
 48
 49    pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
 50        let mut view_id = app.focused_view_id(self.window_id).unwrap();
 51        let mut path = vec![view_id];
 52        while let Some(parent_id) = self.parents.get(&view_id).copied() {
 53            path.push(parent_id);
 54            view_id = parent_id;
 55        }
 56        path.reverse();
 57        path
 58    }
 59
 60    pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, cx: &AppContext) {
 61        for view_id in invalidation.removed {
 62            invalidation.updated.remove(&view_id);
 63            self.rendered_views.remove(&view_id);
 64            self.parents.remove(&view_id);
 65        }
 66        for view_id in invalidation.updated {
 67            self.rendered_views.insert(
 68                view_id,
 69                cx.render_view(self.window_id, view_id, self.titlebar_height)
 70                    .unwrap(),
 71            );
 72        }
 73    }
 74
 75    pub fn build_scene(
 76        &mut self,
 77        window_size: Vector2F,
 78        scale_factor: f32,
 79        cx: &mut MutableAppContext,
 80    ) -> Scene {
 81        let mut scene = Scene::new(scale_factor);
 82
 83        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
 84            self.layout(window_size, cx);
 85            self.after_layout(cx);
 86            let mut paint_cx = PaintContext {
 87                scene: &mut scene,
 88                font_cache: &self.font_cache,
 89                text_layout_cache: &self.text_layout_cache,
 90                rendered_views: &mut self.rendered_views,
 91                app: cx.as_ref(),
 92            };
 93            paint_cx.paint(root_view_id, Vector2F::zero());
 94            self.text_layout_cache.finish_frame();
 95
 96            if let Some(event) = self.last_mouse_moved_event.clone() {
 97                self.dispatch_event(event, cx)
 98            }
 99        } else {
100            log::error!("could not find root_view_id for window {}", self.window_id);
101        }
102
103        scene
104    }
105
106    fn layout(&mut self, size: Vector2F, cx: &mut MutableAppContext) {
107        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
108            self.layout_cx(cx)
109                .layout(root_view_id, SizeConstraint::strict(size));
110        }
111    }
112
113    pub fn layout_cx<'a>(&'a mut self, cx: &'a mut MutableAppContext) -> LayoutContext<'a> {
114        LayoutContext {
115            rendered_views: &mut self.rendered_views,
116            parents: &mut self.parents,
117            font_cache: &self.font_cache,
118            text_layout_cache: &self.text_layout_cache,
119            asset_cache: &self.asset_cache,
120            view_stack: Vec::new(),
121            app: cx,
122        }
123    }
124
125    fn after_layout(&mut self, cx: &mut MutableAppContext) {
126        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
127            let mut layout_cx = AfterLayoutContext {
128                rendered_views: &mut self.rendered_views,
129                font_cache: &self.font_cache,
130                text_layout_cache: &self.text_layout_cache,
131                app: cx,
132            };
133            layout_cx.after_layout(root_view_id);
134        }
135    }
136
137    pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) {
138        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
139            if matches!(event, Event::MouseMoved { .. }) {
140                self.last_mouse_moved_event = Some(event.clone());
141            }
142
143            let mut event_cx = EventContext {
144                rendered_views: &mut self.rendered_views,
145                dispatched_actions: Default::default(),
146                font_cache: &self.font_cache,
147                text_layout_cache: &self.text_layout_cache,
148                view_stack: Default::default(),
149                invalidated_views: Default::default(),
150                app: cx,
151            };
152            event_cx.dispatch_event(root_view_id, &event);
153
154            let invalidated_views = event_cx.invalidated_views;
155            let dispatch_directives = event_cx.dispatched_actions;
156
157            for view_id in invalidated_views {
158                cx.notify_view(self.window_id, view_id);
159            }
160            for directive in dispatch_directives {
161                cx.dispatch_action_any(self.window_id, &directive.path, directive.action.as_ref());
162            }
163        }
164    }
165
166    pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
167        cx.root_view_id(self.window_id)
168            .and_then(|root_view_id| self.rendered_views.get(&root_view_id))
169            .map(|root_element| {
170                root_element.debug(&DebugContext {
171                    rendered_views: &self.rendered_views,
172                    font_cache: &self.font_cache,
173                    app: cx,
174                })
175            })
176    }
177}
178
179pub struct DispatchDirective {
180    pub path: Vec<usize>,
181    pub action: Box<dyn AnyAction>,
182}
183
184pub struct LayoutContext<'a> {
185    rendered_views: &'a mut HashMap<usize, ElementBox>,
186    parents: &'a mut HashMap<usize, usize>,
187    view_stack: Vec<usize>,
188    pub font_cache: &'a FontCache,
189    pub text_layout_cache: &'a TextLayoutCache,
190    pub asset_cache: &'a AssetCache,
191    pub app: &'a mut MutableAppContext,
192}
193
194impl<'a> LayoutContext<'a> {
195    fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
196        if let Some(parent_id) = self.view_stack.last() {
197            self.parents.insert(view_id, *parent_id);
198        }
199        self.view_stack.push(view_id);
200        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
201        let size = rendered_view.layout(constraint, self);
202        self.rendered_views.insert(view_id, rendered_view);
203        self.view_stack.pop();
204        size
205    }
206}
207
208pub struct AfterLayoutContext<'a> {
209    rendered_views: &'a mut HashMap<usize, ElementBox>,
210    pub font_cache: &'a FontCache,
211    pub text_layout_cache: &'a TextLayoutCache,
212    pub app: &'a mut MutableAppContext,
213}
214
215impl<'a> AfterLayoutContext<'a> {
216    fn after_layout(&mut self, view_id: usize) {
217        if let Some(mut view) = self.rendered_views.remove(&view_id) {
218            view.after_layout(self);
219            self.rendered_views.insert(view_id, view);
220        }
221    }
222}
223
224pub struct PaintContext<'a> {
225    rendered_views: &'a mut HashMap<usize, ElementBox>,
226    pub scene: &'a mut Scene,
227    pub font_cache: &'a FontCache,
228    pub text_layout_cache: &'a TextLayoutCache,
229    pub app: &'a AppContext,
230}
231
232impl<'a> PaintContext<'a> {
233    fn paint(&mut self, view_id: usize, origin: Vector2F) {
234        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
235            tree.paint(origin, self);
236            self.rendered_views.insert(view_id, tree);
237        }
238    }
239}
240
241pub struct EventContext<'a> {
242    rendered_views: &'a mut HashMap<usize, ElementBox>,
243    dispatched_actions: Vec<DispatchDirective>,
244    pub font_cache: &'a FontCache,
245    pub text_layout_cache: &'a TextLayoutCache,
246    pub app: &'a mut MutableAppContext,
247    view_stack: Vec<usize>,
248    invalidated_views: HashSet<usize>,
249}
250
251impl<'a> EventContext<'a> {
252    fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
253        if let Some(mut element) = self.rendered_views.remove(&view_id) {
254            self.view_stack.push(view_id);
255            let result = element.dispatch_event(event, self);
256            self.view_stack.pop();
257            self.rendered_views.insert(view_id, element);
258            result
259        } else {
260            false
261        }
262    }
263
264    pub fn dispatch_action<A: Action>(&mut self, action: A) {
265        self.dispatched_actions.push(DispatchDirective {
266            path: self.view_stack.clone(),
267            action: Box::new(action),
268        });
269    }
270
271    pub fn notify(&mut self) {
272        self.invalidated_views
273            .insert(*self.view_stack.last().unwrap());
274    }
275}
276
277pub struct DebugContext<'a> {
278    rendered_views: &'a HashMap<usize, ElementBox>,
279    pub font_cache: &'a FontCache,
280    pub app: &'a AppContext,
281}
282
283#[derive(Clone, Copy, Debug, Eq, PartialEq)]
284pub enum Axis {
285    Horizontal,
286    Vertical,
287}
288
289impl Axis {
290    pub fn invert(self) -> Self {
291        match self {
292            Self::Horizontal => Self::Vertical,
293            Self::Vertical => Self::Horizontal,
294        }
295    }
296}
297
298impl ToJson for Axis {
299    fn to_json(&self) -> serde_json::Value {
300        match self {
301            Axis::Horizontal => json!("horizontal"),
302            Axis::Vertical => json!("vertical"),
303        }
304    }
305}
306
307pub trait Vector2FExt {
308    fn along(self, axis: Axis) -> f32;
309}
310
311impl Vector2FExt for Vector2F {
312    fn along(self, axis: Axis) -> f32 {
313        match axis {
314            Axis::Horizontal => self.x(),
315            Axis::Vertical => self.y(),
316        }
317    }
318}
319
320#[derive(Copy, Clone, Debug)]
321pub struct SizeConstraint {
322    pub min: Vector2F,
323    pub max: Vector2F,
324}
325
326impl SizeConstraint {
327    pub fn new(min: Vector2F, max: Vector2F) -> Self {
328        Self { min, max }
329    }
330
331    pub fn strict(size: Vector2F) -> Self {
332        Self {
333            min: size,
334            max: size,
335        }
336    }
337
338    pub fn strict_along(axis: Axis, max: f32) -> Self {
339        match axis {
340            Axis::Horizontal => Self {
341                min: vec2f(max, 0.0),
342                max: vec2f(max, f32::INFINITY),
343            },
344            Axis::Vertical => Self {
345                min: vec2f(0.0, max),
346                max: vec2f(f32::INFINITY, max),
347            },
348        }
349    }
350
351    pub fn max_along(&self, axis: Axis) -> f32 {
352        match axis {
353            Axis::Horizontal => self.max.x(),
354            Axis::Vertical => self.max.y(),
355        }
356    }
357}
358
359impl ToJson for SizeConstraint {
360    fn to_json(&self) -> serde_json::Value {
361        json!({
362            "min": self.min.to_json(),
363            "max": self.max.to_json(),
364        })
365    }
366}
367
368pub struct ChildView {
369    view_id: usize,
370}
371
372impl ChildView {
373    pub fn new(view_id: usize) -> Self {
374        Self { view_id }
375    }
376}
377
378impl Element for ChildView {
379    type LayoutState = ();
380    type PaintState = ();
381
382    fn layout(
383        &mut self,
384        constraint: SizeConstraint,
385        cx: &mut LayoutContext,
386    ) -> (Vector2F, Self::LayoutState) {
387        let size = cx.layout(self.view_id, constraint);
388        (size, ())
389    }
390
391    fn paint(
392        &mut self,
393        bounds: pathfinder_geometry::rect::RectF,
394        _: &mut Self::LayoutState,
395        cx: &mut PaintContext,
396    ) -> Self::PaintState {
397        cx.paint(self.view_id, bounds.origin());
398    }
399
400    fn dispatch_event(
401        &mut self,
402        event: &Event,
403        _: pathfinder_geometry::rect::RectF,
404        _: &mut Self::LayoutState,
405        _: &mut Self::PaintState,
406        cx: &mut EventContext,
407    ) -> bool {
408        cx.dispatch_event(self.view_id, event)
409    }
410
411    fn debug(
412        &self,
413        bounds: pathfinder_geometry::rect::RectF,
414        _: &Self::LayoutState,
415        _: &Self::PaintState,
416        cx: &DebugContext,
417    ) -> serde_json::Value {
418        json!({
419            "type": "ChildView",
420            "view_id": self.view_id,
421            "bounds": bounds.to_json(),
422            "child": if let Some(view) = cx.rendered_views.get(&self.view_id) {
423                view.debug(cx)
424            } else {
425                json!(null)
426            }
427        })
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    // #[test]
434    // fn test_responder_chain() {
435    //     let settings = settings_rx(None);
436    //     let mut app = App::new().unwrap();
437    //     let workspace = app.add_model(|cx| Workspace::new(Vec::new(), cx));
438    //     let (window_id, workspace_view) =
439    //         app.add_window(|cx| WorkspaceView::new(workspace.clone(), settings, cx));
440
441    //     let invalidations = Rc::new(RefCell::new(Vec::new()));
442    //     let invalidations_ = invalidations.clone();
443    //     app.on_window_invalidated(window_id, move |invalidation, _| {
444    //         invalidations_.borrow_mut().push(invalidation)
445    //     });
446
447    //     let active_pane_id = workspace_view.update(&mut app, |view, cx| {
448    //         cx.focus(view.active_pane());
449    //         view.active_pane().id()
450    //     });
451
452    //     app.update(|app| {
453    //         let mut presenter = Presenter::new(
454    //             window_id,
455    //             Rc::new(FontCache::new()),
456    //             Rc::new(AssetCache::new()),
457    //             app,
458    //         );
459    //         for invalidation in invalidations.borrow().iter().cloned() {
460    //             presenter.update(vec2f(1024.0, 768.0), 2.0, Some(invalidation), app);
461    //         }
462
463    //         assert_eq!(
464    //             presenter.responder_chain(app.cx()).unwrap(),
465    //             vec![workspace_view.id(), active_pane_id]
466    //         );
467    //     });
468    // }
469}