• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "tools/ToolUtils.h"
9 
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkBlendMode.h"
12 #include "include/core/SkCanvas.h"
13 #include "include/core/SkColorPriv.h"
14 #include "include/core/SkColorSpace.h"
15 #include "include/core/SkImage.h"
16 #include "include/core/SkMatrix.h"
17 #include "include/core/SkPaint.h"
18 #include "include/core/SkPathBuilder.h"
19 #include "include/core/SkPicture.h"
20 #include "include/core/SkPixelRef.h"
21 #include "include/core/SkPixmap.h"
22 #include "include/core/SkPoint3.h"
23 #include "include/core/SkRRect.h"
24 #include "include/core/SkShader.h"
25 #include "include/core/SkSurface.h"
26 #include "include/core/SkTextBlob.h"
27 #include "include/private/SkColorData.h"
28 #include "include/private/base/SkFloatingPoint.h"
29 #include "src/core/SkFontPriv.h"
30 
31 #include <cmath>
32 #include <cstring>
33 
34 #if defined(SK_GRAPHITE)
35 #include "include/gpu/graphite/ImageProvider.h"
36 #include <unordered_map>
37 #endif
38 
39 #if defined(SK_ENABLE_SVG)
40 #include "modules/svg/include/SkSVGDOM.h"
41 #include "modules/svg/include/SkSVGNode.h"
42 #include "src/xml/SkDOM.h"
43 #endif
44 
45 #if defined(SK_GANESH)
46 #include "include/gpu/GrDirectContext.h"
47 #include "include/gpu/GrRecordingContext.h"
48 #include "src/gpu/ganesh/GrCaps.h"
49 #include "src/gpu/ganesh/GrDirectContextPriv.h"
50 #endif
51 
52 #ifdef SK_BUILD_FOR_WIN
53 #include "include/ports/SkTypeface_win.h"
54 #endif
55 
56 using namespace skia_private;
57 
58 namespace ToolUtils {
59 
alphatype_name(SkAlphaType at)60 const char* alphatype_name(SkAlphaType at) {
61     switch (at) {
62         case kUnknown_SkAlphaType:  return "Unknown";
63         case kOpaque_SkAlphaType:   return "Opaque";
64         case kPremul_SkAlphaType:   return "Premul";
65         case kUnpremul_SkAlphaType: return "Unpremul";
66     }
67     SkUNREACHABLE;
68 }
69 
colortype_name(SkColorType ct)70 const char* colortype_name(SkColorType ct) {
71     switch (ct) {
72         case kUnknown_SkColorType:            return "Unknown";
73         case kAlpha_8_SkColorType:            return "Alpha_8";
74         case kA16_unorm_SkColorType:          return "Alpha_16";
75         case kA16_float_SkColorType:          return "A16_float";
76         case kRGB_565_SkColorType:            return "RGB_565";
77         case kARGB_4444_SkColorType:          return "ARGB_4444";
78         case kRGBA_8888_SkColorType:          return "RGBA_8888";
79         case kSRGBA_8888_SkColorType:         return "SRGBA_8888";
80         case kRGB_888x_SkColorType:           return "RGB_888x";
81         case kBGRA_8888_SkColorType:          return "BGRA_8888";
82         case kRGBA_1010102_SkColorType:       return "RGBA_1010102";
83         case kBGRA_1010102_SkColorType:       return "BGRA_1010102";
84         case kRGB_101010x_SkColorType:        return "RGB_101010x";
85         case kBGR_101010x_SkColorType:        return "BGR_101010x";
86         case kBGR_101010x_XR_SkColorType:     return "BGR_101010x_XR";
87         case kGray_8_SkColorType:             return "Gray_8";
88         case kRGBA_F16Norm_SkColorType:       return "RGBA_F16Norm";
89         case kRGBA_F16_SkColorType:           return "RGBA_F16";
90         case kRGBA_F32_SkColorType:           return "RGBA_F32";
91         case kR8G8_unorm_SkColorType:         return "R8G8_unorm";
92         case kR16G16_unorm_SkColorType:       return "R16G16_unorm";
93         case kR16G16_float_SkColorType:       return "R16G16_float";
94         case kR16G16B16A16_unorm_SkColorType: return "R16G16B16A16_unorm";
95         case kR8_unorm_SkColorType:           return "R8_unorm";
96     }
97     SkUNREACHABLE;
98 }
99 
colortype_depth(SkColorType ct)100 const char* colortype_depth(SkColorType ct) {
101     switch (ct) {
102         case kUnknown_SkColorType:            return "Unknown";
103         case kAlpha_8_SkColorType:            return "A8";
104         case kA16_unorm_SkColorType:          return "A16";
105         case kA16_float_SkColorType:          return "AF16";
106         case kRGB_565_SkColorType:            return "565";
107         case kARGB_4444_SkColorType:          return "4444";
108         case kRGBA_8888_SkColorType:          return "8888";
109         case kSRGBA_8888_SkColorType:         return "8888";
110         case kRGB_888x_SkColorType:           return "888";
111         case kBGRA_8888_SkColorType:          return "8888";
112         case kRGBA_1010102_SkColorType:       return "1010102";
113         case kBGRA_1010102_SkColorType:       return "1010102";
114         case kRGB_101010x_SkColorType:        return "101010";
115         case kBGR_101010x_SkColorType:        return "101010";
116         case kBGR_101010x_XR_SkColorType:     return "101010";
117         case kGray_8_SkColorType:             return "G8";
118         case kRGBA_F16Norm_SkColorType:       return "F16Norm";
119         case kRGBA_F16_SkColorType:           return "F16";
120         case kRGBA_F32_SkColorType:           return "F32";
121         case kR8G8_unorm_SkColorType:         return "88";
122         case kR16G16_unorm_SkColorType:       return "1616";
123         case kR16G16_float_SkColorType:       return "F16F16";
124         case kR16G16B16A16_unorm_SkColorType: return "16161616";
125         case kR8_unorm_SkColorType:           return "R8";
126     }
127     SkUNREACHABLE;
128 }
129 
tilemode_name(SkTileMode mode)130 const char* tilemode_name(SkTileMode mode) {
131     switch (mode) {
132         case SkTileMode::kClamp:  return "clamp";
133         case SkTileMode::kRepeat: return "repeat";
134         case SkTileMode::kMirror: return "mirror";
135         case SkTileMode::kDecal:  return "decal";
136     }
137     SkUNREACHABLE;
138 }
139 
color_to_565(SkColor color)140 SkColor color_to_565(SkColor color) {
141     // Not a good idea to use this function for greyscale colors...
142     // it will add an obvious purple or green tint.
143     SkASSERT(SkColorGetR(color) != SkColorGetG(color) || SkColorGetR(color) != SkColorGetB(color) ||
144              SkColorGetG(color) != SkColorGetB(color));
145 
146     SkPMColor pmColor = SkPreMultiplyColor(color);
147     U16CPU    color16 = SkPixel32ToPixel16(pmColor);
148     return SkPixel16ToColor(color16);
149 }
150 
create_checkerboard_shader(SkColor c1,SkColor c2,int size)151 sk_sp<SkShader> create_checkerboard_shader(SkColor c1, SkColor c2, int size) {
152     SkBitmap bm;
153     bm.allocPixels(SkImageInfo::MakeS32(2 * size, 2 * size, kPremul_SkAlphaType));
154     bm.eraseColor(c1);
155     bm.eraseArea(SkIRect::MakeLTRB(0, 0, size, size), c2);
156     bm.eraseArea(SkIRect::MakeLTRB(size, size, 2 * size, 2 * size), c2);
157     return bm.makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, SkSamplingOptions());
158 }
159 
create_checkerboard_bitmap(int w,int h,SkColor c1,SkColor c2,int checkSize)160 SkBitmap create_checkerboard_bitmap(int w, int h, SkColor c1, SkColor c2, int checkSize) {
161     SkBitmap bitmap;
162     bitmap.allocPixels(SkImageInfo::MakeS32(w, h, kPremul_SkAlphaType));
163     SkCanvas canvas(bitmap);
164 
165     ToolUtils::draw_checkerboard(&canvas, c1, c2, checkSize);
166     return bitmap;
167 }
168 
create_checkerboard_image(int w,int h,SkColor c1,SkColor c2,int checkSize)169 sk_sp<SkImage> create_checkerboard_image(int w, int h, SkColor c1, SkColor c2, int checkSize) {
170     auto surf = SkSurface::MakeRasterN32Premul(w, h);
171     ToolUtils::draw_checkerboard(surf->getCanvas(), c1, c2, checkSize);
172     return surf->makeImageSnapshot();
173 }
174 
draw_checkerboard(SkCanvas * canvas,SkColor c1,SkColor c2,int size)175 void draw_checkerboard(SkCanvas* canvas, SkColor c1, SkColor c2, int size) {
176     SkPaint paint;
177     paint.setShader(create_checkerboard_shader(c1, c2, size));
178     paint.setBlendMode(SkBlendMode::kSrc);
179     canvas->drawPaint(paint);
180 }
181 
make_pixmaps(SkColorType ct,SkAlphaType at,bool withMips,const SkColor4f colors[6],SkPixmap pixmaps[6],std::unique_ptr<char[]> * mem)182 int make_pixmaps(SkColorType ct,
183                  SkAlphaType at,
184                  bool withMips,
185                  const SkColor4f colors[6],
186                  SkPixmap pixmaps[6],
187                  std::unique_ptr<char[]>* mem) {
188 
189     int levelSize = 32;
190     int numMipLevels = withMips ? 6 : 1;
191     size_t size = 0;
192     SkImageInfo ii[6];
193     size_t rowBytes[6];
194     for (int level = 0; level < numMipLevels; ++level) {
195         ii[level] = SkImageInfo::Make(levelSize, levelSize, ct, at);
196         rowBytes[level] = ii[level].minRowBytes();
197         // Make sure we test row bytes that aren't tight.
198         if (!(level % 2)) {
199             rowBytes[level] += (level + 1)*SkColorTypeBytesPerPixel(ii[level].colorType());
200         }
201         size += rowBytes[level]*ii[level].height();
202         levelSize /= 2;
203     }
204     mem->reset(new char[size]);
205     char* addr = mem->get();
206     for (int level = 0; level < numMipLevels; ++level) {
207         pixmaps[level].reset(ii[level], addr, rowBytes[level]);
208         addr += rowBytes[level]*ii[level].height();
209         pixmaps[level].erase(colors[level]);
210     }
211     return numMipLevels;
212 }
213 
create_string_bitmap(int w,int h,SkColor c,int x,int y,int textSize,const char * str)214 SkBitmap create_string_bitmap(int w, int h, SkColor c, int x, int y, int textSize,
215                               const char* str) {
216     SkBitmap bitmap;
217     bitmap.allocN32Pixels(w, h);
218     SkCanvas canvas(bitmap);
219 
220     SkPaint paint;
221     paint.setColor(c);
222 
223     SkFont font(ToolUtils::create_portable_typeface(), textSize);
224 
225     canvas.clear(0x00000000);
226     canvas.drawSimpleText(str,
227                           strlen(str),
228                           SkTextEncoding::kUTF8,
229                           SkIntToScalar(x),
230                           SkIntToScalar(y),
231                           font,
232                           paint);
233 
234     // Tag data as sRGB (without doing any color space conversion). Color-space aware configs
235     // will process this correctly but legacy configs will render as if this returned N32.
236     SkBitmap result;
237     result.setInfo(SkImageInfo::MakeS32(w, h, kPremul_SkAlphaType));
238     result.setPixelRef(sk_ref_sp(bitmap.pixelRef()), 0, 0);
239     return result;
240 }
241 
create_string_image(int w,int h,SkColor c,int x,int y,int textSize,const char * str)242 sk_sp<SkImage> create_string_image(int w, int h, SkColor c, int x, int y, int textSize,
243                                    const char* str) {
244     return create_string_bitmap(w, h, c, x, y, textSize, str).asImage();
245 }
246 
add_to_text_blob_w_len(SkTextBlobBuilder * builder,const char * text,size_t len,SkTextEncoding encoding,const SkFont & font,SkScalar x,SkScalar y)247 void add_to_text_blob_w_len(SkTextBlobBuilder* builder,
248                             const char*        text,
249                             size_t             len,
250                             SkTextEncoding     encoding,
251                             const SkFont&      font,
252                             SkScalar           x,
253                             SkScalar           y) {
254     int  count = font.countText(text, len, encoding);
255     if (count < 1) {
256         return;
257     }
258     auto run   = builder->allocRun(font, count, x, y);
259     font.textToGlyphs(text, len, encoding, run.glyphs, count);
260 }
261 
add_to_text_blob(SkTextBlobBuilder * builder,const char * text,const SkFont & font,SkScalar x,SkScalar y)262 void add_to_text_blob(SkTextBlobBuilder* builder,
263                       const char*        text,
264                       const SkFont&      font,
265                       SkScalar           x,
266                       SkScalar           y) {
267     add_to_text_blob_w_len(builder, text, strlen(text), SkTextEncoding::kUTF8, font, x, y);
268 }
269 
get_text_path(const SkFont & font,const void * text,size_t length,SkTextEncoding encoding,SkPath * dst,const SkPoint pos[])270 void get_text_path(const SkFont&  font,
271                    const void*    text,
272                    size_t         length,
273                    SkTextEncoding encoding,
274                    SkPath*        dst,
275                    const SkPoint  pos[]) {
276     SkAutoToGlyphs        atg(font, text, length, encoding);
277     const int             count = atg.count();
278     AutoTArray<SkPoint> computedPos;
279     if (pos == nullptr) {
280         computedPos.reset(count);
281         font.getPos(atg.glyphs(), count, &computedPos[0]);
282         pos = computedPos.get();
283     }
284 
285     struct Rec {
286         SkPath*        fDst;
287         const SkPoint* fPos;
288     } rec = {dst, pos};
289     font.getPaths(atg.glyphs(),
290                   atg.count(),
291                   [](const SkPath* src, const SkMatrix& mx, void* ctx) {
292                       Rec* rec = (Rec*)ctx;
293                       if (src) {
294                           SkMatrix tmp(mx);
295                           tmp.postTranslate(rec->fPos->fX, rec->fPos->fY);
296                           rec->fDst->addPath(*src, tmp);
297                       }
298                       rec->fPos += 1;
299                   },
300                   &rec);
301 }
302 
make_star(const SkRect & bounds,int numPts,int step)303 SkPath make_star(const SkRect& bounds, int numPts, int step) {
304     SkASSERT(numPts != step);
305     SkPathBuilder builder;
306     builder.setFillType(SkPathFillType::kEvenOdd);
307     builder.moveTo(0, -1);
308     for (int i = 1; i < numPts; ++i) {
309         int      idx   = i * step % numPts;
310         SkScalar theta = idx * 2 * SK_ScalarPI / numPts + SK_ScalarPI / 2;
311         SkScalar x     = SkScalarCos(theta);
312         SkScalar y     = -SkScalarSin(theta);
313         builder.lineTo(x, y);
314     }
315     SkPath path = builder.detach();
316     path.transform(SkMatrix::RectToRect(path.getBounds(), bounds));
317     return path;
318 }
319 
norm_to_rgb(SkBitmap * bm,int x,int y,const SkVector3 & norm)320 static inline void norm_to_rgb(SkBitmap* bm, int x, int y, const SkVector3& norm) {
321     SkASSERT(SkScalarNearlyEqual(norm.length(), 1.0f));
322     unsigned char r      = static_cast<unsigned char>((0.5f * norm.fX + 0.5f) * 255);
323     unsigned char g      = static_cast<unsigned char>((-0.5f * norm.fY + 0.5f) * 255);
324     unsigned char b      = static_cast<unsigned char>((0.5f * norm.fZ + 0.5f) * 255);
325     *bm->getAddr32(x, y) = SkPackARGB32(0xFF, r, g, b);
326 }
327 
create_hemi_normal_map(SkBitmap * bm,const SkIRect & dst)328 void create_hemi_normal_map(SkBitmap* bm, const SkIRect& dst) {
329     const SkPoint center =
330             SkPoint::Make(dst.fLeft + (dst.width() / 2.0f), dst.fTop + (dst.height() / 2.0f));
331     const SkPoint halfSize = SkPoint::Make(dst.width() / 2.0f, dst.height() / 2.0f);
332 
333     SkVector3 norm;
334 
335     for (int y = dst.fTop; y < dst.fBottom; ++y) {
336         for (int x = dst.fLeft; x < dst.fRight; ++x) {
337             norm.fX = (x + 0.5f - center.fX) / halfSize.fX;
338             norm.fY = (y + 0.5f - center.fY) / halfSize.fY;
339 
340             SkScalar tmp = norm.fX * norm.fX + norm.fY * norm.fY;
341             if (tmp >= 1.0f) {
342                 norm.set(0.0f, 0.0f, 1.0f);
343             } else {
344                 norm.fZ = sqrtf(1.0f - tmp);
345             }
346 
347             norm_to_rgb(bm, x, y, norm);
348         }
349     }
350 }
351 
create_frustum_normal_map(SkBitmap * bm,const SkIRect & dst)352 void create_frustum_normal_map(SkBitmap* bm, const SkIRect& dst) {
353     const SkPoint center =
354             SkPoint::Make(dst.fLeft + (dst.width() / 2.0f), dst.fTop + (dst.height() / 2.0f));
355 
356     SkIRect inner = dst;
357     inner.inset(dst.width() / 4, dst.height() / 4);
358 
359     SkPoint3       norm;
360     const SkPoint3 left  = SkPoint3::Make(-SK_ScalarRoot2Over2, 0.0f, SK_ScalarRoot2Over2);
361     const SkPoint3 up    = SkPoint3::Make(0.0f, -SK_ScalarRoot2Over2, SK_ScalarRoot2Over2);
362     const SkPoint3 right = SkPoint3::Make(SK_ScalarRoot2Over2, 0.0f, SK_ScalarRoot2Over2);
363     const SkPoint3 down  = SkPoint3::Make(0.0f, SK_ScalarRoot2Over2, SK_ScalarRoot2Over2);
364 
365     for (int y = dst.fTop; y < dst.fBottom; ++y) {
366         for (int x = dst.fLeft; x < dst.fRight; ++x) {
367             if (inner.contains(x, y)) {
368                 norm.set(0.0f, 0.0f, 1.0f);
369             } else {
370                 SkScalar locX = x + 0.5f - center.fX;
371                 SkScalar locY = y + 0.5f - center.fY;
372 
373                 if (locX >= 0.0f) {
374                     if (locY > 0.0f) {
375                         norm = locX >= locY ? right : down;  // LR corner
376                     } else {
377                         norm = locX > -locY ? right : up;  // UR corner
378                     }
379                 } else {
380                     if (locY > 0.0f) {
381                         norm = -locX > locY ? left : down;  // LL corner
382                     } else {
383                         norm = locX > locY ? up : left;  // UL corner
384                     }
385                 }
386             }
387 
388             norm_to_rgb(bm, x, y, norm);
389         }
390     }
391 }
392 
create_tetra_normal_map(SkBitmap * bm,const SkIRect & dst)393 void create_tetra_normal_map(SkBitmap* bm, const SkIRect& dst) {
394     const SkPoint center =
395             SkPoint::Make(dst.fLeft + (dst.width() / 2.0f), dst.fTop + (dst.height() / 2.0f));
396 
397     static const SkScalar k1OverRoot3 = 0.5773502692f;
398 
399     SkPoint3       norm;
400     const SkPoint3 leftUp  = SkPoint3::Make(-k1OverRoot3, -k1OverRoot3, k1OverRoot3);
401     const SkPoint3 rightUp = SkPoint3::Make(k1OverRoot3, -k1OverRoot3, k1OverRoot3);
402     const SkPoint3 down    = SkPoint3::Make(0.0f, SK_ScalarRoot2Over2, SK_ScalarRoot2Over2);
403 
404     for (int y = dst.fTop; y < dst.fBottom; ++y) {
405         for (int x = dst.fLeft; x < dst.fRight; ++x) {
406             SkScalar locX = x + 0.5f - center.fX;
407             SkScalar locY = y + 0.5f - center.fY;
408 
409             if (locX >= 0.0f) {
410                 if (locY > 0.0f) {
411                     norm = locX >= locY ? rightUp : down;  // LR corner
412                 } else {
413                     norm = rightUp;
414                 }
415             } else {
416                 if (locY > 0.0f) {
417                     norm = -locX > locY ? leftUp : down;  // LL corner
418                 } else {
419                     norm = leftUp;
420                 }
421             }
422 
423             norm_to_rgb(bm, x, y, norm);
424         }
425     }
426 }
427 
copy_to(SkBitmap * dst,SkColorType dstColorType,const SkBitmap & src)428 bool copy_to(SkBitmap* dst, SkColorType dstColorType, const SkBitmap& src) {
429     SkPixmap srcPM;
430     if (!src.peekPixels(&srcPM)) {
431         return false;
432     }
433 
434     SkBitmap    tmpDst;
435     SkImageInfo dstInfo = srcPM.info().makeColorType(dstColorType);
436     if (!tmpDst.setInfo(dstInfo)) {
437         return false;
438     }
439 
440     if (!tmpDst.tryAllocPixels()) {
441         return false;
442     }
443 
444     SkPixmap dstPM;
445     if (!tmpDst.peekPixels(&dstPM)) {
446         return false;
447     }
448 
449     if (!srcPM.readPixels(dstPM)) {
450         return false;
451     }
452 
453     dst->swap(tmpDst);
454     return true;
455 }
456 
copy_to_g8(SkBitmap * dst,const SkBitmap & src)457 void copy_to_g8(SkBitmap* dst, const SkBitmap& src) {
458     SkASSERT(kBGRA_8888_SkColorType == src.colorType() ||
459              kRGBA_8888_SkColorType == src.colorType());
460 
461     SkImageInfo grayInfo = src.info().makeColorType(kGray_8_SkColorType);
462     dst->allocPixels(grayInfo);
463     uint8_t*        dst8  = (uint8_t*)dst->getPixels();
464     const uint32_t* src32 = (const uint32_t*)src.getPixels();
465 
466     const int  w      = src.width();
467     const int  h      = src.height();
468     const bool isBGRA = (kBGRA_8888_SkColorType == src.colorType());
469     for (int y = 0; y < h; ++y) {
470         if (isBGRA) {
471             // BGRA
472             for (int x = 0; x < w; ++x) {
473                 uint32_t s = src32[x];
474                 dst8[x]    = SkComputeLuminance((s >> 16) & 0xFF, (s >> 8) & 0xFF, s & 0xFF);
475             }
476         } else {
477             // RGBA
478             for (int x = 0; x < w; ++x) {
479                 uint32_t s = src32[x];
480                 dst8[x]    = SkComputeLuminance(s & 0xFF, (s >> 8) & 0xFF, (s >> 16) & 0xFF);
481             }
482         }
483         src32 = (const uint32_t*)((const char*)src32 + src.rowBytes());
484         dst8 += dst->rowBytes();
485     }
486 }
487 
488 //////////////////////////////////////////////////////////////////////////////////////////////
489 
equal_pixels(const SkPixmap & a,const SkPixmap & b)490 bool equal_pixels(const SkPixmap& a, const SkPixmap& b) {
491     if (a.width() != b.width() || a.height() != b.height() || a.colorType() != b.colorType()) {
492         return false;
493     }
494 
495     for (int y = 0; y < a.height(); ++y) {
496         const char* aptr = (const char*)a.addr(0, y);
497         const char* bptr = (const char*)b.addr(0, y);
498         if (0 != memcmp(aptr, bptr, a.width() * a.info().bytesPerPixel())) {
499             return false;
500         }
501     }
502     return true;
503 }
504 
equal_pixels(const SkBitmap & bm0,const SkBitmap & bm1)505 bool equal_pixels(const SkBitmap& bm0, const SkBitmap& bm1) {
506     SkPixmap pm0, pm1;
507     return bm0.peekPixels(&pm0) && bm1.peekPixels(&pm1) && equal_pixels(pm0, pm1);
508 }
509 
equal_pixels(const SkImage * a,const SkImage * b)510 bool equal_pixels(const SkImage* a, const SkImage* b) {
511     // ensure that peekPixels will succeed
512     auto imga = a->makeRasterImage();
513     auto imgb = b->makeRasterImage();
514 
515     SkPixmap pm0, pm1;
516     return imga->peekPixels(&pm0) && imgb->peekPixels(&pm1) && equal_pixels(pm0, pm1);
517 }
518 
makeSurface(SkCanvas * canvas,const SkImageInfo & info,const SkSurfaceProps * props)519 sk_sp<SkSurface> makeSurface(SkCanvas*             canvas,
520                              const SkImageInfo&    info,
521                              const SkSurfaceProps* props) {
522     auto surf = canvas->makeSurface(info, props);
523     if (!surf) {
524         surf = SkSurface::MakeRaster(info, props);
525     }
526     return surf;
527 }
528 
sniff_paths(const char filepath[],std::function<PathSniffCallback> callback)529 void sniff_paths(const char filepath[], std::function<PathSniffCallback> callback) {
530     SkFILEStream stream(filepath);
531     if (!stream.isValid()) {
532         SkDebugf("sniff_paths: invalid input file at \"%s\"\n", filepath);
533         return;
534     }
535 
536     class PathSniffer : public SkCanvas {
537     public:
538         PathSniffer(std::function<PathSniffCallback> callback)
539                 : SkCanvas(4096, 4096, nullptr)
540                 , fPathSniffCallback(callback) {}
541     private:
542         void onDrawPath(const SkPath& path, const SkPaint& paint) override {
543             fPathSniffCallback(this->getTotalMatrix(), path, paint);
544         }
545         std::function<PathSniffCallback> fPathSniffCallback;
546     };
547 
548     PathSniffer pathSniffer(callback);
549     if (const char* ext = strrchr(filepath, '.'); ext && !strcmp(ext, ".svg")) {
550 #if defined(SK_ENABLE_SVG)
551         sk_sp<SkSVGDOM> svg = SkSVGDOM::MakeFromStream(stream);
552         if (!svg) {
553             SkDebugf("sniff_paths: couldn't load svg at \"%s\"\n", filepath);
554             return;
555         }
556         svg->setContainerSize(SkSize::Make(pathSniffer.getBaseLayerSize()));
557         svg->render(&pathSniffer);
558 #endif
559     } else {
560         sk_sp<SkPicture> skp = SkPicture::MakeFromStream(&stream);
561         if (!skp) {
562             SkDebugf("sniff_paths: couldn't load skp at \"%s\"\n", filepath);
563             return;
564         }
565         skp->playback(&pathSniffer);
566     }
567 }
568 
569 #if defined(SK_GANESH)
MakeTextureImage(SkCanvas * canvas,sk_sp<SkImage> orig)570 sk_sp<SkImage> MakeTextureImage(SkCanvas* canvas, sk_sp<SkImage> orig) {
571     if (!orig) {
572         return nullptr;
573     }
574 
575     if (canvas->recordingContext() && canvas->recordingContext()->asDirectContext()) {
576         GrDirectContext* dContext = canvas->recordingContext()->asDirectContext();
577         const GrCaps* caps = dContext->priv().caps();
578 
579         if (orig->width() >= caps->maxTextureSize() || orig->height() >= caps->maxTextureSize()) {
580             // Ganesh is able to tile large SkImage draws. Always forcing SkImages to be uploaded
581             // prevents this feature from being tested by our tools. For now, leave excessively
582             // large SkImages as bitmaps.
583             return orig;
584         }
585 
586         return orig->makeTextureImage(dContext);
587     }
588 #if defined(SK_GRAPHITE)
589     else if (canvas->recorder()) {
590         return orig->makeTextureImage(canvas->recorder());
591     }
592 #endif
593 
594     return orig;
595 }
596 #endif
597 
VariationSliders(SkTypeface * typeface,SkFontArguments::VariationPosition variationPosition)598 VariationSliders::VariationSliders(SkTypeface* typeface,
599                                    SkFontArguments::VariationPosition variationPosition) {
600     if (!typeface) {
601         return;
602     }
603 
604     int numAxes = typeface->getVariationDesignParameters(nullptr, 0);
605     if (numAxes < 0) {
606         return;
607     }
608 
609     std::unique_ptr<SkFontParameters::Variation::Axis[]> copiedAxes =
610             std::make_unique<SkFontParameters::Variation::Axis[]>(numAxes);
611 
612     numAxes = typeface->getVariationDesignParameters(copiedAxes.get(), numAxes);
613     if (numAxes < 0) {
614         return;
615     }
616 
617     auto argVariationPositionOrDefault = [&variationPosition](SkFourByteTag tag,
618                                                               SkScalar defaultValue) -> SkScalar {
619         for (int i = 0; i < variationPosition.coordinateCount; ++i) {
620             if (variationPosition.coordinates[i].axis == tag) {
621                 return variationPosition.coordinates[i].value;
622             }
623         }
624         return defaultValue;
625     };
626 
627     fAxisSliders.resize(numAxes);
628     fCoords = std::make_unique<SkFontArguments::VariationPosition::Coordinate[]>(numAxes);
629     for (int i = 0; i < numAxes; ++i) {
630         fAxisSliders[i].axis = copiedAxes[i];
631         fAxisSliders[i].current =
632                 argVariationPositionOrDefault(copiedAxes[i].tag, copiedAxes[i].def);
633         fAxisSliders[i].name = tagToString(fAxisSliders[i].axis.tag);
634         fCoords[i] = { fAxisSliders[i].axis.tag, fAxisSliders[i].current };
635     }
636 }
637 
638 /* static */
tagToString(SkFourByteTag tag)639 SkString VariationSliders::tagToString(SkFourByteTag tag) {
640     char tagAsString[5];
641     tagAsString[4] = 0;
642     tagAsString[0] = (char)(uint8_t)(tag >> 24);
643     tagAsString[1] = (char)(uint8_t)(tag >> 16);
644     tagAsString[2] = (char)(uint8_t)(tag >> 8);
645     tagAsString[3] = (char)(uint8_t)(tag >> 0);
646     return SkString(tagAsString);
647 }
648 
writeControls(SkMetaData * controls)649 bool VariationSliders::writeControls(SkMetaData* controls) {
650     for (size_t i = 0; i < fAxisSliders.size(); ++i) {
651         SkScalar axisVars[kAxisVarsSize];
652 
653         axisVars[0] = fAxisSliders[i].current;
654         axisVars[1] = fAxisSliders[i].axis.min;
655         axisVars[2] = fAxisSliders[i].axis.max;
656         controls->setScalars(fAxisSliders[i].name.c_str(), kAxisVarsSize, axisVars);
657     }
658     return true;
659 }
660 
readControls(const SkMetaData & controls,bool * changed)661 void VariationSliders::readControls(const SkMetaData& controls, bool* changed) {
662     for (size_t i = 0; i < fAxisSliders.size(); ++i) {
663         SkScalar axisVars[kAxisVarsSize] = {0};
664         int resultAxisVarsSize = 0;
665         SkASSERT_RELEASE(controls.findScalars(
666                 tagToString(fAxisSliders[i].axis.tag).c_str(), &resultAxisVarsSize, axisVars));
667         SkASSERT_RELEASE(resultAxisVarsSize == kAxisVarsSize);
668         if (changed) {
669             *changed |= fAxisSliders[i].current != axisVars[0];
670         }
671         fAxisSliders[i].current = axisVars[0];
672         fCoords[i] = { fAxisSliders[i].axis.tag, fAxisSliders[i].current };
673     }
674 }
675 
getCoordinates()676 SkSpan<const SkFontArguments::VariationPosition::Coordinate> VariationSliders::getCoordinates() {
677     return SkSpan<const SkFontArguments::VariationPosition::Coordinate>{fCoords.get(),
678                                                                         fAxisSliders.size()};
679 }
680 
681 #if defined(SK_GRAPHITE)
682 
683 // Currently, we give each new Recorder its own ImageProvider. This means we don't have to deal
684 // w/ any threading issues.
685 // TODO: We should probably have this class generate and report some cache stats
686 // TODO: Hook up to listener system?
687 // TODO: add testing of a single ImageProvider passed to multiple recorders
688 class TestingImageProvider : public skgpu::graphite::ImageProvider {
689 public:
~TestingImageProvider()690     ~TestingImageProvider() override {}
691 
findOrCreate(skgpu::graphite::Recorder * recorder,const SkImage * image,SkImage::RequiredImageProperties requiredProps)692     sk_sp<SkImage> findOrCreate(skgpu::graphite::Recorder* recorder,
693                                 const SkImage* image,
694                                 SkImage::RequiredImageProperties requiredProps) override {
695         if (requiredProps.fMipmapped == skgpu::Mipmapped::kNo) {
696             // If no mipmaps are required, check to see if we have a mipmapped version anyway -
697             // since it can be used in that case.
698             // TODO: we could get fancy and, if ever a mipmapped key eclipsed a non-mipmapped
699             // key, we could remove the hidden non-mipmapped key/image from the cache.
700             uint64_t mipMappedKey = ((uint64_t)image->uniqueID() << 32) | 0x1;
701             auto result = fCache.find(mipMappedKey);
702             if (result != fCache.end()) {
703                 return result->second;
704             }
705         }
706 
707         uint64_t key = ((uint64_t)image->uniqueID() << 32) |
708                        (requiredProps.fMipmapped == skgpu::Mipmapped::kYes ? 0x1 : 0x0);
709 
710         auto result = fCache.find(key);
711         if (result != fCache.end()) {
712             return result->second;
713         }
714 
715         sk_sp<SkImage> newImage = image->makeTextureImage(recorder, requiredProps);
716         if (!newImage) {
717             return nullptr;
718         }
719 
720         auto [iter, success] = fCache.insert({ key, newImage });
721         SkASSERT(success);
722 
723         return iter->second;
724     }
725 
726 private:
727     std::unordered_map<uint64_t, sk_sp<SkImage>> fCache;
728 };
729 
CreateTestingRecorderOptions()730 skgpu::graphite::RecorderOptions CreateTestingRecorderOptions() {
731     skgpu::graphite::RecorderOptions options;
732 
733     options.fImageProvider.reset(new TestingImageProvider);
734 
735     return options;
736 }
737 
738 #endif // SK_GRAPHITE
739 
740 }  // namespace ToolUtils
741