takumi 1.0.5

Render UI component trees to images.
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
use crate::layout::style::unexpected_token;
use cssparser::{Parser, Token, match_ignore_ascii_case};
use taffy::{AbsoluteAxis, Point, Rect, Size};

use crate::{
  layout::style::{
    Axis, BorderStyle, Color, CssDescriptorKind, CssSyntaxKind, CssToken, FromCss,
    ImageScalingAlgorithm, Length, MakeComputed, ParseResult, Sides, SpacePair,
  },
  rendering::{
    BorderProperties, BufferPool, Fill, PathBuilder, PathData, Placement, RenderContext, Sizing,
    render_mask,
  },
};

/// Represents the fill rule used for determining the interior of shapes.
///
/// Corresponds to the SVG fill-rule attribute and is used in polygon(), path(), and shape() functions.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum FillRule {
  /// The default rule - counts the number of times a ray from the point crosses the shape's edges
  #[default]
  NonZero,
  /// Counts the total number of crossings - if even, the point is outside
  EvenOdd,
}

impl MakeComputed for FillRule {}

impl From<FillRule> for Fill {
  fn from(value: FillRule) -> Self {
    match value {
      FillRule::EvenOdd => Fill::EvenOdd,
      FillRule::NonZero => Fill::NonZero,
    }
  }
}

/// Represents radius values for circle() and ellipse() functions.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub enum ShapeRadius {
  /// Uses the length from the center to the closest side of the reference box
  #[default]
  ClosestSide,
  /// Uses the length from the center to the farthest side of the reference box
  FarthestSide,
  /// A specific length value
  Length(Length),
}

impl MakeComputed for ShapeRadius {
  fn make_computed(&mut self, sizing: &Sizing) {
    if let ShapeRadius::Length(length) = self {
      length.make_computed(sizing);
    }
  }
}

/// Represents a position for circle() and ellipse() functions.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct ShapePosition(pub SpacePair<Length>);

impl MakeComputed for ShapePosition {
  fn make_computed(&mut self, sizing: &Sizing) {
    self.0.make_computed(sizing);
  }
}

impl Default for ShapePosition {
  fn default() -> Self {
    Self(SpacePair::from_single(Length::Percentage(50.0)))
  }
}

/// Represents an inset() rectangle shape.
///
/// The inset() function creates an inset rectangle, with its size defined by the offset distance
/// of each of the four sides of its container and, optionally, rounded corners.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct InsetShape {
  /// Sides of the inset.
  pub inset: Sides<Length>,
  /// Optional border radius for rounded corners
  pub border_radius: Option<Sides<Length>>,
}

impl MakeComputed for InsetShape {
  fn make_computed(&mut self, sizing: &Sizing) {
    self.inset.make_computed(sizing);
    self.border_radius.make_computed(sizing);
  }
}

/// Represents an ellipse() shape.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct EllipseShape {
  /// The horizontal radius
  pub radius_x: ShapeRadius,
  /// The vertical radius
  pub radius_y: ShapeRadius,
  /// The center position of the ellipse
  pub position: ShapePosition,
}

impl MakeComputed for EllipseShape {
  fn make_computed(&mut self, sizing: &Sizing) {
    self.radius_x.make_computed(sizing);
    self.radius_y.make_computed(sizing);
    self.position.make_computed(sizing);
  }
}

/// Represents a single coordinate pair in a polygon.
pub type PolygonCoordinate = SpacePair<Length>;

/// Represents a polygon() shape.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct PolygonShape {
  /// The fill rule to use
  pub fill_rule: Option<FillRule>,
  /// List of coordinate pairs defining the polygon vertices
  pub coordinates: Box<[PolygonCoordinate]>,
}

impl MakeComputed for PolygonShape {
  fn make_computed(&mut self, sizing: &Sizing) {
    self.coordinates.make_computed(sizing);
  }
}

/// Represents a path() shape using an SVG path string.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct PathShape {
  /// The fill rule to use
  pub fill_rule: Option<FillRule>,
  /// SVG path data string
  pub path: Box<str>,
}

/// Represents a basic shape function for clip-path.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum BasicShape {
  /// inset() function
  Inset(Box<InsetShape>),
  /// ellipse() function
  Ellipse(Box<EllipseShape>),
  /// polygon() function
  Polygon(PolygonShape),
  /// path() function
  Path(PathShape),
}

impl MakeComputed for BasicShape {
  fn make_computed(&mut self, sizing: &Sizing) {
    match self {
      BasicShape::Inset(shape) => shape.make_computed(sizing),
      BasicShape::Ellipse(shape) => shape.make_computed(sizing),
      BasicShape::Polygon(shape) => shape.make_computed(sizing),
      BasicShape::Path(_) => {}
    }
  }
}

fn resolve_radius(radius: ShapeRadius, distance: Size<f32>, sizing: &Sizing, full: f32) -> f32 {
  match radius {
    ShapeRadius::ClosestSide => distance.width.min(distance.height),
    ShapeRadius::FarthestSide => distance.width.max(distance.height),
    ShapeRadius::Length(length) => length.to_px(sizing, full),
  }
}

impl BasicShape {
  pub(crate) fn fill_rule(&self) -> Option<FillRule> {
    match self {
      BasicShape::Polygon(shape) => shape.fill_rule,
      BasicShape::Path(shape) => shape.fill_rule,
      _ => None,
    }
  }

  pub(crate) fn render_mask(
    &self,
    context: &RenderContext,
    size: Size<f32>,
    buffer_pool: &mut BufferPool,
  ) -> (Vec<u8>, Placement) {
    let mut paths = Vec::new();

    match self {
      BasicShape::Inset(shape) => {
        let inset: Rect<f32> = shape
          .inset
          .map_axis(|value, axis| {
            value.to_px(
              &context.sizing,
              match axis {
                Axis::Horizontal => size.width,
                Axis::Vertical => size.height,
              },
            )
          })
          .into();

        let border = BorderProperties {
          width: Rect::zero(),
          color: Rect {
            top: Color::transparent(),
            right: Color::transparent(),
            bottom: Color::transparent(),
            left: Color::transparent(),
          },
          radius: shape
            .border_radius
            .map(|radius| {
              Sides(
                radius
                  .0
                  .map(|corner| SpacePair::from_single(corner.to_px(&context.sizing, size.width))),
              )
            })
            .unwrap_or_default(),
          image_rendering: ImageScalingAlgorithm::Auto,
          style: Rect {
            top: BorderStyle::Solid,
            right: BorderStyle::Solid,
            bottom: BorderStyle::Solid,
            left: BorderStyle::Solid,
          },
        };

        border.append_mask_commands(
          &mut paths,
          Size {
            width: size.width - inset.grid_axis_sum(AbsoluteAxis::Horizontal),
            height: size.height - inset.grid_axis_sum(AbsoluteAxis::Vertical),
          },
          Point {
            x: inset.left,
            y: inset.top,
          },
        );
      }
      BasicShape::Ellipse(shape) => {
        let distance = Size {
          width: shape.position.0.x.to_px(&context.sizing, size.width),
          height: shape.position.0.y.to_px(&context.sizing, size.height),
        };

        paths.add_ellipse(
          (distance.width, distance.height),
          resolve_radius(shape.radius_x, distance, &context.sizing, size.width),
          resolve_radius(shape.radius_y, distance, &context.sizing, size.height),
        );
      }
      BasicShape::Polygon(shape) => {
        if !shape.coordinates.is_empty() {
          // Start the path at the first coordinate
          let first = &shape.coordinates[0];
          let first_x = first.x.to_px(&context.sizing, size.width);
          let first_y = first.y.to_px(&context.sizing, size.height);

          paths.move_to((first_x, first_y));

          // Add lines to each subsequent coordinate
          for coord in &shape.coordinates[1..] {
            let x = coord.x.to_px(&context.sizing, size.width);
            let y = coord.y.to_px(&context.sizing, size.height);
            paths.line_to((x, y));
          }

          // Close the path to complete the polygon
          paths.close();
        }
      }
      BasicShape::Path(shape) => {
        paths.extend(shape.path.as_ref().commands());
      }
    }

    render_mask(
      &paths,
      Some(context.transform),
      Some(Fill::from(self.fill_rule().unwrap_or(context.style.clip_rule)).into()),
      buffer_pool,
    )
  }
}

impl<'i> FromCss<'i> for FillRule {
  fn from_css(parser: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let location = parser.current_source_location();
    let ident = parser.expect_ident()?;

    match_ignore_ascii_case! { &ident,
      "nonzero" => Ok(FillRule::NonZero),
      "evenodd" => Ok(FillRule::EvenOdd),
      _ => Err(unexpected_token!(location, &Token::Ident(ident.clone()))),
    }
  }

  const VALID_TOKENS: &'static [CssToken] =
    &[CssToken::Keyword("nonzero"), CssToken::Keyword("evenodd")];
}

impl<'i> FromCss<'i> for ShapeRadius {
  fn from_css(parser: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let location = parser.current_source_location();

    // Try parsing as length first
    if let Ok(length) = parser.try_parse(Length::from_css) {
      return Ok(ShapeRadius::Length(length));
    }

    // Try parsing keywords
    let ident = parser.expect_ident()?;
    match_ignore_ascii_case! { &ident,
      "closest-side" => Ok(ShapeRadius::ClosestSide),
      "farthest-side" => Ok(ShapeRadius::FarthestSide),
      _ => Err(unexpected_token!(location, &Token::Ident(ident.clone()))),
    }
  }

  const VALID_TOKENS: &'static [CssToken] = &[
    CssToken::Keyword("closest-side"),
    CssToken::Keyword("farthest-side"),
    CssToken::Syntax(CssSyntaxKind::Length),
  ];
}

impl<'i> FromCss<'i> for ShapePosition {
  fn from_css(parser: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let first = Length::from_css(parser)?;

    // If there's a second value, parse it; otherwise default to 50%
    let second = parser
      .try_parse(Length::from_css)
      .unwrap_or(Length::Percentage(50.0));

    Ok(ShapePosition(SpacePair::from_pair(first, second)))
  }

  const VALID_TOKENS: &'static [CssToken] = Length::<true>::VALID_TOKENS;
}

impl<'i> FromCss<'i> for BasicShape {
  fn from_css(parser: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let location = parser.current_source_location();
    let token = parser.next()?;

    match token {
      Token::Function(function) => {
        match_ignore_ascii_case! { &function,
          "inset" => parser.parse_nested_block(|input| {
            let inset = Sides::from_css(input)?;

            // Parse border radius with "round" keyword
            let border_radius = if input.try_parse(|input| input.expect_ident_matching("round")).is_ok() {
              Some(Sides::from_css(input)?)
            } else {
              None
            };

            Ok(BasicShape::Inset(Box::new(InsetShape {
              inset,
              border_radius,
            })))
          }),
          "circle" => parser.parse_nested_block(|input| {
            let radius = input.try_parse(ShapeRadius::from_css).unwrap_or_default();

            let position = if input.try_parse(|input| input.expect_ident_matching("at")).is_ok() {
              ShapePosition::from_css(input)?
            } else {
              ShapePosition::default()
            };

            Ok(BasicShape::Ellipse(Box::new(EllipseShape { radius_x: radius, radius_y: radius, position })))
          }),
          "ellipse" => parser.parse_nested_block(|input| {
            let radius_x = ShapeRadius::from_css(input)?;
            let radius_y = input.try_parse(ShapeRadius::from_css).unwrap_or_default();

            let position = if input.try_parse(|input| input.expect_ident_matching("at")).is_ok() {
              ShapePosition::from_css(input)?
            } else {
              ShapePosition::default()
            };

            Ok(BasicShape::Ellipse(Box::new(EllipseShape { radius_x, radius_y, position })))
          }),
          "polygon" => parser.parse_nested_block(|input| {
            let fill_rule = input.try_parse(FillRule::from_css).ok();
            if fill_rule.is_some() {
              input.expect_comma()?;
            }

            Ok(BasicShape::Polygon(PolygonShape {
              fill_rule,
              coordinates: input
                .parse_comma_separated(PolygonCoordinate::from_css)?
                .into_boxed_slice(),
            }))
          }),
          "path" => parser.parse_nested_block(|input| {
            let fill_rule = input.try_parse(FillRule::from_css).ok();
            if fill_rule.is_some() {
              input.expect_comma()?;
            }

            let path = input.expect_string()?.as_ref().into();

            Ok(BasicShape::Path(PathShape {
              fill_rule,
              path,
            }))
          }),
          _ => Err(unexpected_token!(location, token)),
        }
      }
      _ => Err(unexpected_token!(location, token)),
    }
  }

  const VALID_TOKENS: &'static [CssToken] = &[
    CssToken::Descriptor(CssDescriptorKind::InsetFn),
    CssToken::Descriptor(CssDescriptorKind::CircleFn),
    CssToken::Descriptor(CssDescriptorKind::EllipseFn),
    CssToken::Descriptor(CssDescriptorKind::PolygonFn),
    CssToken::Descriptor(CssDescriptorKind::PathFn),
  ];
}

#[cfg(test)]
mod tests {
  use super::*;
  use Length::*;

  #[test]
  fn test_parse_inset_simple() {
    assert_eq!(
      BasicShape::from_str("inset(10px)"),
      Ok(BasicShape::Inset(Box::new(InsetShape {
        inset: Sides([Px(10.0); 4]),
        border_radius: None,
      })))
    );
  }

  #[test]
  fn test_parse_inset_four_values() {
    assert_eq!(
      BasicShape::from_str("inset(10px 20px 30px 40px)"),
      Ok(BasicShape::Inset(Box::new(InsetShape {
        inset: Sides([Px(10.0), Px(20.0), Px(30.0), Px(40.0)]),
        border_radius: None,
      })))
    );
  }

  #[test]
  fn test_parse_inset_with_border_radius() {
    assert_eq!(
      BasicShape::from_str("inset(10px round 5px)"),
      Ok(BasicShape::Inset(Box::new(InsetShape {
        inset: Sides::from(Px(10.0)),
        border_radius: Some(Sides::from(Px(5.0))),
      })))
    );
  }

  #[test]
  fn test_parse_inset_with_complex_border_radius() {
    assert_eq!(
      BasicShape::from_str("inset(10px 20px 30px 40px round 5px 10px 15px 20px)"),
      Ok(BasicShape::Inset(Box::new(InsetShape {
        inset: Sides([Px(10.0), Px(20.0), Px(30.0), Px(40.0)]),
        border_radius: Some(Sides([Px(5.0), Px(10.0), Px(15.0), Px(20.0)])),
      })))
    );
  }

  #[test]
  fn test_parse_circle_simple() {
    assert_eq!(
      BasicShape::from_str("circle(50px)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::Length(Px(50.0)),
        radius_y: ShapeRadius::Length(Px(50.0)),
        position: ShapePosition::default(),
      })))
    );
  }

  #[test]
  fn test_parse_circle_with_position() {
    assert_eq!(
      BasicShape::from_str("circle(50px at 25% 75%)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::Length(Px(50.0)),
        radius_y: ShapeRadius::Length(Px(50.0)),
        position: ShapePosition(SpacePair {
          x: Length::Percentage(25.0),
          y: Length::Percentage(75.0),
        }),
      })))
    );
  }

  #[test]
  fn test_parse_circle_default_radius() {
    assert_eq!(
      BasicShape::from_str("circle(at 25% 75%)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::ClosestSide,
        radius_y: ShapeRadius::ClosestSide,
        position: ShapePosition(SpacePair {
          x: Length::Percentage(25.0),
          y: Length::Percentage(75.0),
        }),
      })))
    );
  }

  #[test]
  fn test_parse_ellipse_simple() {
    assert_eq!(
      BasicShape::from_str("ellipse(50px 30px)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::Length(Px(50.0)),
        radius_y: ShapeRadius::Length(Px(30.0)),
        position: ShapePosition::default(),
      })))
    );
  }

  #[test]
  fn test_parse_ellipse_with_position() {
    assert_eq!(
      BasicShape::from_str("ellipse(50px 30px at 25% 75%)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::Length(Px(50.0)),
        radius_y: ShapeRadius::Length(Px(30.0)),
        position: ShapePosition(SpacePair {
          x: Length::Percentage(25.0),
          y: Length::Percentage(75.0),
        }),
      })))
    );
  }

  #[test]
  fn test_parse_polygon_triangle() {
    assert!(matches!(
      BasicShape::from_str("polygon(50% 0%, 0% 100%, 100% 100%)"),
      Ok(BasicShape::Polygon(PolygonShape {
        fill_rule: None,
        coordinates: coords,
      })) if coords.len() == 3 &&
            coords[0] == SpacePair { x: Length::Percentage(50.0), y: Length::Percentage(0.0) } &&
            coords[1] == SpacePair { x: Length::Percentage(0.0), y: Length::Percentage(100.0) } &&
            coords[2] == SpacePair { x: Length::Percentage(100.0), y: Length::Percentage(100.0) }
    ));
  }

  #[test]
  fn test_parse_polygon_with_fill_rule() {
    assert!(matches!(
      BasicShape::from_str("polygon(evenodd, 50% 0%, 0% 100%, 100% 100%)"),
      Ok(BasicShape::Polygon(PolygonShape {
        fill_rule: Some(FillRule::EvenOdd),
        coordinates: coords,
      })) if coords.len() == 3
    ));
  }

  #[test]
  fn test_parse_path() {
    assert_eq!(
      BasicShape::from_str("path('M 10 10 L 90 90')"),
      Ok(BasicShape::Path(PathShape {
        fill_rule: None,
        path: "M 10 10 L 90 90".into(),
      }))
    );
  }

  #[test]
  fn test_parse_path_with_fill_rule() {
    assert_eq!(
      BasicShape::from_str("path(evenodd, 'M 10 10 L 90 90')"),
      Ok(BasicShape::Path(PathShape {
        fill_rule: Some(FillRule::EvenOdd),
        path: "M 10 10 L 90 90".into(),
      }))
    );
  }

  #[test]
  fn test_parse_circle_percentage_radius() {
    assert_eq!(
      BasicShape::from_str("circle(50%)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::Length(Length::Percentage(50.0)),
        radius_y: ShapeRadius::Length(Length::Percentage(50.0)),
        position: ShapePosition::default(),
      })))
    );
  }

  #[test]
  fn test_parse_circle_closest_side() {
    assert_eq!(
      BasicShape::from_str("circle(closest-side)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::ClosestSide,
        radius_y: ShapeRadius::ClosestSide,
        position: ShapePosition::default(),
      })))
    );
  }

  #[test]
  fn test_parse_circle_farthest_side() {
    assert_eq!(
      BasicShape::from_str("circle(farthest-side)"),
      Ok(BasicShape::Ellipse(Box::new(EllipseShape {
        radius_x: ShapeRadius::FarthestSide,
        radius_y: ShapeRadius::FarthestSide,
        position: ShapePosition::default(),
      })))
    );
  }
}