Resolution.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Resolution.h"
  7. #include <LibWeb/CSS/StyleValue.h>
  8. namespace Web::CSS {
  9. Resolution::Resolution(int value, Type type)
  10. : m_type(type)
  11. , m_value(value)
  12. {
  13. }
  14. Resolution::Resolution(float value, Type type)
  15. : m_type(type)
  16. , m_value(value)
  17. {
  18. }
  19. String Resolution::to_string() const
  20. {
  21. return String::formatted("{}{}", m_value, unit_name());
  22. }
  23. float Resolution::to_dots_per_pixel() const
  24. {
  25. switch (m_type) {
  26. case Type::Dpi:
  27. return m_value * 96; // 1in = 2.54cm = 96px
  28. case Type::Dpcm:
  29. return m_value * (96.0f / 2.54f); // 1cm = 96px/2.54
  30. case Type::Dppx:
  31. return m_value;
  32. }
  33. VERIFY_NOT_REACHED();
  34. }
  35. StringView Resolution::unit_name() const
  36. {
  37. switch (m_type) {
  38. case Type::Dpi:
  39. return "dpi"sv;
  40. case Type::Dpcm:
  41. return "dpcm"sv;
  42. case Type::Dppx:
  43. return "dppx"sv;
  44. }
  45. VERIFY_NOT_REACHED();
  46. }
  47. Optional<Resolution::Type> Resolution::unit_from_name(StringView name)
  48. {
  49. if (name.equals_ignoring_case("dpi"sv)) {
  50. return Type::Dpi;
  51. } else if (name.equals_ignoring_case("dpcm"sv)) {
  52. return Type::Dpcm;
  53. } else if (name.equals_ignoring_case("dppx"sv)) {
  54. return Type::Dppx;
  55. }
  56. return {};
  57. }
  58. }