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    ParentId, ReadModel, ReadView, RenderContext, RenderParams, Scene, UpgradeModelHandle,
 14    UpgradeViewHandle, 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_moved_region = None;
239            let mut mouse_down_region = None;
240            let mut clicked_region = None;
241            let mut dragged_region = None;
242
243            match &event {
244                Event::MouseDown(
245                    e @ MouseButtonEvent {
246                        position, button, ..
247                    },
248                ) => {
249                    let mut hit = false;
250                    for (region, _) in self.mouse_regions.iter().rev() {
251                        if region.bounds.contains_point(*position) {
252                            if !hit {
253                                hit = true;
254                                invalidated_views.push(region.view_id);
255                                mouse_down_region =
256                                    Some((region.clone(), MouseRegionEvent::Down(e.clone())));
257                                self.clicked_region = Some(region.clone());
258                                self.prev_drag_position = Some(*position);
259                            }
260                        } else if let Some(handler) = region
261                            .handlers
262                            .get(&(MouseRegionEvent::down_out_disc(), Some(*button)))
263                        {
264                            mouse_down_out_handlers.push((
265                                handler,
266                                region.view_id,
267                                MouseRegionEvent::DownOut(e.clone()),
268                            ));
269                        }
270                    }
271                }
272                Event::MouseUp(e @ MouseButtonEvent { position, .. }) => {
273                    self.prev_drag_position.take();
274                    if let Some(region) = self.clicked_region.take() {
275                        invalidated_views.push(region.view_id);
276                        if region.bounds.contains_point(*position) {
277                            clicked_region = Some((region, MouseRegionEvent::Click(e.clone())));
278                        }
279                    }
280                }
281                Event::MouseMoved(e @ MouseMovedEvent { position, .. }) => {
282                    if let Some((clicked_region, prev_drag_position)) = self
283                        .clicked_region
284                        .as_ref()
285                        .zip(self.prev_drag_position.as_mut())
286                    {
287                        dragged_region = Some((
288                            clicked_region.clone(),
289                            MouseRegionEvent::Drag(*prev_drag_position, *e),
290                        ));
291                        *prev_drag_position = *position;
292                    }
293
294                    for (region, _) in self.mouse_regions.iter().rev() {
295                        if region.bounds.contains_point(*position) {
296                            invalidated_views.push(region.view_id);
297                            mouse_moved_region =
298                                Some((region.clone(), MouseRegionEvent::Move(e.clone())));
299                            break;
300                        }
301                    }
302
303                    self.last_mouse_moved_event = Some(event.clone());
304                }
305                _ => {}
306            }
307
308            let (mut handled, mut event_cx) =
309                self.handle_hover_events(&event, &mut invalidated_views, cx);
310
311            for (handler, view_id, region_event) in mouse_down_out_handlers {
312                event_cx.with_current_view(view_id, |event_cx| handler(region_event, event_cx))
313            }
314
315            if let Some((mouse_down_region, region_event)) = mouse_down_region {
316                handled = true;
317                if let Some(mouse_down_callback) =
318                    mouse_down_region.handlers.get(&region_event.handler_key())
319                {
320                    event_cx.with_current_view(mouse_down_region.view_id, |event_cx| {
321                        mouse_down_callback(region_event, event_cx);
322                    })
323                }
324            }
325
326            if let Some((move_moved_region, region_event)) = mouse_moved_region {
327                handled = true;
328                if let Some(mouse_moved_callback) =
329                    move_moved_region.handlers.get(&region_event.handler_key())
330                {
331                    event_cx.with_current_view(move_moved_region.view_id, |event_cx| {
332                        mouse_moved_callback(region_event, event_cx);
333                    })
334                }
335            }
336
337            if let Some((clicked_region, region_event)) = clicked_region {
338                handled = true;
339                if let Some(click_callback) =
340                    clicked_region.handlers.get(&region_event.handler_key())
341                {
342                    event_cx.with_current_view(clicked_region.view_id, |event_cx| {
343                        click_callback(region_event, event_cx);
344                    })
345                }
346            }
347
348            if let Some((dragged_region, region_event)) = dragged_region {
349                handled = true;
350                if let Some(drag_callback) =
351                    dragged_region.handlers.get(&region_event.handler_key())
352                {
353                    event_cx.with_current_view(dragged_region.view_id, |event_cx| {
354                        drag_callback(region_event, event_cx);
355                    })
356                }
357            }
358
359            if !handled {
360                handled = event_cx.dispatch_event(root_view_id, &event);
361            }
362
363            invalidated_views.extend(event_cx.invalidated_views);
364
365            for view_id in invalidated_views {
366                cx.notify_view(self.window_id, view_id);
367            }
368
369            handled
370        } else {
371            false
372        }
373    }
374
375    fn handle_hover_events<'a>(
376        &'a mut self,
377        event: &Event,
378        invalidated_views: &mut Vec<usize>,
379        cx: &'a mut MutableAppContext,
380    ) -> (bool, EventContext<'a>) {
381        let mut hover_regions = Vec::new();
382        if let Event::MouseMoved(
383            e @ MouseMovedEvent {
384                position,
385                pressed_button,
386                ..
387            },
388        ) = event
389        {
390            if pressed_button.is_none() {
391                let mut style_to_assign = CursorStyle::Arrow;
392                for region in self.cursor_regions.iter().rev() {
393                    if region.bounds.contains_point(*position) {
394                        style_to_assign = region.style;
395                        break;
396                    }
397                }
398                cx.platform().set_cursor_style(style_to_assign);
399
400                let mut hover_depth = None;
401                for (region, depth) in self.mouse_regions.iter().rev() {
402                    if region.bounds.contains_point(*position)
403                        && hover_depth.map_or(true, |hover_depth| hover_depth == *depth)
404                    {
405                        hover_depth = Some(*depth);
406                        if let Some(region_id) = region.id() {
407                            if !self.hovered_region_ids.contains(&region_id) {
408                                invalidated_views.push(region.view_id);
409                                hover_regions
410                                    .push((region.clone(), MouseRegionEvent::Hover(true, *e)));
411                                self.hovered_region_ids.insert(region_id);
412                            }
413                        }
414                    } else if let Some(region_id) = region.id() {
415                        if self.hovered_region_ids.contains(&region_id) {
416                            invalidated_views.push(region.view_id);
417                            hover_regions
418                                .push((region.clone(), MouseRegionEvent::Hover(false, *e)));
419                            self.hovered_region_ids.remove(&region_id);
420                        }
421                    }
422                }
423            }
424        }
425
426        let mut event_cx = self.build_event_context(cx);
427        let mut handled = false;
428
429        for (hover_region, region_event) in hover_regions {
430            handled = true;
431            if let Some(hover_callback) = hover_region.handlers.get(&region_event.handler_key()) {
432                event_cx.with_current_view(hover_region.view_id, |event_cx| {
433                    hover_callback(region_event, event_cx);
434                })
435            }
436        }
437
438        (handled, event_cx)
439    }
440
441    pub fn build_event_context<'a>(
442        &'a mut self,
443        cx: &'a mut MutableAppContext,
444    ) -> EventContext<'a> {
445        EventContext {
446            rendered_views: &mut self.rendered_views,
447            font_cache: &self.font_cache,
448            text_layout_cache: &self.text_layout_cache,
449            view_stack: Default::default(),
450            invalidated_views: Default::default(),
451            notify_count: 0,
452            window_id: self.window_id,
453            app: cx,
454        }
455    }
456
457    pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
458        let view = cx.root_view(self.window_id)?;
459        Some(json!({
460            "root_view": view.debug_json(cx),
461            "root_element": self.rendered_views.get(&view.id())
462                .map(|root_element| {
463                    root_element.debug(&DebugContext {
464                        rendered_views: &self.rendered_views,
465                        font_cache: &self.font_cache,
466                        app: cx,
467                    })
468                })
469        }))
470    }
471}
472
473pub struct LayoutContext<'a> {
474    window_id: usize,
475    rendered_views: &'a mut HashMap<usize, ElementBox>,
476    view_stack: Vec<usize>,
477    pub font_cache: &'a Arc<FontCache>,
478    pub font_system: Arc<dyn FontSystem>,
479    pub text_layout_cache: &'a TextLayoutCache,
480    pub asset_cache: &'a AssetCache,
481    pub app: &'a mut MutableAppContext,
482    pub refreshing: bool,
483    pub window_size: Vector2F,
484    titlebar_height: f32,
485    hovered_region_ids: HashSet<MouseRegionId>,
486    clicked_region_id: Option<MouseRegionId>,
487    right_clicked_region_id: Option<MouseRegionId>,
488}
489
490impl<'a> LayoutContext<'a> {
491    pub(crate) fn keystrokes_for_action(
492        &self,
493        action: &dyn Action,
494    ) -> Option<SmallVec<[Keystroke; 2]>> {
495        self.app
496            .keystrokes_for_action(self.window_id, &self.view_stack, action)
497    }
498
499    fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
500        let print_error = |view_id| {
501            format!(
502                "{} with id {}",
503                self.app.name_for_view(self.window_id, view_id).unwrap(),
504                view_id,
505            )
506        };
507        match (
508            self.view_stack.last(),
509            self.app.parents.get(&(self.window_id, view_id)),
510        ) {
511            (Some(layout_parent), Some(ParentId::View(app_parent))) => {
512                if layout_parent != app_parent {
513                    panic!(
514                        "View {} was laid out with parent {} when it was constructed with parent {}", 
515                        print_error(view_id),
516                        print_error(*layout_parent),
517                        print_error(*app_parent))
518                }
519            }
520            (None, Some(ParentId::View(app_parent))) => panic!(
521                "View {} was laid out without a parent when it was constructed with parent {}",
522                print_error(view_id),
523                print_error(*app_parent)
524            ),
525            (Some(layout_parent), Some(ParentId::Root)) => panic!(
526                "View {} was laid out with parent {} when it was constructed as a window root",
527                print_error(view_id),
528                print_error(*layout_parent),
529            ),
530            (_, None) => panic!(
531                "View {} did not have a registered parent in the app context",
532                print_error(view_id),
533            ),
534            _ => {}
535        }
536
537        self.view_stack.push(view_id);
538        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
539        let size = rendered_view.layout(constraint, self);
540        self.rendered_views.insert(view_id, rendered_view);
541        self.view_stack.pop();
542        size
543    }
544
545    pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
546    where
547        F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
548        V: View,
549    {
550        handle.update(self.app, |view, cx| {
551            let mut render_cx = RenderContext {
552                app: cx,
553                window_id: handle.window_id(),
554                view_id: handle.id(),
555                view_type: PhantomData,
556                titlebar_height: self.titlebar_height,
557                hovered_region_ids: self.hovered_region_ids.clone(),
558                clicked_region_id: self.clicked_region_id,
559                right_clicked_region_id: self.right_clicked_region_id,
560                refreshing: self.refreshing,
561            };
562            f(view, &mut render_cx)
563        })
564    }
565}
566
567impl<'a> Deref for LayoutContext<'a> {
568    type Target = MutableAppContext;
569
570    fn deref(&self) -> &Self::Target {
571        self.app
572    }
573}
574
575impl<'a> DerefMut for LayoutContext<'a> {
576    fn deref_mut(&mut self) -> &mut Self::Target {
577        self.app
578    }
579}
580
581impl<'a> ReadView for LayoutContext<'a> {
582    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
583        self.app.read_view(handle)
584    }
585}
586
587impl<'a> ReadModel for LayoutContext<'a> {
588    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
589        self.app.read_model(handle)
590    }
591}
592
593impl<'a> UpgradeModelHandle for LayoutContext<'a> {
594    fn upgrade_model_handle<T: Entity>(
595        &self,
596        handle: &WeakModelHandle<T>,
597    ) -> Option<ModelHandle<T>> {
598        self.app.upgrade_model_handle(handle)
599    }
600
601    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
602        self.app.model_handle_is_upgradable(handle)
603    }
604
605    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
606        self.app.upgrade_any_model_handle(handle)
607    }
608}
609
610impl<'a> UpgradeViewHandle for LayoutContext<'a> {
611    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
612        self.app.upgrade_view_handle(handle)
613    }
614
615    fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
616        self.app.upgrade_any_view_handle(handle)
617    }
618}
619
620pub struct PaintContext<'a> {
621    rendered_views: &'a mut HashMap<usize, ElementBox>,
622    view_stack: Vec<usize>,
623    pub window_size: Vector2F,
624    pub scene: &'a mut Scene,
625    pub font_cache: &'a FontCache,
626    pub text_layout_cache: &'a TextLayoutCache,
627    pub app: &'a AppContext,
628}
629
630impl<'a> PaintContext<'a> {
631    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
632        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
633            self.view_stack.push(view_id);
634            tree.paint(origin, visible_bounds, self);
635            self.rendered_views.insert(view_id, tree);
636            self.view_stack.pop();
637        }
638    }
639
640    #[inline]
641    pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
642    where
643        F: FnOnce(&mut Self),
644    {
645        self.scene.push_layer(clip_bounds);
646        f(self);
647        self.scene.pop_layer();
648    }
649
650    pub fn current_view_id(&self) -> usize {
651        *self.view_stack.last().unwrap()
652    }
653}
654
655impl<'a> Deref for PaintContext<'a> {
656    type Target = AppContext;
657
658    fn deref(&self) -> &Self::Target {
659        self.app
660    }
661}
662
663pub struct EventContext<'a> {
664    rendered_views: &'a mut HashMap<usize, ElementBox>,
665    pub font_cache: &'a FontCache,
666    pub text_layout_cache: &'a TextLayoutCache,
667    pub app: &'a mut MutableAppContext,
668    pub window_id: usize,
669    pub notify_count: usize,
670    view_stack: Vec<usize>,
671    invalidated_views: HashSet<usize>,
672}
673
674impl<'a> EventContext<'a> {
675    fn dispatch_event(&mut self, view_id: usize, event: &Event) -> bool {
676        if let Some(mut element) = self.rendered_views.remove(&view_id) {
677            let result =
678                self.with_current_view(view_id, |this| element.dispatch_event(event, this));
679            self.rendered_views.insert(view_id, element);
680            result
681        } else {
682            false
683        }
684    }
685
686    fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
687    where
688        F: FnOnce(&mut Self) -> T,
689    {
690        self.view_stack.push(view_id);
691        let result = f(self);
692        self.view_stack.pop();
693        result
694    }
695
696    pub fn window_id(&self) -> usize {
697        self.window_id
698    }
699
700    pub fn view_id(&self) -> Option<usize> {
701        self.view_stack.last().copied()
702    }
703
704    pub fn is_parent_view_focused(&self) -> bool {
705        if let Some(parent_view_id) = self.view_stack.last() {
706            self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
707        } else {
708            false
709        }
710    }
711
712    pub fn focus_parent_view(&mut self) {
713        if let Some(parent_view_id) = self.view_stack.last() {
714            self.app.focus(self.window_id, Some(*parent_view_id))
715        }
716    }
717
718    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
719        self.app
720            .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
721    }
722
723    pub fn dispatch_action<A: Action>(&mut self, action: A) {
724        self.dispatch_any_action(Box::new(action));
725    }
726
727    pub fn notify(&mut self) {
728        self.notify_count += 1;
729        if let Some(view_id) = self.view_stack.last() {
730            self.invalidated_views.insert(*view_id);
731        }
732    }
733
734    pub fn notify_count(&self) -> usize {
735        self.notify_count
736    }
737}
738
739impl<'a> Deref for EventContext<'a> {
740    type Target = MutableAppContext;
741
742    fn deref(&self) -> &Self::Target {
743        self.app
744    }
745}
746
747impl<'a> DerefMut for EventContext<'a> {
748    fn deref_mut(&mut self) -> &mut Self::Target {
749        self.app
750    }
751}
752
753pub struct MeasurementContext<'a> {
754    app: &'a AppContext,
755    rendered_views: &'a HashMap<usize, ElementBox>,
756    pub window_id: usize,
757}
758
759impl<'a> Deref for MeasurementContext<'a> {
760    type Target = AppContext;
761
762    fn deref(&self) -> &Self::Target {
763        self.app
764    }
765}
766
767impl<'a> MeasurementContext<'a> {
768    fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
769        let element = self.rendered_views.get(&view_id)?;
770        element.rect_for_text_range(range_utf16, self)
771    }
772}
773
774pub struct DebugContext<'a> {
775    rendered_views: &'a HashMap<usize, ElementBox>,
776    pub font_cache: &'a FontCache,
777    pub app: &'a AppContext,
778}
779
780#[derive(Clone, Copy, Debug, Eq, PartialEq)]
781pub enum Axis {
782    Horizontal,
783    Vertical,
784}
785
786impl Axis {
787    pub fn invert(self) -> Self {
788        match self {
789            Self::Horizontal => Self::Vertical,
790            Self::Vertical => Self::Horizontal,
791        }
792    }
793}
794
795impl ToJson for Axis {
796    fn to_json(&self) -> serde_json::Value {
797        match self {
798            Axis::Horizontal => json!("horizontal"),
799            Axis::Vertical => json!("vertical"),
800        }
801    }
802}
803
804pub trait Vector2FExt {
805    fn along(self, axis: Axis) -> f32;
806}
807
808impl Vector2FExt for Vector2F {
809    fn along(self, axis: Axis) -> f32 {
810        match axis {
811            Axis::Horizontal => self.x(),
812            Axis::Vertical => self.y(),
813        }
814    }
815}
816
817#[derive(Copy, Clone, Debug)]
818pub struct SizeConstraint {
819    pub min: Vector2F,
820    pub max: Vector2F,
821}
822
823impl SizeConstraint {
824    pub fn new(min: Vector2F, max: Vector2F) -> Self {
825        Self { min, max }
826    }
827
828    pub fn strict(size: Vector2F) -> Self {
829        Self {
830            min: size,
831            max: size,
832        }
833    }
834
835    pub fn strict_along(axis: Axis, max: f32) -> Self {
836        match axis {
837            Axis::Horizontal => Self {
838                min: vec2f(max, 0.0),
839                max: vec2f(max, f32::INFINITY),
840            },
841            Axis::Vertical => Self {
842                min: vec2f(0.0, max),
843                max: vec2f(f32::INFINITY, max),
844            },
845        }
846    }
847
848    pub fn max_along(&self, axis: Axis) -> f32 {
849        match axis {
850            Axis::Horizontal => self.max.x(),
851            Axis::Vertical => self.max.y(),
852        }
853    }
854
855    pub fn min_along(&self, axis: Axis) -> f32 {
856        match axis {
857            Axis::Horizontal => self.min.x(),
858            Axis::Vertical => self.min.y(),
859        }
860    }
861
862    pub fn constrain(&self, size: Vector2F) -> Vector2F {
863        vec2f(
864            size.x().min(self.max.x()).max(self.min.x()),
865            size.y().min(self.max.y()).max(self.min.y()),
866        )
867    }
868}
869
870impl Default for SizeConstraint {
871    fn default() -> Self {
872        SizeConstraint {
873            min: Vector2F::zero(),
874            max: Vector2F::splat(f32::INFINITY),
875        }
876    }
877}
878
879impl ToJson for SizeConstraint {
880    fn to_json(&self) -> serde_json::Value {
881        json!({
882            "min": self.min.to_json(),
883            "max": self.max.to_json(),
884        })
885    }
886}
887
888pub struct ChildView {
889    view: AnyViewHandle,
890}
891
892impl ChildView {
893    pub fn new(view: impl Into<AnyViewHandle>) -> Self {
894        Self { view: view.into() }
895    }
896}
897
898impl Element for ChildView {
899    type LayoutState = ();
900    type PaintState = ();
901
902    fn layout(
903        &mut self,
904        constraint: SizeConstraint,
905        cx: &mut LayoutContext,
906    ) -> (Vector2F, Self::LayoutState) {
907        let size = cx.layout(self.view.id(), constraint);
908        (size, ())
909    }
910
911    fn paint(
912        &mut self,
913        bounds: RectF,
914        visible_bounds: RectF,
915        _: &mut Self::LayoutState,
916        cx: &mut PaintContext,
917    ) -> Self::PaintState {
918        cx.paint(self.view.id(), bounds.origin(), visible_bounds);
919    }
920
921    fn dispatch_event(
922        &mut self,
923        event: &Event,
924        _: RectF,
925        _: RectF,
926        _: &mut Self::LayoutState,
927        _: &mut Self::PaintState,
928        cx: &mut EventContext,
929    ) -> bool {
930        cx.dispatch_event(self.view.id(), event)
931    }
932
933    fn rect_for_text_range(
934        &self,
935        range_utf16: Range<usize>,
936        _: RectF,
937        _: RectF,
938        _: &Self::LayoutState,
939        _: &Self::PaintState,
940        cx: &MeasurementContext,
941    ) -> Option<RectF> {
942        cx.rect_for_text_range(self.view.id(), range_utf16)
943    }
944
945    fn debug(
946        &self,
947        bounds: RectF,
948        _: &Self::LayoutState,
949        _: &Self::PaintState,
950        cx: &DebugContext,
951    ) -> serde_json::Value {
952        json!({
953            "type": "ChildView",
954            "view_id": self.view.id(),
955            "bounds": bounds.to_json(),
956            "view": self.view.debug_json(cx.app),
957            "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
958                view.debug(cx)
959            } else {
960                json!(null)
961            }
962        })
963    }
964}