color_util.cc 1.8 KB

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