paint_vector_icon.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ui/gfx/paint_vector_icon.h"
  5. #include <algorithm>
  6. #include <map>
  7. #include <tuple>
  8. #include "base/i18n/rtl.h"
  9. #include "base/lazy_instance.h"
  10. #include "base/memory/raw_ptr.h"
  11. #include "base/numerics/safe_conversions.h"
  12. #include "base/strings/string_number_conversions.h"
  13. #include "base/strings/string_split.h"
  14. #include "base/trace_event/trace_event.h"
  15. #include "cc/paint/paint_canvas.h"
  16. #include "cc/paint/paint_flags.h"
  17. #include "third_party/skia/include/core/SkPath.h"
  18. #include "ui/gfx/animation/tween.h"
  19. #include "ui/gfx/canvas.h"
  20. #include "ui/gfx/color_palette.h"
  21. #include "ui/gfx/image/canvas_image_source.h"
  22. #include "ui/gfx/scoped_canvas.h"
  23. #include "ui/gfx/vector_icon_types.h"
  24. #include "ui/gfx/vector_icon_utils.h"
  25. namespace gfx {
  26. namespace {
  27. // The default size of a single side of the square canvas to which path
  28. // coordinates are relative, in device independent pixels.
  29. constexpr int kReferenceSizeDip = 48;
  30. constexpr int kEmptyIconSize = -1;
  31. // Retrieves the specified CANVAS_DIMENSIONS size from a PathElement.
  32. int GetCanvasDimensions(const PathElement* path) {
  33. if (!path)
  34. return kEmptyIconSize;
  35. return path[0].command == CANVAS_DIMENSIONS ? path[1].arg : kReferenceSizeDip;
  36. }
  37. // Retrieves the appropriate icon representation to draw when the pixel size
  38. // requested is |icon_size_px|.
  39. const VectorIconRep* GetRepForPxSize(const VectorIcon& icon, int icon_size_px) {
  40. if (icon.is_empty())
  41. return nullptr;
  42. const VectorIconRep* best_rep = nullptr;
  43. // Prefer an exact match. If none exists, prefer the largest rep that is an
  44. // exact divisor of the icon size (e.g. 20 for a 40px icon). If none exists,
  45. // return the smallest rep that is larger than the target. If none exists,
  46. // use the largest rep. The rep array is sorted by size in descending order,
  47. // so start at the back and work towards the front.
  48. for (int i = static_cast<int>(icon.reps_size - 1); i >= 0; --i) {
  49. const VectorIconRep* rep = &icon.reps[i];
  50. int rep_size = GetCanvasDimensions(rep->path);
  51. if (rep_size == icon_size_px)
  52. return rep;
  53. if (icon_size_px % rep_size == 0)
  54. best_rep = rep;
  55. if (rep_size > icon_size_px)
  56. return best_rep ? best_rep : &icon.reps[i];
  57. }
  58. return best_rep ? best_rep : &icon.reps[0];
  59. }
  60. struct CompareIconDescription {
  61. bool operator()(const IconDescription& a, const IconDescription& b) const {
  62. const VectorIcon* a_icon = &a.icon;
  63. const VectorIcon* b_icon = &b.icon;
  64. const VectorIcon* a_badge = &a.badge_icon;
  65. const VectorIcon* b_badge = &b.badge_icon;
  66. return std::tie(a_icon, a.dip_size, a.color, a_badge) <
  67. std::tie(b_icon, b.dip_size, b.color, b_badge);
  68. }
  69. };
  70. // Helper that simplifies iterating over a sequence of PathElements.
  71. class PathParser {
  72. public:
  73. PathParser(const PathElement* path_elements, size_t path_size)
  74. : path_elements_(path_elements), path_size_(path_size) {}
  75. PathParser(const PathParser&) = delete;
  76. PathParser& operator=(const PathParser&) = delete;
  77. ~PathParser() {}
  78. void Advance() { command_index_ += GetArgumentCount() + 1; }
  79. bool HasCommandsRemaining() const { return command_index_ < path_size_; }
  80. CommandType CurrentCommand() const {
  81. return path_elements_[command_index_].command;
  82. }
  83. SkScalar GetArgument(int index) const {
  84. DCHECK_LT(index, GetArgumentCount());
  85. return path_elements_[command_index_ + 1 + index].arg;
  86. }
  87. private:
  88. int GetArgumentCount() const {
  89. switch (CurrentCommand()) {
  90. case STROKE:
  91. case H_LINE_TO:
  92. case R_H_LINE_TO:
  93. case V_LINE_TO:
  94. case R_V_LINE_TO:
  95. case CANVAS_DIMENSIONS:
  96. case PATH_COLOR_ALPHA:
  97. return 1;
  98. case MOVE_TO:
  99. case R_MOVE_TO:
  100. case LINE_TO:
  101. case R_LINE_TO:
  102. case QUADRATIC_TO_SHORTHAND:
  103. case R_QUADRATIC_TO_SHORTHAND:
  104. return 2;
  105. case CIRCLE:
  106. return 3;
  107. case PATH_COLOR_ARGB:
  108. case CUBIC_TO_SHORTHAND:
  109. case CLIP:
  110. case QUADRATIC_TO:
  111. case R_QUADRATIC_TO:
  112. case OVAL:
  113. return 4;
  114. case ROUND_RECT:
  115. return 5;
  116. case CUBIC_TO:
  117. case R_CUBIC_TO:
  118. return 6;
  119. case ARC_TO:
  120. case R_ARC_TO:
  121. return 7;
  122. case NEW_PATH:
  123. case PATH_MODE_CLEAR:
  124. case CAP_SQUARE:
  125. case CLOSE:
  126. case DISABLE_AA:
  127. case FLIPS_IN_RTL:
  128. return 0;
  129. }
  130. NOTREACHED();
  131. return 0;
  132. }
  133. raw_ptr<const PathElement> path_elements_;
  134. size_t path_size_;
  135. size_t command_index_ = 0;
  136. };
  137. // Translates a string such as "MOVE_TO" into a command such as MOVE_TO.
  138. CommandType CommandFromString(const std::string& source) {
  139. #define RETURN_IF_IS(command) \
  140. if (source == #command) \
  141. return command;
  142. RETURN_IF_IS(NEW_PATH);
  143. RETURN_IF_IS(PATH_COLOR_ALPHA);
  144. RETURN_IF_IS(PATH_COLOR_ARGB);
  145. RETURN_IF_IS(PATH_MODE_CLEAR);
  146. RETURN_IF_IS(STROKE);
  147. RETURN_IF_IS(CAP_SQUARE);
  148. RETURN_IF_IS(MOVE_TO);
  149. RETURN_IF_IS(R_MOVE_TO);
  150. RETURN_IF_IS(ARC_TO);
  151. RETURN_IF_IS(R_ARC_TO);
  152. RETURN_IF_IS(LINE_TO);
  153. RETURN_IF_IS(R_LINE_TO);
  154. RETURN_IF_IS(H_LINE_TO);
  155. RETURN_IF_IS(R_H_LINE_TO);
  156. RETURN_IF_IS(V_LINE_TO);
  157. RETURN_IF_IS(R_V_LINE_TO);
  158. RETURN_IF_IS(CUBIC_TO);
  159. RETURN_IF_IS(R_CUBIC_TO);
  160. RETURN_IF_IS(CUBIC_TO_SHORTHAND);
  161. RETURN_IF_IS(QUADRATIC_TO);
  162. RETURN_IF_IS(R_QUADRATIC_TO);
  163. RETURN_IF_IS(QUADRATIC_TO_SHORTHAND);
  164. RETURN_IF_IS(R_QUADRATIC_TO_SHORTHAND);
  165. RETURN_IF_IS(CIRCLE);
  166. RETURN_IF_IS(OVAL);
  167. RETURN_IF_IS(ROUND_RECT);
  168. RETURN_IF_IS(CLOSE);
  169. RETURN_IF_IS(CANVAS_DIMENSIONS);
  170. RETURN_IF_IS(CLIP);
  171. RETURN_IF_IS(DISABLE_AA);
  172. RETURN_IF_IS(FLIPS_IN_RTL);
  173. #undef RETURN_IF_IS
  174. NOTREACHED() << "Unrecognized command: " << source;
  175. return CLOSE;
  176. }
  177. std::vector<PathElement> PathFromSource(const std::string& source) {
  178. std::vector<PathElement> path;
  179. std::vector<std::string> pieces = base::SplitString(
  180. source, "\n ,f", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  181. for (const auto& piece : pieces) {
  182. double value = 0;
  183. int hex_value = 0;
  184. if (base::StringToDouble(piece, &value))
  185. path.push_back(PathElement(SkDoubleToScalar(value)));
  186. else if (base::HexStringToInt(piece, &hex_value))
  187. path.push_back(PathElement(SkIntToScalar(hex_value)));
  188. else
  189. path.push_back(PathElement(CommandFromString(piece)));
  190. }
  191. return path;
  192. }
  193. bool IsCommandTypeCurve(CommandType command) {
  194. return command == CUBIC_TO || command == R_CUBIC_TO ||
  195. command == CUBIC_TO_SHORTHAND || command == QUADRATIC_TO ||
  196. command == R_QUADRATIC_TO || command == QUADRATIC_TO_SHORTHAND ||
  197. command == R_QUADRATIC_TO_SHORTHAND;
  198. }
  199. void PaintPath(Canvas* canvas,
  200. const PathElement* path_elements,
  201. size_t path_size,
  202. int dip_size,
  203. SkColor color) {
  204. int canvas_size = kReferenceSizeDip;
  205. std::vector<SkPath> paths;
  206. std::vector<cc::PaintFlags> flags_array;
  207. SkRect clip_rect = SkRect::MakeEmpty();
  208. bool flips_in_rtl = false;
  209. CommandType previous_command_type = NEW_PATH;
  210. for (PathParser parser(path_elements, path_size);
  211. parser.HasCommandsRemaining(); parser.Advance()) {
  212. auto arg = [&parser](int i) { return parser.GetArgument(i); };
  213. const CommandType command_type = parser.CurrentCommand();
  214. auto start_new_path = [&paths]() {
  215. paths.push_back(SkPath());
  216. paths.back().setFillType(SkPathFillType::kEvenOdd);
  217. };
  218. auto start_new_flags = [&flags_array, &color]() {
  219. flags_array.push_back(cc::PaintFlags());
  220. flags_array.back().setColor(color);
  221. flags_array.back().setAntiAlias(true);
  222. flags_array.back().setStrokeCap(cc::PaintFlags::kRound_Cap);
  223. };
  224. if (paths.empty() || command_type == NEW_PATH) {
  225. start_new_path();
  226. start_new_flags();
  227. }
  228. SkPath& path = paths.back();
  229. cc::PaintFlags& flags = flags_array.back();
  230. switch (command_type) {
  231. // Handled above.
  232. case NEW_PATH:
  233. break;
  234. case PATH_COLOR_ALPHA:
  235. flags.setAlpha(SkScalarFloorToInt(arg(0)));
  236. break;
  237. case PATH_COLOR_ARGB:
  238. flags.setColor(SkColorSetARGB(
  239. SkScalarFloorToInt(arg(0)), SkScalarFloorToInt(arg(1)),
  240. SkScalarFloorToInt(arg(2)), SkScalarFloorToInt(arg(3))));
  241. break;
  242. case PATH_MODE_CLEAR:
  243. flags.setBlendMode(SkBlendMode::kClear);
  244. break;
  245. case STROKE:
  246. flags.setStyle(cc::PaintFlags::kStroke_Style);
  247. flags.setStrokeWidth(arg(0));
  248. break;
  249. case CAP_SQUARE:
  250. flags.setStrokeCap(cc::PaintFlags::kSquare_Cap);
  251. break;
  252. case MOVE_TO:
  253. path.moveTo(arg(0), arg(1));
  254. break;
  255. case R_MOVE_TO:
  256. if (previous_command_type == CLOSE) {
  257. // This triggers injectMoveToIfNeeded() so that the next subpath
  258. // will start at the correct place. See [
  259. // https://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand ].
  260. path.rLineTo(0, 0);
  261. }
  262. path.rMoveTo(arg(0), arg(1));
  263. break;
  264. case ARC_TO:
  265. case R_ARC_TO: {
  266. SkScalar rx = arg(0);
  267. SkScalar ry = arg(1);
  268. SkScalar angle = arg(2);
  269. SkScalar large_arc_flag = arg(3);
  270. SkScalar arc_sweep_flag = arg(4);
  271. SkScalar x = arg(5);
  272. SkScalar y = arg(6);
  273. SkPath::ArcSize arc_size =
  274. large_arc_flag ? SkPath::kLarge_ArcSize : SkPath::kSmall_ArcSize;
  275. SkPathDirection direction =
  276. arc_sweep_flag ? SkPathDirection::kCW : SkPathDirection::kCCW;
  277. if (command_type == ARC_TO)
  278. path.arcTo(rx, ry, angle, arc_size, direction, x, y);
  279. else
  280. path.rArcTo(rx, ry, angle, arc_size, direction, x, y);
  281. break;
  282. }
  283. case LINE_TO:
  284. path.lineTo(arg(0), arg(1));
  285. break;
  286. case R_LINE_TO:
  287. path.rLineTo(arg(0), arg(1));
  288. break;
  289. case H_LINE_TO: {
  290. SkPoint last_point;
  291. path.getLastPt(&last_point);
  292. path.lineTo(arg(0), last_point.fY);
  293. break;
  294. }
  295. case R_H_LINE_TO:
  296. path.rLineTo(arg(0), 0);
  297. break;
  298. case V_LINE_TO: {
  299. SkPoint last_point;
  300. path.getLastPt(&last_point);
  301. path.lineTo(last_point.fX, arg(0));
  302. break;
  303. }
  304. case R_V_LINE_TO:
  305. path.rLineTo(0, arg(0));
  306. break;
  307. case CUBIC_TO:
  308. path.cubicTo(arg(0), arg(1), arg(2), arg(3), arg(4), arg(5));
  309. break;
  310. case R_CUBIC_TO:
  311. path.rCubicTo(arg(0), arg(1), arg(2), arg(3), arg(4), arg(5));
  312. break;
  313. case CUBIC_TO_SHORTHAND:
  314. case QUADRATIC_TO_SHORTHAND:
  315. case R_QUADRATIC_TO_SHORTHAND: {
  316. // Compute the first control point (|x1| and |y1|) as the reflection of
  317. // the last control point on the previous command relative to the
  318. // current point. If there is no previous command or if the previous
  319. // command is not a Bezier curve, the first control point is coincident
  320. // with the current point. Refer to the SVG path specs for further
  321. // details.
  322. // Note that |x1| and |y1| will correspond to the sole control point if
  323. // calculating a quadratic curve.
  324. SkPoint last_point;
  325. path.getLastPt(&last_point);
  326. SkScalar delta_x = 0;
  327. SkScalar delta_y = 0;
  328. if (IsCommandTypeCurve(previous_command_type)) {
  329. SkPoint last_control_point = path.getPoint(path.countPoints() - 2);
  330. // We find what the delta was between the last curve's starting point
  331. // and the control point. This difference is what we will reflect on
  332. // the current point, creating our new control point.
  333. delta_x = last_point.fX - last_control_point.fX;
  334. delta_y = last_point.fY - last_control_point.fY;
  335. }
  336. SkScalar x1 = last_point.fX + delta_x;
  337. SkScalar y1 = last_point.fY + delta_y;
  338. if (command_type == CUBIC_TO_SHORTHAND)
  339. path.cubicTo(x1, y1, arg(0), arg(1), arg(2), arg(3));
  340. else if (command_type == QUADRATIC_TO_SHORTHAND)
  341. path.quadTo(x1, y1, arg(0), arg(1));
  342. else if (command_type == R_QUADRATIC_TO_SHORTHAND)
  343. path.rQuadTo(x1, y1, arg(0), arg(1));
  344. break;
  345. }
  346. case QUADRATIC_TO:
  347. path.quadTo(arg(0), arg(1), arg(2), arg(3));
  348. break;
  349. case R_QUADRATIC_TO:
  350. path.rQuadTo(arg(0), arg(1), arg(2), arg(3));
  351. break;
  352. case OVAL: {
  353. SkScalar x = arg(0);
  354. SkScalar y = arg(1);
  355. SkScalar rx = arg(2);
  356. SkScalar ry = arg(3);
  357. path.addOval(SkRect::MakeLTRB(x - rx, y - ry, x + rx, y + ry));
  358. break;
  359. }
  360. case CIRCLE:
  361. path.addCircle(arg(0), arg(1), arg(2));
  362. break;
  363. case ROUND_RECT:
  364. path.addRoundRect(SkRect::MakeXYWH(arg(0), arg(1), arg(2), arg(3)),
  365. arg(4), arg(4));
  366. break;
  367. case CLOSE:
  368. path.close();
  369. break;
  370. case CANVAS_DIMENSIONS:
  371. canvas_size = SkScalarTruncToInt(arg(0));
  372. break;
  373. case CLIP:
  374. clip_rect = SkRect::MakeXYWH(arg(0), arg(1), arg(2), arg(3));
  375. break;
  376. case DISABLE_AA:
  377. flags.setAntiAlias(false);
  378. break;
  379. case FLIPS_IN_RTL:
  380. flips_in_rtl = true;
  381. break;
  382. }
  383. previous_command_type = command_type;
  384. }
  385. ScopedCanvas scoped_canvas(canvas);
  386. if (dip_size != canvas_size) {
  387. SkScalar scale = SkIntToScalar(dip_size) / SkIntToScalar(canvas_size);
  388. canvas->sk_canvas()->scale(scale, scale);
  389. }
  390. if (flips_in_rtl)
  391. scoped_canvas.FlipIfRTL(canvas_size);
  392. if (!clip_rect.isEmpty())
  393. canvas->sk_canvas()->clipRect(clip_rect);
  394. DCHECK_EQ(flags_array.size(), paths.size());
  395. for (size_t i = 0; i < paths.size(); ++i)
  396. canvas->DrawPath(paths[i], flags_array[i]);
  397. }
  398. class VectorIconSource : public CanvasImageSource {
  399. public:
  400. explicit VectorIconSource(const IconDescription& data)
  401. : CanvasImageSource(Size(data.dip_size, data.dip_size)), data_(data) {}
  402. VectorIconSource(const std::string& definition, int dip_size, SkColor color)
  403. : CanvasImageSource(Size(dip_size, dip_size)),
  404. data_(kNoneIcon, dip_size, color, &kNoneIcon),
  405. path_(PathFromSource(definition)) {}
  406. VectorIconSource(const VectorIconSource&) = delete;
  407. VectorIconSource& operator=(const VectorIconSource&) = delete;
  408. ~VectorIconSource() override {}
  409. // CanvasImageSource:
  410. bool HasRepresentationAtAllScales() const override {
  411. return !data_.icon.is_empty();
  412. }
  413. void Draw(Canvas* canvas) override {
  414. if (path_.empty()) {
  415. PaintVectorIcon(canvas, data_.icon, size_.width(), data_.color);
  416. if (!data_.badge_icon.is_empty())
  417. PaintVectorIcon(canvas, data_.badge_icon, size_.width(), data_.color);
  418. } else {
  419. PaintPath(canvas, path_.data(), path_.size(), size_.width(), data_.color);
  420. }
  421. }
  422. private:
  423. const IconDescription data_;
  424. const std::vector<PathElement> path_;
  425. };
  426. // This class caches vector icons (as ImageSkia) so they don't have to be drawn
  427. // more than once. This also guarantees the backing data for the images returned
  428. // by CreateVectorIcon will persist in memory until program termination.
  429. class VectorIconCache {
  430. public:
  431. VectorIconCache() {}
  432. VectorIconCache(const VectorIconCache&) = delete;
  433. VectorIconCache& operator=(const VectorIconCache&) = delete;
  434. ~VectorIconCache() {}
  435. ImageSkia GetOrCreateIcon(const IconDescription& description) {
  436. auto iter = images_.find(description);
  437. if (iter != images_.end())
  438. return iter->second;
  439. ImageSkia icon_image(std::make_unique<VectorIconSource>(description),
  440. Size(description.dip_size, description.dip_size));
  441. images_.emplace(description, icon_image);
  442. return icon_image;
  443. }
  444. private:
  445. std::map<IconDescription, ImageSkia, CompareIconDescription> images_;
  446. };
  447. static base::LazyInstance<VectorIconCache>::DestructorAtExit g_icon_cache =
  448. LAZY_INSTANCE_INITIALIZER;
  449. } // namespace
  450. IconDescription::IconDescription(const IconDescription& other) = default;
  451. IconDescription::IconDescription(const VectorIcon& icon,
  452. int dip_size,
  453. SkColor color,
  454. const VectorIcon* badge_icon)
  455. : icon(icon),
  456. dip_size(dip_size),
  457. color(color),
  458. badge_icon(badge_icon ? *badge_icon : kNoneIcon) {
  459. if (dip_size == 0)
  460. this->dip_size = GetDefaultSizeOfVectorIcon(icon);
  461. }
  462. IconDescription::~IconDescription() {}
  463. const VectorIcon kNoneIcon = {};
  464. void PaintVectorIcon(Canvas* canvas, const VectorIcon& icon, SkColor color) {
  465. PaintVectorIcon(canvas, icon, GetDefaultSizeOfVectorIcon(icon), color);
  466. }
  467. void PaintVectorIcon(Canvas* canvas,
  468. const VectorIcon& icon,
  469. int dip_size,
  470. SkColor color) {
  471. DCHECK(!icon.is_empty());
  472. for (size_t i = 0; i < icon.reps_size; ++i)
  473. DCHECK(icon.reps[i].path_size > 0);
  474. const int px_size = base::ClampCeil(canvas->image_scale() * dip_size);
  475. const VectorIconRep* rep = GetRepForPxSize(icon, px_size);
  476. PaintPath(canvas, rep->path, rep->path_size, dip_size, color);
  477. }
  478. ImageSkia CreateVectorIcon(const IconDescription& params) {
  479. if (params.icon.is_empty())
  480. return ImageSkia();
  481. return g_icon_cache.Get().GetOrCreateIcon(params);
  482. }
  483. ImageSkia CreateVectorIcon(const VectorIcon& icon, SkColor color) {
  484. return CreateVectorIcon(icon, GetDefaultSizeOfVectorIcon(icon), color);
  485. }
  486. ImageSkia CreateVectorIcon(const VectorIcon& icon,
  487. int dip_size,
  488. SkColor color) {
  489. return CreateVectorIcon(IconDescription(icon, dip_size, color, &kNoneIcon));
  490. }
  491. ImageSkia CreateVectorIconWithBadge(const VectorIcon& icon,
  492. int dip_size,
  493. SkColor color,
  494. const VectorIcon& badge_icon) {
  495. return CreateVectorIcon(IconDescription(icon, dip_size, color, &badge_icon));
  496. }
  497. ImageSkia CreateVectorIconFromSource(const std::string& source,
  498. int dip_size,
  499. SkColor color) {
  500. return CanvasImageSource::MakeImageSkia<VectorIconSource>(source, dip_size,
  501. color);
  502. }
  503. } // namespace gfx