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