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