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