Angle.cpp 1.9 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. #include <LibWeb/CSS/StyleValues/CSSMathValue.h>
  10. namespace Web::CSS {
  11. Angle::Angle(double value, Type type)
  12. : m_type(type)
  13. , m_value(value)
  14. {
  15. }
  16. Angle Angle::make_degrees(double value)
  17. {
  18. return { value, Type::Deg };
  19. }
  20. Angle Angle::percentage_of(Percentage const& percentage) const
  21. {
  22. return Angle { percentage.as_fraction() * m_value, m_type };
  23. }
  24. String Angle::to_string() const
  25. {
  26. return MUST(String::formatted("{}deg", to_degrees()));
  27. }
  28. double Angle::to_degrees() const
  29. {
  30. switch (m_type) {
  31. case Type::Deg:
  32. return m_value;
  33. case Type::Grad:
  34. return m_value * (360.0 / 400.0);
  35. case Type::Rad:
  36. return AK::to_degrees(m_value);
  37. case Type::Turn:
  38. return m_value * 360.0;
  39. }
  40. VERIFY_NOT_REACHED();
  41. }
  42. double Angle::to_radians() const
  43. {
  44. return AK::to_radians(to_degrees());
  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. Angle Angle::resolve_calculated(NonnullRefPtr<CSSMathValue> const& calculated, Layout::Node const&, Angle const& reference_value)
  77. {
  78. return calculated->resolve_angle_percentage(reference_value).value();
  79. }
  80. }