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    scene::{CursorRegion, MouseRegionEvent},
 10    text_layout::TextLayoutCache,
 11    Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AssetCache, ElementBox, Entity,
 12    FontSystem, ModelHandle, MouseButtonEvent, MouseMovedEvent, MouseRegion, MouseRegionId,
 13    ReadModel, ReadView, RenderContext, RenderParams, Scene, UpgradeModelHandle, UpgradeViewHandle,
 14    View, ViewHandle, WeakModelHandle, WeakViewHandle,
 15};
 16use collections::{HashMap, HashSet};
 17use pathfinder_geometry::vector::{vec2f, Vector2F};
 18use serde_json::json;
 19use smallvec::SmallVec;
 20use std::{
 21    marker::PhantomData,
 22    ops::{Deref, DerefMut, Range},
 23    sync::Arc,
 24};
 25
 26pub struct Presenter {
 27    window_id: usize,
 28    pub(crate) rendered_views: HashMap<usize, ElementBox>,
 29    cursor_regions: Vec<CursorRegion>,
 30    mouse_regions: Vec<(MouseRegion, usize)>,
 31    font_cache: Arc<FontCache>,
 32    text_layout_cache: TextLayoutCache,
 33    asset_cache: Arc<AssetCache>,
 34    last_mouse_moved_event: Option<Event>,
 35    hovered_region_ids: HashSet<MouseRegionId>,
 36    clicked_region: Option<MouseRegion>,
 37    right_clicked_region: Option<MouseRegion>,
 38    prev_drag_position: Option<Vector2F>,
 39    titlebar_height: f32,
 40}
 41
 42impl Presenter {
 43    pub fn new(
 44        window_id: usize,
 45        titlebar_height: f32,
 46        font_cache: Arc<FontCache>,
 47        text_layout_cache: TextLayoutCache,
 48        asset_cache: Arc<AssetCache>,
 49        cx: &mut MutableAppContext,
 50    ) -> Self {
 51        Self {
 52            window_id,
 53            rendered_views: cx.render_views(window_id, titlebar_height),
 54            cursor_regions: Default::default(),
 55            mouse_regions: Default::default(),
 56            font_cache,
 57            text_layout_cache,
 58            asset_cache,
 59            last_mouse_moved_event: None,
 60            hovered_region_ids: Default::default(),
 61            clicked_region: None,
 62            right_clicked_region: None,
 63            prev_drag_position: None,
 64            titlebar_height,
 65        }
 66    }
 67
 68    // pub fn dispatch_path(&self, app: &AppContext) -> Vec<usize> {
 69    //     let mut path = Vec::new();
 70    //     if let Some(view_id) = app.focused_view_id(self.window_id) {
 71    //         self.compute_dispatch_path_from(view_id, &mut path)
 72    //     }
 73    //     path
 74    // }
 75
 76    // pub(crate) fn compute_dispatch_path_from(&self, mut view_id: usize, path: &mut Vec<usize>) {
 77    //     path.push(view_id);
 78    //     while let Some(parent_id) = self.parents.get(&view_id).copied() {
 79    //         path.push(parent_id);
 80    //         view_id = parent_id;
 81    //     }
 82    //     path.reverse();
 83    // }
 84
 85    pub fn invalidate(
 86        &mut self,
 87        invalidation: &mut WindowInvalidation,
 88        cx: &mut MutableAppContext,
 89    ) {
 90        cx.start_frame();
 91        for view_id in &invalidation.removed {
 92            invalidation.updated.remove(&view_id);
 93            self.rendered_views.remove(&view_id);
 94        }
 95        for view_id in &invalidation.updated {
 96            self.rendered_views.insert(
 97                *view_id,
 98                cx.render_view(RenderParams {
 99                    window_id: self.window_id,
100                    view_id: *view_id,
101                    titlebar_height: self.titlebar_height,
102                    hovered_region_ids: self.hovered_region_ids.clone(),
103                    clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
104                    right_clicked_region_id: self
105                        .right_clicked_region
106                        .as_ref()
107                        .and_then(MouseRegion::id),
108                    refreshing: false,
109                })
110                .unwrap(),
111            );
112        }
113    }
114
115    pub fn refresh(&mut self, invalidation: &mut WindowInvalidation, cx: &mut MutableAppContext) {
116        self.invalidate(invalidation, cx);
117        for (view_id, view) in &mut self.rendered_views {
118            if !invalidation.updated.contains(view_id) {
119                *view = cx
120                    .render_view(RenderParams {
121                        window_id: self.window_id,
122                        view_id: *view_id,
123                        titlebar_height: self.titlebar_height,
124                        hovered_region_ids: self.hovered_region_ids.clone(),
125                        clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
126                        right_clicked_region_id: self
127                            .right_clicked_region
128                            .as_ref()
129                            .and_then(MouseRegion::id),
130                        refreshing: true,
131                    })
132                    .unwrap();
133            }
134        }
135    }
136
137    pub fn build_scene(
138        &mut self,
139        window_size: Vector2F,
140        scale_factor: f32,
141        refreshing: bool,
142        cx: &mut MutableAppContext,
143    ) -> Scene {
144        let mut scene = Scene::new(scale_factor);
145
146        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
147            self.layout(window_size, refreshing, cx);
148            let mut paint_cx = self.build_paint_context(&mut scene, window_size, cx);
149            paint_cx.paint(
150                root_view_id,
151                Vector2F::zero(),
152                RectF::new(Vector2F::zero(), window_size),
153            );
154            self.text_layout_cache.finish_frame();
155            self.cursor_regions = scene.cursor_regions();
156            self.mouse_regions = scene.mouse_regions();
157
158            if cx.window_is_active(self.window_id) {
159                if let Some(event) = self.last_mouse_moved_event.clone() {
160                    let mut invalidated_views = Vec::new();
161                    self.handle_hover_events(&event, &mut invalidated_views, cx);
162
163                    for view_id in invalidated_views {
164                        cx.notify_view(self.window_id, view_id);
165                    }
166                }
167            }
168        } else {
169            log::error!("could not find root_view_id for window {}", self.window_id);
170        }
171
172        scene
173    }
174
175    fn layout(&mut self, window_size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
176        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
177            self.build_layout_context(window_size, refreshing, cx)
178                .layout(root_view_id, SizeConstraint::strict(window_size));
179        }
180    }
181
182    pub fn build_layout_context<'a>(
183        &'a mut self,
184        window_size: Vector2F,
185        refreshing: bool,
186        cx: &'a mut MutableAppContext,
187    ) -> LayoutContext<'a> {
188        LayoutContext {
189            window_id: self.window_id,
190            rendered_views: &mut self.rendered_views,
191            font_cache: &self.font_cache,
192            font_system: cx.platform().fonts(),
193            text_layout_cache: &self.text_layout_cache,
194            asset_cache: &self.asset_cache,
195            view_stack: Vec::new(),
196            refreshing,
197            hovered_region_ids: self.hovered_region_ids.clone(),
198            clicked_region_id: self.clicked_region.as_ref().and_then(MouseRegion::id),
199            right_clicked_region_id: self.right_clicked_region.as_ref().and_then(MouseRegion::id),
200            titlebar_height: self.titlebar_height,
201            window_size,
202            app: cx,
203        }
204    }
205
206    pub fn build_paint_context<'a>(
207        &'a mut self,
208        scene: &'a mut Scene,
209        window_size: Vector2F,
210        cx: &'a mut MutableAppContext,
211    ) -> PaintContext {
212        PaintContext {
213            scene,
214            window_size,
215            font_cache: &self.font_cache,
216            text_layout_cache: &self.text_layout_cache,
217            rendered_views: &mut self.rendered_views,
218            view_stack: Vec::new(),
219            app: cx,
220        }
221    }
222
223    pub fn rect_for_text_range(&self, range_utf16: Range<usize>, cx: &AppContext) -> Option<RectF> {
224        cx.focused_view_id(self.window_id).and_then(|view_id| {
225            let cx = MeasurementContext {
226                app: cx,
227                rendered_views: &self.rendered_views,
228                window_id: self.window_id,
229            };
230            cx.rect_for_text_range(view_id, range_utf16)
231        })
232    }
233
234    pub fn dispatch_event(&mut self, event: Event, cx: &mut MutableAppContext) -> bool {
235        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
236            let mut invalidated_views = Vec::new();
237            let mut mouse_down_out_handlers = Vec::new();
238            let mut mouse_down_region = None;
239            let mut clicked_region = None;
240            let mut dragged_region = None;
241
242            match &event {
243                Event::MouseDown(
244                    e @ MouseButtonEvent {
245                        position, button, ..
246                    },
247                ) => {
248                    let mut hit = false;
249                    for (region, _) in self.mouse_regions.iter().rev() {
250                        if region.bounds.contains_point(*position) {
251                            if !hit {
252                                hit = true;
253                                invalidated_views.push(region.view_id);
254                                mouse_down_region =
255                                    Some((region.clone(), MouseRegionEvent::Down(e.clone())));
256                                self.clicked_region = Some(region.clone());
257                                self.prev_drag_position = Some(*position);
258                            }
259                        } else if let Some(handler) = region
260                            .handlers
261                            .get(&(MouseRegionEvent::down_out_disc(), Some(*button)))
262                        {
263                            mouse_down_out_handlers.push((
264                                handler,
265                                region.view_id,
266                                MouseRegionEvent::DownOut(e.clone()),
267                            ));
268                        }
269                    }
270                }
271                Event::MouseUp(e @ MouseButtonEvent { position, .. }) => {
272                    self.prev_drag_position.take();
273                    if let Some(region) = self.clicked_region.take() {
274                        invalidated_views.push(region.view_id);
275                        if region.bounds.contains_point(*position) {
276                            clicked_region = Some((region, MouseRegionEvent::Click(e.clone())));
277                        }
278                    }
279                }
280                Event::MouseMoved(e @ MouseMovedEvent { position, .. }) => {
281                    if let Some((clicked_region, prev_drag_position)) = self
282                        .clicked_region
283                        .as_ref()
284                        .zip(self.prev_drag_position.as_mut())
285                    {
286                        dragged_region = Some((
287                            clicked_region.clone(),
288                            MouseRegionEvent::Drag(*prev_drag_position, e.clone()),
289                        ));
290                        *prev_drag_position = *position;
291                    }
292
293                    self.last_mouse_moved_event = Some(event.clone());
294                }
295                _ => {}
296            }
297
298            let (mut handled, mut event_cx) =
299                self.handle_hover_events(&event, &mut invalidated_views, cx);
300
301            for (handler, view_id, region_event) in mouse_down_out_handlers {
302                event_cx.with_current_view(view_id, |event_cx| handler(region_event, event_cx))
303            }
304
305            if let Some((mouse_down_region, region_event)) = mouse_down_region {
306                handled = true;
307                if let Some(mouse_down_callback) =
308                    mouse_down_region.handlers.get(&region_event.handler_key())
309                {
310                    event_cx.with_current_view(mouse_down_region.view_id, |event_cx| {
311                        mouse_down_callback(region_event, event_cx);
312                    })
313                }
314            }
315
316            if let Some((clicked_region, region_event)) = clicked_region {
317                handled = true;
318                if let Some(click_callback) =
319                    clicked_region.handlers.get(&region_event.handler_key())
320                {
321                    event_cx.with_current_view(clicked_region.view_id, |event_cx| {
322                        click_callback(region_event, event_cx);
323                    })
324                }
325            }
326
327            if let Some((dragged_region, region_event)) = dragged_region {
328                handled = true;
329                if let Some(drag_callback) =
330                    dragged_region.handlers.get(&region_event.handler_key())
331                {
332                    event_cx.with_current_view(dragged_region.view_id, |event_cx| {
333                        drag_callback(region_event, event_cx);
334                    })
335                }
336            }
337
338            if !handled {
339                handled = event_cx.dispatch_event(root_view_id, &event);
340            }
341
342            invalidated_views.extend(event_cx.invalidated_views);
343
344            for view_id in invalidated_views {
345                cx.notify_view(self.window_id, view_id);
346            }
347
348            handled
349        } else {
350            false
351        }
352    }
353
354    fn handle_hover_events<'a>(
355        &'a mut self,
356        event: &Event,
357        invalidated_views: &mut Vec<usize>,
358        cx: &'a mut MutableAppContext,
359    ) -> (bool, EventContext<'a>) {
360        let mut hover_regions = Vec::new();
361        if let Event::MouseMoved(
362            e @ MouseMovedEvent {
363                position,
364                pressed_button,
365                ..
366            },
367        ) = event
368        {
369            if let None = pressed_button {
370                let mut style_to_assign = CursorStyle::Arrow;
371                for region in self.cursor_regions.iter().rev() {
372                    if region.bounds.contains_point(*position) {
373                        style_to_assign = region.style;
374                        break;
375                    }
376                }
377                cx.platform().set_cursor_style(style_to_assign);
378
379                let mut hover_depth = None;
380                for (region, depth) in self.mouse_regions.iter().rev() {
381                    if region.bounds.contains_point(*position)
382                        && hover_depth.map_or(true, |hover_depth| hover_depth == *depth)
383                    {
384                        hover_depth = Some(*depth);
385                        if let Some(region_id) = region.id() {
386                            if !self.hovered_region_ids.contains(&region_id) {
387                                invalidated_views.push(region.view_id);
388                                hover_regions.push((
389                                    region.clone(),
390                                    MouseRegionEvent::Hover(true, e.clone()),
391                                ));
392                                self.hovered_region_ids.insert(region_id);
393                            }
394                        }
395                    } else {
396                        if let Some(region_id) = region.id() {
397                            if self.hovered_region_ids.contains(&region_id) {
398                                invalidated_views.push(region.view_id);
399                                hover_regions.push((
400                                    region.clone(),
401                                    MouseRegionEvent::Hover(false, e.clone()),
402                                ));
403                                self.hovered_region_ids.remove(&region_id);
404                            }
405                        }
406                    }
407                }
408            }
409        }
410
411        let mut event_cx = self.build_event_context(cx);
412        let mut handled = false;
413
414        for (hover_region, region_event) in hover_regions {
415            handled = true;
416            if let Some(hover_callback) = hover_region.handlers.get(&region_event.handler_key()) {
417                event_cx.with_current_view(hover_region.view_id, |event_cx| {
418                    hover_callback(region_event, event_cx);
419                })
420            }
421        }
422
423        (handled, event_cx)
424    }
425
426    pub fn build_event_context<'a>(
427        &'a mut self,
428        cx: &'a mut MutableAppContext,
429    ) -> EventContext<'a> {
430        EventContext {
431            rendered_views: &mut self.rendered_views,
432            font_cache: &self.font_cache,
433            text_layout_cache: &self.text_layout_cache,
434            view_stack: Default::default(),
435            invalidated_views: Default::default(),
436            notify_count: 0,
437            window_id: self.window_id,
438            app: cx,
439        }
440    }
441
442    pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
443        let view = cx.root_view(self.window_id)?;
444        Some(json!({
445            "root_view": view.debug_json(cx),
446            "root_element": self.rendered_views.get(&view.id())
447                .map(|root_element| {
448                    root_element.debug(&DebugContext {
449                        rendered_views: &self.rendered_views,
450                        font_cache: &self.font_cache,
451                        app: cx,
452                    })
453                })
454        }))
455    }
456}
457
458pub struct LayoutContext<'a> {
459    window_id: usize,
460    rendered_views: &'a mut HashMap<usize, ElementBox>,
461    view_stack: Vec<usize>,
462    pub font_cache: &'a Arc<FontCache>,
463    pub font_system: Arc<dyn FontSystem>,
464    pub text_layout_cache: &'a TextLayoutCache,
465    pub asset_cache: &'a AssetCache,
466    pub app: &'a mut MutableAppContext,
467    pub refreshing: bool,
468    pub window_size: Vector2F,
469    titlebar_height: f32,
470    hovered_region_ids: HashSet<MouseRegionId>,
471    clicked_region_id: Option<MouseRegionId>,
472    right_clicked_region_id: Option<MouseRegionId>,
473}
474
475impl<'a> LayoutContext<'a> {
476    pub(crate) fn keystrokes_for_action(
477        &self,
478        action: &dyn Action,
479    ) -> Option<SmallVec<[Keystroke; 2]>> {
480        self.app
481            .keystrokes_for_action(self.window_id, &self.view_stack, action)
482    }
483
484    fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
485        self.view_stack.push(view_id);
486        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
487        let size = rendered_view.layout(constraint, self);
488        self.rendered_views.insert(view_id, rendered_view);
489        self.view_stack.pop();
490        size
491    }
492
493    pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
494    where
495        F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
496        V: View,
497    {
498        handle.update(self.app, |view, cx| {
499            let mut render_cx = RenderContext {
500                app: cx,
501                window_id: handle.window_id(),
502                view_id: handle.id(),
503                view_type: PhantomData,
504                titlebar_height: self.titlebar_height,
505                hovered_region_ids: self.hovered_region_ids.clone(),
506                clicked_region_id: self.clicked_region_id,
507                right_clicked_region_id: self.right_clicked_region_id,
508                refreshing: self.refreshing,
509            };
510            f(view, &mut render_cx)
511        })
512    }
513}
514
515impl<'a> Deref for LayoutContext<'a> {
516    type Target = MutableAppContext;
517
518    fn deref(&self) -> &Self::Target {
519        self.app
520    }
521}
522
523impl<'a> DerefMut for LayoutContext<'a> {
524    fn deref_mut(&mut self) -> &mut Self::Target {
525        self.app
526    }
527}
528
529impl<'a> ReadView for LayoutContext<'a> {
530    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
531        self.app.read_view(handle)
532    }
533}
534
535impl<'a> ReadModel for LayoutContext<'a> {
536    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
537        self.app.read_model(handle)
538    }
539}
540
541impl<'a> UpgradeModelHandle for LayoutContext<'a> {
542    fn upgrade_model_handle<T: Entity>(
543        &self,
544        handle: &WeakModelHandle<T>,
545    ) -> Option<ModelHandle<T>> {
546        self.app.upgrade_model_handle(handle)
547    }
548
549    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
550        self.app.model_handle_is_upgradable(handle)
551    }
552
553    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
554        self.app.upgrade_any_model_handle(handle)
555    }
556}
557
558impl<'a> UpgradeViewHandle for LayoutContext<'a> {
559    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
560        self.app.upgrade_view_handle(handle)
561    }
562
563    fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
564        self.app.upgrade_any_view_handle(handle)
565    }
566}
567
568pub struct PaintContext<'a> {
569    rendered_views: &'a mut HashMap<usize, ElementBox>,
570    view_stack: Vec<usize>,
571    pub window_size: Vector2F,
572    pub scene: &'a mut Scene,
573    pub font_cache: &'a FontCache,
574    pub text_layout_cache: &'a TextLayoutCache,
575    pub app: &'a AppContext,
576}
577
578impl<'a> PaintContext<'a> {
579    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
580        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
581            self.view_stack.push(view_id);
582            tree.paint(origin, visible_bounds, self);
583            self.rendered_views.insert(view_id, tree);
584            self.view_stack.pop();
585        }
586    }
587
588    #[inline]
589    pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
590    where
591        F: FnOnce(&mut Self) -> (),
592    {
593        self.scene.push_layer(clip_bounds);
594        f(self);
595        self.scene.pop_layer();
596    }
597
598    pub fn current_view_id(&self) -> usize {
599        *self.view_stack.last().unwrap()
600    }
601}
602
603impl<'a> Deref for PaintContext<'a> {
604    type Target = AppContext;
605
606    fn deref(&self) -> &Self::Target {
607        self.app
608    }
609}
610
611pub struct EventContext<'a> {
612    rendered_views: &'a mut HashMap<usize, ElementBox>,
613    pub font_cache: &'a FontCache,
614    pub text_layout_cache: &'a TextLayoutCache,
615    pub app: &'a mut MutableAppContext,
616    pub window_id: usize,
617    pub notify_count: usize,
618    view_stack: Vec<usize>,
619    invalidated_views: HashSet<usize>,
620}
621
622impl<'a> EventContext<'a> {
623    fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
624        if let Some(mut element) = self.rendered_views.remove(&view_id) {
625            let result =
626                self.with_current_view(view_id, |this| element.dispatch_event(event, this));
627            self.rendered_views.insert(view_id, element);
628            result
629        } else {
630            false
631        }
632    }
633
634    fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
635    where
636        F: FnOnce(&mut Self) -> T,
637    {
638        self.view_stack.push(view_id);
639        let result = f(self);
640        self.view_stack.pop();
641        result
642    }
643
644    pub fn window_id(&self) -> usize {
645        self.window_id
646    }
647
648    pub fn view_id(&self) -> Option<usize> {
649        self.view_stack.last().copied()
650    }
651
652    pub fn is_parent_view_focused(&self) -> bool {
653        if let Some(parent_view_id) = self.view_stack.last() {
654            self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
655        } else {
656            false
657        }
658    }
659
660    pub fn focus_parent_view(&mut self) {
661        if let Some(parent_view_id) = self.view_stack.last() {
662            self.app.focus(self.window_id, Some(*parent_view_id))
663        }
664    }
665
666    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
667        self.app
668            .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
669    }
670
671    pub fn dispatch_action<A: Action>(&mut self, action: A) {
672        self.dispatch_any_action(Box::new(action));
673    }
674
675    pub fn notify(&mut self) {
676        self.notify_count += 1;
677        if let Some(view_id) = self.view_stack.last() {
678            self.invalidated_views.insert(*view_id);
679        }
680    }
681
682    pub fn notify_count(&self) -> usize {
683        self.notify_count
684    }
685}
686
687impl<'a> Deref for EventContext<'a> {
688    type Target = MutableAppContext;
689
690    fn deref(&self) -> &Self::Target {
691        self.app
692    }
693}
694
695impl<'a> DerefMut for EventContext<'a> {
696    fn deref_mut(&mut self) -> &mut Self::Target {
697        self.app
698    }
699}
700
701pub struct MeasurementContext<'a> {
702    app: &'a AppContext,
703    rendered_views: &'a HashMap<usize, ElementBox>,
704    pub window_id: usize,
705}
706
707impl<'a> Deref for MeasurementContext<'a> {
708    type Target = AppContext;
709
710    fn deref(&self) -> &Self::Target {
711        self.app
712    }
713}
714
715impl<'a> MeasurementContext<'a> {
716    fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
717        let element = self.rendered_views.get(&view_id)?;
718        element.rect_for_text_range(range_utf16, self)
719    }
720}
721
722pub struct DebugContext<'a> {
723    rendered_views: &'a HashMap<usize, ElementBox>,
724    pub font_cache: &'a FontCache,
725    pub app: &'a AppContext,
726}
727
728#[derive(Clone, Copy, Debug, Eq, PartialEq)]
729pub enum Axis {
730    Horizontal,
731    Vertical,
732}
733
734impl Axis {
735    pub fn invert(self) -> Self {
736        match self {
737            Self::Horizontal => Self::Vertical,
738            Self::Vertical => Self::Horizontal,
739        }
740    }
741}
742
743impl ToJson for Axis {
744    fn to_json(&self) -> serde_json::Value {
745        match self {
746            Axis::Horizontal => json!("horizontal"),
747            Axis::Vertical => json!("vertical"),
748        }
749    }
750}
751
752pub trait Vector2FExt {
753    fn along(self, axis: Axis) -> f32;
754}
755
756impl Vector2FExt for Vector2F {
757    fn along(self, axis: Axis) -> f32 {
758        match axis {
759            Axis::Horizontal => self.x(),
760            Axis::Vertical => self.y(),
761        }
762    }
763}
764
765#[derive(Copy, Clone, Debug)]
766pub struct SizeConstraint {
767    pub min: Vector2F,
768    pub max: Vector2F,
769}
770
771impl SizeConstraint {
772    pub fn new(min: Vector2F, max: Vector2F) -> Self {
773        Self { min, max }
774    }
775
776    pub fn strict(size: Vector2F) -> Self {
777        Self {
778            min: size,
779            max: size,
780        }
781    }
782
783    pub fn strict_along(axis: Axis, max: f32) -> Self {
784        match axis {
785            Axis::Horizontal => Self {
786                min: vec2f(max, 0.0),
787                max: vec2f(max, f32::INFINITY),
788            },
789            Axis::Vertical => Self {
790                min: vec2f(0.0, max),
791                max: vec2f(f32::INFINITY, max),
792            },
793        }
794    }
795
796    pub fn max_along(&self, axis: Axis) -> f32 {
797        match axis {
798            Axis::Horizontal => self.max.x(),
799            Axis::Vertical => self.max.y(),
800        }
801    }
802
803    pub fn min_along(&self, axis: Axis) -> f32 {
804        match axis {
805            Axis::Horizontal => self.min.x(),
806            Axis::Vertical => self.min.y(),
807        }
808    }
809
810    pub fn constrain(&self, size: Vector2F) -> Vector2F {
811        vec2f(
812            size.x().min(self.max.x()).max(self.min.x()),
813            size.y().min(self.max.y()).max(self.min.y()),
814        )
815    }
816}
817
818impl Default for SizeConstraint {
819    fn default() -> Self {
820        SizeConstraint {
821            min: Vector2F::zero(),
822            max: Vector2F::splat(f32::INFINITY),
823        }
824    }
825}
826
827impl ToJson for SizeConstraint {
828    fn to_json(&self) -> serde_json::Value {
829        json!({
830            "min": self.min.to_json(),
831            "max": self.max.to_json(),
832        })
833    }
834}
835
836pub struct ChildView {
837    view: AnyViewHandle,
838}
839
840impl ChildView {
841    pub fn new(view: impl Into<AnyViewHandle>) -> Self {
842        Self { view: view.into() }
843    }
844}
845
846impl Element for ChildView {
847    type LayoutState = ();
848    type PaintState = ();
849
850    fn layout(
851        &mut self,
852        constraint: SizeConstraint,
853        cx: &mut LayoutContext,
854    ) -> (Vector2F, Self::LayoutState) {
855        let size = cx.layout(self.view.id(), constraint);
856        (size, ())
857    }
858
859    fn paint(
860        &mut self,
861        bounds: RectF,
862        visible_bounds: RectF,
863        _: &mut Self::LayoutState,
864        cx: &mut PaintContext,
865    ) -> Self::PaintState {
866        cx.paint(self.view.id(), bounds.origin(), visible_bounds);
867    }
868
869    fn dispatch_event(
870        &mut self,
871        event: &Event,
872        _: RectF,
873        _: RectF,
874        _: &mut Self::LayoutState,
875        _: &mut Self::PaintState,
876        cx: &mut EventContext,
877    ) -> bool {
878        cx.dispatch_event(self.view.id(), event)
879    }
880
881    fn rect_for_text_range(
882        &self,
883        range_utf16: Range<usize>,
884        _: RectF,
885        _: RectF,
886        _: &Self::LayoutState,
887        _: &Self::PaintState,
888        cx: &MeasurementContext,
889    ) -> Option<RectF> {
890        cx.rect_for_text_range(self.view.id(), range_utf16)
891    }
892
893    fn debug(
894        &self,
895        bounds: RectF,
896        _: &Self::LayoutState,
897        _: &Self::PaintState,
898        cx: &DebugContext,
899    ) -> serde_json::Value {
900        json!({
901            "type": "ChildView",
902            "view_id": self.view.id(),
903            "bounds": bounds.to_json(),
904            "view": self.view.debug_json(cx.app),
905            "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
906                view.debug(cx)
907            } else {
908                json!(null)
909            }
910        })
911    }
912}