color_util.cc 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 IsHexFormat(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 color_str = color_string;
  29. if (IsHexFormat(color_str)) {
  30. if (color_str.length() == 5) {
  31. // #ARGB => #RGBA
  32. std::swap(color_str[1], color_str[4]);
  33. } else {
  34. // #AARRGGBB => #RRGGBBAA
  35. std::swap(color_str[1], color_str[7]);
  36. std::swap(color_str[2], color_str[8]);
  37. }
  38. }
  39. SkColor color;
  40. if (!content::ParseCssColorString(color_str, &color))
  41. color = SK_ColorWHITE;
  42. return color;
  43. }
  44. std::string ToRGBHex(SkColor color) {
  45. return base::StringPrintf("#%02X%02X%02X", SkColorGetR(color),
  46. SkColorGetG(color), SkColorGetB(color));
  47. }
  48. std::string ToRGBAHex(SkColor color, bool include_hash) {
  49. std::string color_str = base::StringPrintf(
  50. "%02X%02X%02X%02X", SkColorGetR(color), SkColorGetG(color),
  51. SkColorGetB(color), SkColorGetA(color));
  52. if (include_hash) {
  53. return "#" + color_str;
  54. }
  55. return color_str;
  56. }
  57. } // namespace electron