color_util.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (c) 2016 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/common/color_util.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include "content/public/common/color_parser.h"
  8. #include "third_party/abseil-cpp/absl/strings/str_format.h"
  9. namespace {
  10. bool IsHexFormatWithAlpha(const std::string& str) {
  11. // Must be either #ARGB or #AARRGGBB.
  12. bool is_hex_length = str.length() == 5 || str.length() == 9;
  13. if (str[0] != '#' || !is_hex_length)
  14. return false;
  15. if (!std::all_of(str.begin() + 1, str.end(), ::isxdigit))
  16. return false;
  17. return true;
  18. }
  19. } // namespace
  20. namespace electron {
  21. SkColor ParseCSSColor(const std::string& color_string) {
  22. // ParseCssColorString expects RGBA and we historically use ARGB
  23. // so we need to convert before passing to ParseCssColorString.
  24. std::string converted_color_str;
  25. if (IsHexFormatWithAlpha(color_string)) {
  26. std::string temp = color_string;
  27. int len = color_string.length() == 5 ? 1 : 2;
  28. converted_color_str = temp.erase(1, len) + color_string.substr(1, len);
  29. } else {
  30. converted_color_str = color_string;
  31. }
  32. SkColor color;
  33. if (!content::ParseCssColorString(converted_color_str, &color))
  34. color = SK_ColorWHITE;
  35. return color;
  36. }
  37. std::string ToRGBHex(SkColor color) {
  38. return absl::StrFormat("#%02X%02X%02X", SkColorGetR(color),
  39. SkColorGetG(color), SkColorGetB(color));
  40. }
  41. std::string ToRGBAHex(SkColor color, bool include_hash) {
  42. std::string color_str = absl::StrFormat(
  43. "%02X%02X%02X%02X", SkColorGetR(color), SkColorGetG(color),
  44. SkColorGetB(color), SkColorGetA(color));
  45. if (include_hash) {
  46. return "#" + color_str;
  47. }
  48. return color_str;
  49. }
  50. } // namespace electron