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