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