Angle.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Angle.h"
  7. #include <AK/Math.h>
  8. #include <LibWeb/CSS/Percentage.h>
  9. namespace Web::CSS {
  10. Angle::Angle(int value, Type type)
  11. : m_type(type)
  12. , m_value(value)
  13. {
  14. }
  15. Angle::Angle(float value, Type type)
  16. : m_type(type)
  17. , m_value(value)
  18. {
  19. }
  20. Angle Angle::make_degrees(float value)
  21. {
  22. return { value, Type::Deg };
  23. }
  24. Angle Angle::percentage_of(Percentage const& percentage) const
  25. {
  26. return Angle { percentage.as_fraction() * m_value, m_type };
  27. }
  28. ErrorOr<String> Angle::to_string() const
  29. {
  30. return String::formatted("{}{}", m_value, unit_name());
  31. }
  32. float Angle::to_degrees() const
  33. {
  34. switch (m_type) {
  35. case Type::Deg:
  36. return m_value;
  37. case Type::Grad:
  38. return m_value * (360.0f / 400.0f);
  39. case Type::Rad:
  40. return m_value * (180.0f / AK::Pi<float>);
  41. case Type::Turn:
  42. return m_value * 360.0f;
  43. }
  44. VERIFY_NOT_REACHED();
  45. }
  46. StringView Angle::unit_name() const
  47. {
  48. switch (m_type) {
  49. case Type::Deg:
  50. return "deg"sv;
  51. case Type::Grad:
  52. return "grad"sv;
  53. case Type::Rad:
  54. return "rad"sv;
  55. case Type::Turn:
  56. return "turn"sv;
  57. }
  58. VERIFY_NOT_REACHED();
  59. }
  60. Optional<Angle::Type> Angle::unit_from_name(StringView name)
  61. {
  62. if (name.equals_ignoring_ascii_case("deg"sv)) {
  63. return Type::Deg;
  64. }
  65. if (name.equals_ignoring_ascii_case("grad"sv)) {
  66. return Type::Grad;
  67. }
  68. if (name.equals_ignoring_ascii_case("rad"sv)) {
  69. return Type::Rad;
  70. }
  71. if (name.equals_ignoring_ascii_case("turn"sv)) {
  72. return Type::Turn;
  73. }
  74. return {};
  75. }
  76. }