color_util.cc 1.8 KB

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