freya-core 0.4.0-rc.7

Reactivity runtime, tree management, accessibility integration, rendering pipeline and more, for Freya
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! [rect()] acts as a generic container to contain other elements inside, like a box.

use std::{
    any::Any,
    borrow::Cow,
    rc::Rc,
};

use freya_engine::prelude::{
    Canvas,
    ClipOp,
    Paint,
    PaintStyle,
    PathBuilder,
    SkBlurStyle,
    SkMaskFilter,
    SkPath,
    SkPathFillType,
    SkPoint,
    SkRRect,
    SkRect,
};
use rustc_hash::FxHashMap;
use torin::{
    prelude::Area,
    scaled::Scaled,
};

use crate::{
    diff_key::DiffKey,
    element::{
        ClipContext,
        ElementExt,
        EventHandlerType,
        EventMeasurementContext,
        RenderContext,
    },
    events::name::EventName,
    layers::Layer,
    prelude::*,
    style::{
        font_size::FontSize,
        scale::Scale,
        shadow::{
            Shadow,
            ShadowPosition,
        },
    },
    tree::DiffModifies,
};

/// [rect()] acts as a generic container to contain other elements inside, like a box.
///
/// Its the equivalent of `view`/`div`/`container` in other UI models.
///
/// See the available methods in [Rect].
///
/// ```rust
/// # use freya::prelude::*;
/// fn app() -> impl IntoElement {
///     rect().expanded().background((0, 255, 0))
/// }
/// ```
pub fn rect() -> Rect {
    Rect::empty()
}

#[derive(PartialEq, Clone)]
pub struct RectElement {
    pub style: StyleState,
    pub layout: LayoutData,
    pub text_style_data: TextStyleData,
    pub relative_layer: Layer,
    pub event_handlers: FxHashMap<EventName, EventHandlerType>,
    pub accessibility: AccessibilityData,
    pub effect: Option<EffectData>,
}

impl Default for RectElement {
    fn default() -> Self {
        let mut accessibility = AccessibilityData::default();
        accessibility
            .builder
            .set_role(accesskit::Role::GenericContainer);
        Self {
            style: Default::default(),
            layout: Default::default(),
            text_style_data: Default::default(),
            relative_layer: Default::default(),
            event_handlers: Default::default(),
            accessibility,
            effect: Default::default(),
        }
    }
}

impl RectElement {
    pub fn render_shadow(
        canvas: &Canvas,
        path: &mut SkPath,
        rounded_rect: SkRRect,
        _area: Area,
        shadow: &Shadow,
        corner_radius: &CornerRadius,
    ) {
        let mut shadow_path = PathBuilder::new();
        let mut shadow_paint = Paint::default();
        shadow_paint.set_anti_alias(true);
        shadow_paint.set_color(shadow.color);

        // Shadows can be either outset or inset
        // If they are outset, we fill a copy of the path outset by spread_radius, and blur it.
        // Otherwise, we draw a stroke with the inner portion being spread_radius width, and the outer portion being blur_radius width.
        let outset: SkPoint = match shadow.position {
            ShadowPosition::Normal => {
                shadow_paint.set_style(PaintStyle::Fill);
                (shadow.spread, shadow.spread).into()
            }
            ShadowPosition::Inset => {
                shadow_paint.set_style(PaintStyle::Stroke);
                shadow_paint.set_stroke_width(shadow.blur / 2.0 + shadow.spread);
                (-shadow.spread / 2.0, -shadow.spread / 2.0).into()
            }
        };

        // Apply gassuan blur to the copied path.
        if shadow.blur > 0.0 {
            shadow_paint.set_mask_filter(SkMaskFilter::blur(
                SkBlurStyle::Normal,
                shadow.blur / 2.0,
                false,
            ));
        }

        // Add either the RRect or smoothed path based on whether smoothing is used.
        if corner_radius.smoothing > 0.0 {
            shadow_path.add_path(&corner_radius.smoothed_path(rounded_rect.with_outset(outset)));
        } else {
            shadow_path.add_rrect(rounded_rect.with_outset(outset), None, None);
        }

        // Offset our path by the shadow's x and y coordinates.
        shadow_path.offset((shadow.x, shadow.y));

        // Exclude the original path bounds from the shadow using a clip, then draw the shadow.
        canvas.save();
        canvas.clip_path(
            path,
            match shadow.position {
                ShadowPosition::Normal => ClipOp::Difference,
                ShadowPosition::Inset => ClipOp::Intersect,
            },
            true,
        );
        let shadow_path = shadow_path.detach();
        canvas.draw_path(&shadow_path, &shadow_paint);
        canvas.restore();
    }

    pub fn render_border(
        canvas: &Canvas,
        rect: SkRect,
        border: &Border,
        corner_radius: &CornerRadius,
    ) {
        let mut border_paint = Paint::default();
        border_paint.set_style(PaintStyle::Fill);
        border_paint.set_anti_alias(true);
        border_paint.set_color(border.fill);

        match Self::border_shape(rect, corner_radius, border) {
            BorderShape::DRRect(outer, inner) => {
                canvas.draw_drrect(outer, inner, &border_paint);
            }
            BorderShape::Path(path) => {
                canvas.draw_path(&path, &border_paint);
            }
        }
    }

    /// Returns a `Path` that will draw a [`Border`] around a base rectangle.
    ///
    /// We don't use Skia's stroking API here, since we might need different widths for each side.
    pub fn border_shape(
        base_rect: SkRect,
        base_corner_radius: &CornerRadius,
        border: &Border,
    ) -> BorderShape {
        let border_alignment = border.alignment;
        let border_width = border.width;

        // First we create a path that is outset from the rect by a certain amount on each side.
        //
        // Let's call this the outer border path.
        let (outer_rrect, outer_corner_radius) = {
            // Calculate the outer corner radius for the border.
            let corner_radius = CornerRadius {
                top_left: Self::outer_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.top_left,
                    border_width.top,
                    border_width.left,
                ),
                top_right: Self::outer_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.top_right,
                    border_width.top,
                    border_width.right,
                ),
                bottom_left: Self::outer_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.bottom_left,
                    border_width.bottom,
                    border_width.left,
                ),
                bottom_right: Self::outer_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.bottom_right,
                    border_width.bottom,
                    border_width.right,
                ),
                smoothing: base_corner_radius.smoothing,
            };

            let rrect = SkRRect::new_rect_radii(
                {
                    let mut rect = base_rect;
                    let alignment_scale = match border_alignment {
                        BorderAlignment::Outer => 1.0,
                        BorderAlignment::Center => 0.5,
                        BorderAlignment::Inner => 0.0,
                    };

                    rect.left -= border_width.left * alignment_scale;
                    rect.top -= border_width.top * alignment_scale;
                    rect.right += border_width.right * alignment_scale;
                    rect.bottom += border_width.bottom * alignment_scale;

                    rect
                },
                &[
                    (corner_radius.top_left, corner_radius.top_left).into(),
                    (corner_radius.top_right, corner_radius.top_right).into(),
                    (corner_radius.bottom_right, corner_radius.bottom_right).into(),
                    (corner_radius.bottom_left, corner_radius.bottom_left).into(),
                ],
            );

            (rrect, corner_radius)
        };

        // After the outer path, we will then move to the inner bounds of the border.
        let (inner_rrect, inner_corner_radius) = {
            // Calculate the inner corner radius for the border.
            let corner_radius = CornerRadius {
                top_left: Self::inner_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.top_left,
                    border_width.top,
                    border_width.left,
                ),
                top_right: Self::inner_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.top_right,
                    border_width.top,
                    border_width.right,
                ),
                bottom_left: Self::inner_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.bottom_left,
                    border_width.bottom,
                    border_width.left,
                ),
                bottom_right: Self::inner_border_path_corner_radius(
                    border_alignment,
                    base_corner_radius.bottom_right,
                    border_width.bottom,
                    border_width.right,
                ),
                smoothing: base_corner_radius.smoothing,
            };

            let rrect = SkRRect::new_rect_radii(
                {
                    let mut rect = base_rect;
                    let alignment_scale = match border_alignment {
                        BorderAlignment::Outer => 0.0,
                        BorderAlignment::Center => 0.5,
                        BorderAlignment::Inner => 1.0,
                    };

                    rect.left += border_width.left * alignment_scale;
                    rect.top += border_width.top * alignment_scale;
                    rect.right -= border_width.right * alignment_scale;
                    rect.bottom -= border_width.bottom * alignment_scale;

                    rect
                },
                &[
                    (corner_radius.top_left, corner_radius.top_left).into(),
                    (corner_radius.top_right, corner_radius.top_right).into(),
                    (corner_radius.bottom_right, corner_radius.bottom_right).into(),
                    (corner_radius.bottom_left, corner_radius.bottom_left).into(),
                ],
            );

            (rrect, corner_radius)
        };

        if base_corner_radius.smoothing > 0.0 {
            let mut path = PathBuilder::new();
            path.set_fill_type(SkPathFillType::EvenOdd);

            path.add_path(&outer_corner_radius.smoothed_path(outer_rrect));

            path.add_path(&inner_corner_radius.smoothed_path(inner_rrect));

            let path = path.detach();
            BorderShape::Path(path)
        } else {
            BorderShape::DRRect(outer_rrect, inner_rrect)
        }
    }

    fn outer_border_path_corner_radius(
        alignment: BorderAlignment,
        corner_radius: f32,
        width_1: f32,
        width_2: f32,
    ) -> f32 {
        if alignment == BorderAlignment::Inner || corner_radius == 0.0 {
            return corner_radius;
        }

        let mut offset = if width_1 == 0.0 {
            width_2
        } else if width_2 == 0.0 {
            width_1
        } else {
            width_1.min(width_2)
        };

        if alignment == BorderAlignment::Center {
            offset *= 0.5;
        }

        corner_radius + offset
    }

    fn inner_border_path_corner_radius(
        alignment: BorderAlignment,
        corner_radius: f32,
        width_1: f32,
        width_2: f32,
    ) -> f32 {
        if alignment == BorderAlignment::Outer || corner_radius == 0.0 {
            return corner_radius;
        }

        let mut offset = if width_1 == 0.0 {
            width_2
        } else if width_2 == 0.0 {
            width_1
        } else {
            width_1.min(width_2)
        };

        if alignment == BorderAlignment::Center {
            offset *= 0.5;
        }

        corner_radius - offset
    }
}

impl ElementExt for RectElement {
    fn changed(&self, other: &Rc<dyn ElementExt>) -> bool {
        let Some(rect) = (other.as_ref() as &dyn Any).downcast_ref::<Self>() else {
            return false;
        };

        self != rect
    }

    fn diff(&self, other: &Rc<dyn ElementExt>) -> DiffModifies {
        let Some(rect) = (other.as_ref() as &dyn Any).downcast_ref::<Self>() else {
            return DiffModifies::all();
        };

        let mut diff = DiffModifies::empty();

        if self.style != rect.style {
            diff.insert(DiffModifies::STYLE);
        }

        if self.effect != rect.effect {
            diff.insert(DiffModifies::EFFECT);
        }

        if !self.layout.self_layout_eq(&rect.layout.layout) {
            diff.insert(DiffModifies::STYLE);
            diff.insert(DiffModifies::LAYOUT);
        }

        if !self.layout.inner_layout_eq(&rect.layout.layout) {
            diff.insert(DiffModifies::STYLE);
            diff.insert(DiffModifies::INNER_LAYOUT);
        }

        if self.accessibility != rect.accessibility {
            diff.insert(DiffModifies::ACCESSIBILITY);
        }

        if self.relative_layer != rect.relative_layer {
            diff.insert(DiffModifies::LAYER);
        }

        if self.event_handlers != rect.event_handlers {
            diff.insert(DiffModifies::EVENT_HANDLERS);
        }

        if self.text_style_data != rect.text_style_data {
            diff.insert(DiffModifies::TEXT_STYLE);
        }

        diff
    }

    fn layout(&'_ self) -> Cow<'_, LayoutData> {
        Cow::Borrowed(&self.layout)
    }

    fn effect(&'_ self) -> Option<Cow<'_, EffectData>> {
        self.effect.as_ref().map(Cow::Borrowed)
    }

    fn style(&'_ self) -> Cow<'_, StyleState> {
        Cow::Borrowed(&self.style)
    }

    fn text_style(&'_ self) -> Cow<'_, TextStyleData> {
        Cow::Borrowed(&self.text_style_data)
    }

    fn accessibility(&'_ self) -> Cow<'_, AccessibilityData> {
        Cow::Borrowed(&self.accessibility)
    }

    fn layer(&self) -> Layer {
        self.relative_layer
    }

    fn events_handlers(&'_ self) -> Option<Cow<'_, FxHashMap<EventName, EventHandlerType>>> {
        Some(Cow::Borrowed(&self.event_handlers))
    }

    fn is_point_inside(&self, context: EventMeasurementContext) -> bool {
        let area = context.layout_node.visible_area();
        let cursor = context.cursor.to_f32();
        let rounded_rect = self.render_rect(&area, context.scale_factor as f32);
        rounded_rect.contains(SkRect::new(
            cursor.x,
            cursor.y,
            cursor.x + 0.0001,
            cursor.y + 0.0001,
        ))
    }

    fn clip(&self, context: ClipContext) {
        let area = context.visible_area;

        let rounded_rect = self.render_rect(area, context.scale_factor as f32);

        context
            .canvas
            .clip_rrect(rounded_rect, ClipOp::Intersect, true);
    }

    fn render(&self, context: RenderContext) {
        let style = self.style();

        let area = context.layout_node.visible_area();
        let corner_radius = style.corner_radius.with_scale(context.scale_factor as f32);

        let mut path = PathBuilder::new();
        let mut paint = Paint::default();
        paint.set_anti_alias(true);
        paint.set_style(PaintStyle::Fill);
        style.background.apply_to_paint(&mut paint, area);

        // Container
        let rounded_rect = self.render_rect(&area, context.scale_factor as f32);
        if corner_radius.smoothing > 0.0 {
            path.add_path(&corner_radius.smoothed_path(rounded_rect));
        } else {
            path.add_rrect(rounded_rect, None, None);
        }

        let mut path = path.detach();
        context.canvas.draw_path(&path, &paint);

        // Shadows
        for shadow in style.shadows.iter() {
            if shadow.color != Color::TRANSPARENT {
                let shadow = shadow.with_scale(context.scale_factor as f32);

                Self::render_shadow(
                    context.canvas,
                    &mut path,
                    rounded_rect,
                    area,
                    &shadow,
                    &corner_radius,
                );
            }
        }

        // Borders
        for border in style.borders.iter() {
            if border.is_visible() {
                let border = border.with_scale(context.scale_factor as f32);
                let rect = *rounded_rect.rect();
                Self::render_border(context.canvas, rect, &border, &corner_radius);
            }
        }
    }
}

pub struct Rect {
    element: RectElement,
    elements: Vec<Element>,
    key: DiffKey,
}

impl ChildrenExt for Rect {
    fn get_children(&mut self) -> &mut Vec<Element> {
        &mut self.elements
    }
}

impl KeyExt for Rect {
    fn write_key(&mut self) -> &mut DiffKey {
        &mut self.key
    }
}

impl EventHandlersExt for Rect {
    fn get_event_handlers(&mut self) -> &mut FxHashMap<EventName, EventHandlerType> {
        &mut self.element.event_handlers
    }
}

impl AccessibilityExt for Rect {
    fn get_accessibility_data(&mut self) -> &mut AccessibilityData {
        &mut self.element.accessibility
    }
}

impl TextStyleExt for Rect {
    fn get_text_style_data(&mut self) -> &mut TextStyleData {
        &mut self.element.text_style_data
    }
}

impl StyleExt for Rect {
    fn get_style(&mut self) -> &mut StyleState {
        &mut self.element.style
    }
}

impl MaybeExt for Rect {}

impl LayerExt for Rect {
    fn get_layer(&mut self) -> &mut Layer {
        &mut self.element.relative_layer
    }
}

impl LayoutExt for Rect {
    fn get_layout(&mut self) -> &mut LayoutData {
        &mut self.element.layout
    }
}

impl ContainerExt for Rect {}

impl ContainerWithContentExt for Rect {}

impl ScrollableExt for Rect {
    fn get_effect(&mut self) -> &mut EffectData {
        if self.element.effect.is_none() {
            self.element.effect = Some(EffectData::default())
        }

        self.element.effect.as_mut().unwrap()
    }
}

impl InteractiveExt for Rect {
    fn get_effect(&mut self) -> &mut EffectData {
        if self.element.effect.is_none() {
            self.element.effect = Some(EffectData::default())
        }

        self.element.effect.as_mut().unwrap()
    }
}

impl From<Rect> for Element {
    fn from(value: Rect) -> Self {
        Element::Element {
            key: value.key,
            element: Rc::new(value.element),
            elements: value.elements,
        }
    }
}

impl Rect {
    pub fn empty() -> Self {
        Self {
            element: RectElement::default(),
            elements: Vec::default(),
            key: DiffKey::None,
        }
    }

    pub fn try_downcast(element: &dyn ElementExt) -> Option<RectElement> {
        (element as &dyn Any).downcast_ref::<RectElement>().cloned()
    }

    pub fn color(mut self, color: impl Into<Color>) -> Self {
        self.element.text_style_data.color = Some(color.into());
        self
    }

    pub fn font_size(mut self, font_size: impl Into<FontSize>) -> Self {
        self.element.text_style_data.font_size = Some(font_size.into());
        self
    }

    pub fn overflow<S: Into<Overflow>>(mut self, overflow: S) -> Self {
        self.element
            .effect
            .get_or_insert_with(Default::default)
            .overflow = overflow.into();
        self
    }

    pub fn rotate<R: Into<Option<f32>>>(mut self, rotation: R) -> Self {
        self.element
            .effect
            .get_or_insert_with(Default::default)
            .rotation = rotation.into();
        self
    }

    pub fn scale(mut self, scale: impl Into<Scale>) -> Self {
        self.element
            .effect
            .get_or_insert_with(Default::default)
            .scale = Some(scale.into());
        self
    }

    pub fn opacity(mut self, opacity: impl Into<f32>) -> Self {
        self.element
            .effect
            .get_or_insert_with(Default::default)
            .opacity = Some(opacity.into());
        self
    }

    pub fn blur(mut self, blur: impl Into<f32>) -> Self {
        self.element
            .effect
            .get_or_insert_with(Default::default)
            .blur = Some(blur.into());
        self
    }
}