Angle.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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(double value, Type type)
  16. : m_type(type)
  17. , m_value(value)
  18. {
  19. }
  20. Angle Angle::make_degrees(double 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("{}deg", to_degrees());
  31. }
  32. double 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.0 / 400.0);
  39. case Type::Rad:
  40. return m_value * (180.0 / AK::Pi<double>);
  41. case Type::Turn:
  42. return m_value * 360.0;
  43. }
  44. VERIFY_NOT_REACHED();
  45. }
  46. double Angle::to_radians() const
  47. {
  48. return to_degrees() * (AK::Pi<double> / 180.0);
  49. }
  50. StringView Angle::unit_name() const
  51. {
  52. switch (m_type) {
  53. case Type::Deg:
  54. return "deg"sv;
  55. case Type::Grad:
  56. return "grad"sv;
  57. case Type::Rad:
  58. return "rad"sv;
  59. case Type::Turn:
  60. return "turn"sv;
  61. }
  62. VERIFY_NOT_REACHED();
  63. }
  64. Optional<Angle::Type> Angle::unit_from_name(StringView name)
  65. {
  66. if (name.equals_ignoring_ascii_case("deg"sv)) {
  67. return Type::Deg;
  68. }
  69. if (name.equals_ignoring_ascii_case("grad"sv)) {
  70. return Type::Grad;
  71. }
  72. if (name.equals_ignoring_ascii_case("rad"sv)) {
  73. return Type::Rad;
  74. }
  75. if (name.equals_ignoring_ascii_case("turn"sv)) {
  76. return Type::Turn;
  77. }
  78. return {};
  79. }
  80. }