CSSRGB.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2024, Sam Atkins <sam@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "CSSRGB.h"
  7. #include <AK/TypeCasts.h>
  8. #include <LibWeb/CSS/Serialize.h>
  9. #include <LibWeb/CSS/StyleValues/CSSMathValue.h>
  10. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  11. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  12. namespace Web::CSS {
  13. Color CSSRGB::to_color(Optional<Layout::NodeWithStyle const&>) const
  14. {
  15. auto resolve_rgb_to_u8 = [](CSSStyleValue const& style_value) -> Optional<u8> {
  16. // <number> | <percentage> | none
  17. auto normalized = [](double number) {
  18. return llround(clamp(number, 0.0, 255.0));
  19. };
  20. if (style_value.is_number())
  21. return normalized(style_value.as_number().number());
  22. if (style_value.is_percentage())
  23. return normalized(style_value.as_percentage().value() * 2.55);
  24. if (style_value.is_math()) {
  25. auto const& calculated = style_value.as_math();
  26. if (calculated.resolves_to_number())
  27. return normalized(calculated.resolve_number().value());
  28. if (calculated.resolves_to_percentage())
  29. return normalized(calculated.resolve_percentage().value().value() * 2.55);
  30. }
  31. if (style_value.is_keyword() && style_value.to_keyword() == Keyword::None)
  32. return 0;
  33. return {};
  34. };
  35. auto resolve_alpha_to_u8 = [](CSSStyleValue const& style_value) -> Optional<u8> {
  36. auto alpha_0_1 = resolve_alpha(style_value);
  37. if (alpha_0_1.has_value())
  38. return llround(clamp(alpha_0_1.value() * 255.0, 0.0, 255.0));
  39. return {};
  40. };
  41. u8 const r_val = resolve_rgb_to_u8(m_properties.r).value_or(0);
  42. u8 const g_val = resolve_rgb_to_u8(m_properties.g).value_or(0);
  43. u8 const b_val = resolve_rgb_to_u8(m_properties.b).value_or(0);
  44. u8 const alpha_val = resolve_alpha_to_u8(m_properties.alpha).value_or(255);
  45. return Color(r_val, g_val, b_val, alpha_val);
  46. }
  47. bool CSSRGB::equals(CSSStyleValue const& other) const
  48. {
  49. if (type() != other.type())
  50. return false;
  51. auto const& other_color = other.as_color();
  52. if (color_type() != other_color.color_type())
  53. return false;
  54. auto const& other_rgb = verify_cast<CSSRGB>(other_color);
  55. return m_properties == other_rgb.m_properties;
  56. }
  57. // https://www.w3.org/TR/css-color-4/#serializing-sRGB-values
  58. String CSSRGB::to_string() const
  59. {
  60. // FIXME: Do this properly, taking unresolved calculated values into account.
  61. return serialize_a_srgb_value(to_color({}));
  62. }
  63. }