Resolution.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
  3. * Copyright (c) 2024, Glenn Skrzypczak <glenn.skrzypczak@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Resolution.h"
  8. namespace Web::CSS {
  9. Resolution::Resolution(double value, Type type)
  10. : m_type(type)
  11. , m_value(value)
  12. {
  13. }
  14. Resolution Resolution::make_dots_per_pixel(double value)
  15. {
  16. return { value, Type::Dppx };
  17. }
  18. String Resolution::to_string() const
  19. {
  20. return MUST(String::formatted("{}dppx", to_dots_per_pixel()));
  21. }
  22. double 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.0 / 2.54); // 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) || name.equals_ignoring_ascii_case("x"sv)) {
  53. return Type::Dppx;
  54. }
  55. return {};
  56. }
  57. }