Resolution.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2022-2023, 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(double value, Type type)
  9. : m_type(type)
  10. , m_value(value)
  11. {
  12. }
  13. String Resolution::to_string() const
  14. {
  15. return MUST(String::formatted("{}dppx", to_dots_per_pixel()));
  16. }
  17. double Resolution::to_dots_per_pixel() const
  18. {
  19. switch (m_type) {
  20. case Type::Dpi:
  21. return m_value / 96; // 1in = 2.54cm = 96px
  22. case Type::Dpcm:
  23. return m_value / (96.0 / 2.54); // 1cm = 96px/2.54
  24. case Type::Dppx:
  25. return m_value;
  26. }
  27. VERIFY_NOT_REACHED();
  28. }
  29. StringView Resolution::unit_name() const
  30. {
  31. switch (m_type) {
  32. case Type::Dpi:
  33. return "dpi"sv;
  34. case Type::Dpcm:
  35. return "dpcm"sv;
  36. case Type::Dppx:
  37. return "dppx"sv;
  38. }
  39. VERIFY_NOT_REACHED();
  40. }
  41. Optional<Resolution::Type> Resolution::unit_from_name(StringView name)
  42. {
  43. if (name.equals_ignoring_ascii_case("dpi"sv)) {
  44. return Type::Dpi;
  45. } else if (name.equals_ignoring_ascii_case("dpcm"sv)) {
  46. return Type::Dpcm;
  47. } else if (name.equals_ignoring_ascii_case("dppx"sv)) {
  48. return Type::Dppx;
  49. }
  50. return {};
  51. }
  52. }