Resolution.cpp 1.3 KB

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