Angle.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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(double value, Type type)
  11. : m_type(type)
  12. , m_value(value)
  13. {
  14. }
  15. Angle Angle::make_degrees(double value)
  16. {
  17. return { value, Type::Deg };
  18. }
  19. Angle Angle::percentage_of(Percentage const& percentage) const
  20. {
  21. return Angle { percentage.as_fraction() * m_value, m_type };
  22. }
  23. String Angle::to_string() const
  24. {
  25. return MUST(String::formatted("{}deg", to_degrees()));
  26. }
  27. double Angle::to_degrees() const
  28. {
  29. switch (m_type) {
  30. case Type::Deg:
  31. return m_value;
  32. case Type::Grad:
  33. return m_value * (360.0 / 400.0);
  34. case Type::Rad:
  35. return AK::to_degrees(m_value);
  36. case Type::Turn:
  37. return m_value * 360.0;
  38. }
  39. VERIFY_NOT_REACHED();
  40. }
  41. double Angle::to_radians() const
  42. {
  43. return AK::to_radians(to_degrees());
  44. }
  45. StringView Angle::unit_name() const
  46. {
  47. switch (m_type) {
  48. case Type::Deg:
  49. return "deg"sv;
  50. case Type::Grad:
  51. return "grad"sv;
  52. case Type::Rad:
  53. return "rad"sv;
  54. case Type::Turn:
  55. return "turn"sv;
  56. }
  57. VERIFY_NOT_REACHED();
  58. }
  59. Optional<Angle::Type> Angle::unit_from_name(StringView name)
  60. {
  61. if (name.equals_ignoring_ascii_case("deg"sv)) {
  62. return Type::Deg;
  63. }
  64. if (name.equals_ignoring_ascii_case("grad"sv)) {
  65. return Type::Grad;
  66. }
  67. if (name.equals_ignoring_ascii_case("rad"sv)) {
  68. return Type::Rad;
  69. }
  70. if (name.equals_ignoring_ascii_case("turn"sv)) {
  71. return Type::Turn;
  72. }
  73. return {};
  74. }
  75. }