Resolution.cpp 1.3 KB

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