color_util.cc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 <cmath>
  6. #include <utility>
  7. #include <vector>
  8. #include "base/cxx17_backports.h"
  9. #include "base/strings/string_util.h"
  10. #include "base/strings/stringprintf.h"
  11. #include "content/public/common/color_parser.h"
  12. #include "ui/gfx/color_utils.h"
  13. namespace {
  14. bool IsHexFormatWithAlpha(const std::string& str) {
  15. // Must be either #ARGB or #AARRGGBB.
  16. bool is_hex_length = str.length() == 5 || str.length() == 9;
  17. if (str[0] != '#' || !is_hex_length)
  18. return false;
  19. if (!std::all_of(str.begin() + 1, str.end(), ::isxdigit))
  20. return false;
  21. return true;
  22. }
  23. } // namespace
  24. namespace electron {
  25. SkColor ParseCSSColor(const std::string& color_string) {
  26. // ParseCssColorString expects RGBA and we historically use ARGB
  27. // so we need to convert before passing to ParseCssColorString.
  28. std::string converted_color_str;
  29. if (IsHexFormatWithAlpha(color_string)) {
  30. std::string temp = color_string;
  31. int len = color_string.length() == 5 ? 1 : 2;
  32. converted_color_str = temp.erase(1, len) + color_string.substr(1, len);
  33. } else {
  34. converted_color_str = color_string;
  35. }
  36. SkColor color;
  37. if (!content::ParseCssColorString(converted_color_str, &color))
  38. color = SK_ColorWHITE;
  39. return color;
  40. }
  41. std::string ToRGBHex(SkColor color) {
  42. return base::StringPrintf("#%02X%02X%02X", SkColorGetR(color),
  43. SkColorGetG(color), SkColorGetB(color));
  44. }
  45. std::string ToRGBAHex(SkColor color, bool include_hash) {
  46. std::string color_str = base::StringPrintf(
  47. "%02X%02X%02X%02X", SkColorGetR(color), SkColorGetG(color),
  48. SkColorGetB(color), SkColorGetA(color));
  49. if (include_hash) {
  50. return "#" + color_str;
  51. }
  52. return color_str;
  53. }
  54. } // namespace electron