AttributeParser.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/DeprecatedString.h>
  9. #include <AK/Vector.h>
  10. #include <LibGfx/Point.h>
  11. namespace Web::SVG {
  12. enum class PathInstructionType {
  13. Move,
  14. ClosePath,
  15. Line,
  16. HorizontalLine,
  17. VerticalLine,
  18. Curve,
  19. SmoothCurve,
  20. QuadraticBezierCurve,
  21. SmoothQuadraticBezierCurve,
  22. EllipticalArc,
  23. Invalid,
  24. };
  25. struct PathInstruction {
  26. PathInstructionType type;
  27. bool absolute;
  28. Vector<float> data;
  29. };
  30. class AttributeParser final {
  31. public:
  32. ~AttributeParser() = default;
  33. static Optional<float> parse_coordinate(StringView input);
  34. static Optional<float> parse_length(StringView input);
  35. static Optional<float> parse_positive_length(StringView input);
  36. static Vector<Gfx::FloatPoint> parse_points(StringView input);
  37. static Vector<PathInstruction> parse_path_data(StringView input);
  38. private:
  39. AttributeParser(StringView source);
  40. void parse_drawto();
  41. void parse_moveto();
  42. void parse_closepath();
  43. void parse_lineto();
  44. void parse_horizontal_lineto();
  45. void parse_vertical_lineto();
  46. void parse_curveto();
  47. void parse_smooth_curveto();
  48. void parse_quadratic_bezier_curveto();
  49. void parse_smooth_quadratic_bezier_curveto();
  50. void parse_elliptical_arc();
  51. float parse_length();
  52. float parse_coordinate();
  53. Vector<float> parse_coordinate_pair();
  54. Vector<float> parse_coordinate_sequence();
  55. Vector<Vector<float>> parse_coordinate_pair_sequence();
  56. Vector<float> parse_coordinate_pair_double();
  57. Vector<float> parse_coordinate_pair_triplet();
  58. Vector<float> parse_elliptical_arg_argument();
  59. void parse_whitespace(bool must_match_once = false);
  60. void parse_comma_whitespace();
  61. float parse_number();
  62. float parse_nonnegative_number();
  63. float parse_flag();
  64. // -1 if negative, +1 otherwise
  65. int parse_sign();
  66. bool match_whitespace() const;
  67. bool match_comma_whitespace() const;
  68. bool match_coordinate() const;
  69. bool match_length() const;
  70. bool match(char c) const { return !done() && ch() == c; }
  71. bool done() const { return m_cursor >= m_source.length(); }
  72. char ch() const { return m_source[m_cursor]; }
  73. char consume() { return m_source[m_cursor++]; }
  74. StringView m_source;
  75. size_t m_cursor { 0 };
  76. Vector<PathInstruction> m_instructions;
  77. };
  78. }