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 #ifndef ToolUtils_DEFINED
9 #define ToolUtils_DEFINED
10
11 #include "include/core/SkColor.h"
12 #include "include/core/SkData.h"
13 #include "include/core/SkEncodedImageFormat.h"
14 #include "include/core/SkFont.h"
15 #include "include/core/SkFontStyle.h"
16 #include "include/core/SkFontTypes.h"
17 #include "include/core/SkImageEncoder.h"
18 #include "include/core/SkImageInfo.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkRect.h"
21 #include "include/core/SkRefCnt.h"
22 #include "include/core/SkScalar.h"
23 #include "include/core/SkSpan.h"
24 #include "include/core/SkStream.h"
25 #include "include/core/SkSurface.h"
26 #include "include/core/SkTypeface.h"
27 #include "include/core/SkTypes.h"
28 #include "include/private/base/SkTArray.h"
29 #include "include/private/base/SkTDArray.h"
30 #include "src/base/SkRandom.h"
31 #include "src/base/SkTInternalLList.h"
32 #include "tools/SkMetaData.h"
33
34 #if defined(SK_GRAPHITE)
35 #include "include/gpu/graphite/Recorder.h"
36 #endif
37
38 class SkBitmap;
39 class SkCanvas;
40 class SkFontStyle;
41 class SkImage;
42 class SkPath;
43 class SkPixmap;
44 class SkRRect;
45 class SkShader;
46 class SkSurface;
47 class SkSurfaceProps;
48 class SkTextBlobBuilder;
49 class SkTypeface;
50
51 namespace ToolUtils {
52
53 const char* alphatype_name (SkAlphaType);
54 const char* colortype_name (SkColorType);
55 const char* colortype_depth(SkColorType); // like colortype_name, but channel order agnostic
56 const char* tilemode_name(SkTileMode);
57
58 /**
59 * Map opaque colors from 8888 to 565.
60 */
61 SkColor color_to_565(SkColor color);
62
63 /* Return a color emoji typeface with planets to scale if available. */
64 sk_sp<SkTypeface> planet_typeface();
65
66 /** Return a color emoji typeface if available. */
67 sk_sp<SkTypeface> emoji_typeface();
68
69 /** Sample text for the emoji_typeface font. */
emoji_sample_text()70 constexpr const char* emoji_sample_text() {
71 return "\xF0\x9F\x98\x80"
72 " "
73 "\xE2\x99\xA2"; // ♢
74 }
75
76 /** A simple SkUserTypeface for testing. */
77 sk_sp<SkTypeface> sample_user_typeface();
78
79 /**
80 * Returns a platform-independent text renderer.
81 */
82 sk_sp<SkTypeface> create_portable_typeface(const char* name, SkFontStyle style);
83
create_portable_typeface()84 static inline sk_sp<SkTypeface> create_portable_typeface() {
85 return create_portable_typeface(nullptr, SkFontStyle());
86 }
87
88 void get_text_path(const SkFont&,
89 const void* text,
90 size_t length,
91 SkTextEncoding,
92 SkPath*,
93 const SkPoint* positions = nullptr);
94
95 /**
96 * Returns true iff all of the pixels between the two images are identical.
97 *
98 * If the configs differ, return false.
99 */
100 bool equal_pixels(const SkPixmap&, const SkPixmap&);
101 bool equal_pixels(const SkBitmap&, const SkBitmap&);
102 bool equal_pixels(const SkImage* a, const SkImage* b);
103
104 /** Returns a newly created CheckerboardShader. */
105 sk_sp<SkShader> create_checkerboard_shader(SkColor c1, SkColor c2, int size);
106
107 /** Draw a checkerboard pattern in the current canvas, restricted to
108 the current clip, using SkXfermode::kSrc_Mode. */
109 void draw_checkerboard(SkCanvas* canvas, SkColor color1, SkColor color2, int checkSize);
110
111 /** Make it easier to create a bitmap-based checkerboard */
112 SkBitmap create_checkerboard_bitmap(int w, int h, SkColor c1, SkColor c2, int checkSize);
113
114 sk_sp<SkImage> create_checkerboard_image(int w, int h, SkColor c1, SkColor c2, int checkSize);
115
116 /** A default checkerboard. */
draw_checkerboard(SkCanvas * canvas)117 inline void draw_checkerboard(SkCanvas* canvas) {
118 ToolUtils::draw_checkerboard(canvas, 0xFF999999, 0xFF666666, 8);
119 }
120
121 /** Create pixmaps to initialize a 32x32 image w/ or w/o mipmaps.
122 * Returns the number of levels (either 1 or 6). The mipmap levels will be colored as
123 * specified in 'colors'
124 */
125 int make_pixmaps(SkColorType,
126 SkAlphaType,
127 bool withMips,
128 const SkColor4f colors[6],
129 SkPixmap pixmaps[6],
130 std::unique_ptr<char[]>* mem);
131
132 SkBitmap create_string_bitmap(int w, int h, SkColor c, int x, int y, int textSize, const char* str);
133 sk_sp<SkImage> create_string_image(int w, int h, SkColor c, int x, int y, int textSize, const char* str);
134
135 // If the canvas doesn't make a surface (e.g. recording), make a raster surface
136 sk_sp<SkSurface> makeSurface(SkCanvas*, const SkImageInfo&, const SkSurfaceProps* = nullptr);
137
138 // A helper for inserting a drawtext call into a SkTextBlobBuilder
139 void add_to_text_blob_w_len(SkTextBlobBuilder*,
140 const char* text,
141 size_t len,
142 SkTextEncoding,
143 const SkFont&,
144 SkScalar x,
145 SkScalar y);
146
147 void add_to_text_blob(SkTextBlobBuilder*, const char* text, const SkFont&, SkScalar x, SkScalar y);
148
149 // Constructs a star by walking a 'numPts'-sided regular polygon with even/odd fill:
150 //
151 // moveTo(pts[0]);
152 // lineTo(pts[step % numPts]);
153 // ...
154 // lineTo(pts[(step * (N - 1)) % numPts]);
155 //
156 // numPts=5, step=2 will produce a classic five-point star.
157 //
158 // numPts and step must be co-prime.
159 SkPath make_star(const SkRect& bounds, int numPts = 5, int step = 2);
160
161 void create_hemi_normal_map(SkBitmap* bm, const SkIRect& dst);
162
163 void create_frustum_normal_map(SkBitmap* bm, const SkIRect& dst);
164
165 void create_tetra_normal_map(SkBitmap* bm, const SkIRect& dst);
166
167 // A helper object to test the topological sorting code (TopoSortBench.cpp & TopoSortTest.cpp)
168 class TopoTestNode : public SkRefCnt {
169 public:
TopoTestNode(int id)170 TopoTestNode(int id) : fID(id) {}
171
dependsOn(TopoTestNode * src)172 void dependsOn(TopoTestNode* src) { *fDependencies.append() = src; }
targets(uint32_t target)173 void targets(uint32_t target) { *fTargets.append() = target; }
174
id()175 int id() const { return fID; }
reset()176 void reset() {
177 fOutputPos = 0;
178 fTempMark = false;
179 fWasOutput = false;
180 }
181
outputPos()182 uint32_t outputPos() const {
183 SkASSERT(fWasOutput);
184 return fOutputPos;
185 }
186
187 // check that the topological sort is valid for this node
check()188 bool check() {
189 if (!fWasOutput) {
190 return false;
191 }
192
193 for (int i = 0; i < fDependencies.size(); ++i) {
194 if (!fDependencies[i]->fWasOutput) {
195 return false;
196 }
197 // This node should've been output after all the nodes on which it depends
198 if (fOutputPos < fDependencies[i]->outputPos()) {
199 return false;
200 }
201 }
202
203 return true;
204 }
205
206 // The following 7 methods are needed by the topological sort
SetTempMark(TopoTestNode * node)207 static void SetTempMark(TopoTestNode* node) { node->fTempMark = true; }
ResetTempMark(TopoTestNode * node)208 static void ResetTempMark(TopoTestNode* node) { node->fTempMark = false; }
IsTempMarked(TopoTestNode * node)209 static bool IsTempMarked(TopoTestNode* node) { return node->fTempMark; }
Output(TopoTestNode * node,uint32_t outputPos)210 static void Output(TopoTestNode* node, uint32_t outputPos) {
211 SkASSERT(!node->fWasOutput);
212 node->fOutputPos = outputPos;
213 node->fWasOutput = true;
214 }
WasOutput(TopoTestNode * node)215 static bool WasOutput(TopoTestNode* node) { return node->fWasOutput; }
GetIndex(TopoTestNode * node)216 static uint32_t GetIndex(TopoTestNode* node) { return node->outputPos(); }
NumDependencies(TopoTestNode * node)217 static int NumDependencies(TopoTestNode* node) { return node->fDependencies.size(); }
Dependency(TopoTestNode * node,int index)218 static TopoTestNode* Dependency(TopoTestNode* node, int index) {
219 return node->fDependencies[index];
220 }
NumTargets(TopoTestNode * node)221 static int NumTargets(TopoTestNode* node) { return node->fTargets.size(); }
GetTarget(TopoTestNode * node,int i)222 static uint32_t GetTarget(TopoTestNode* node, int i) { return node->fTargets[i]; }
GetID(TopoTestNode * node)223 static uint32_t GetID(TopoTestNode* node) { return node->id(); }
224
225 // Helper functions for TopoSortBench & TopoSortTest
AllocNodes(SkTArray<sk_sp<ToolUtils::TopoTestNode>> * graph,int num)226 static void AllocNodes(SkTArray<sk_sp<ToolUtils::TopoTestNode>>* graph, int num) {
227 graph->reserve_back(num);
228
229 for (int i = 0; i < num; ++i) {
230 graph->push_back(sk_sp<TopoTestNode>(new TopoTestNode(i)));
231 }
232 }
233
234 #ifdef SK_DEBUG
Print(const SkTArray<TopoTestNode * > & graph)235 static void Print(const SkTArray<TopoTestNode*>& graph) {
236 for (int i = 0; i < graph.size(); ++i) {
237 SkDebugf("%d, ", graph[i]->id());
238 }
239 SkDebugf("\n");
240 }
241 #endif
242
243 // randomize the array
Shuffle(SkSpan<sk_sp<TopoTestNode>> graph,SkRandom * rand)244 static void Shuffle(SkSpan<sk_sp<TopoTestNode>> graph, SkRandom* rand) {
245 for (size_t i = graph.size() - 1; i > 0; --i) {
246 int swap = rand->nextU() % (i + 1);
247
248 graph[i].swap(graph[swap]);
249 }
250 }
251
252 SK_DECLARE_INTERNAL_LLIST_INTERFACE(TopoTestNode);
253
254 private:
255 int fID;
256 uint32_t fOutputPos = 0;
257 bool fTempMark = false;
258 bool fWasOutput = false;
259
260 SkTDArray<TopoTestNode*> fDependencies;
261 SkTDArray<uint32_t> fTargets;
262 };
263
264 template <typename T>
EncodeImageToFile(const char * path,const T & src,SkEncodedImageFormat f,int q)265 inline bool EncodeImageToFile(const char* path, const T& src, SkEncodedImageFormat f, int q) {
266 SkFILEWStream file(path);
267 return file.isValid() && SkEncodeImage(&file, src, f, q);
268 }
269
270 bool copy_to(SkBitmap* dst, SkColorType dstCT, const SkBitmap& src);
271 void copy_to_g8(SkBitmap* dst, const SkBitmap& src);
272
273 class PixelIter {
274 public:
275 PixelIter();
PixelIter(SkSurface * surf)276 PixelIter(SkSurface* surf) {
277 SkPixmap pm;
278 if (!surf->peekPixels(&pm)) {
279 pm.reset();
280 }
281 this->reset(pm);
282 }
283
reset(const SkPixmap & pm)284 void reset(const SkPixmap& pm) {
285 fPM = pm;
286 fLoc = {-1, 0};
287 }
288
289 void* next(SkIPoint* loc = nullptr) {
290 if (!fPM.addr()) {
291 return nullptr;
292 }
293 fLoc.fX += 1;
294 if (fLoc.fX >= fPM.width()) {
295 fLoc.fX = 0;
296 if (++fLoc.fY >= fPM.height()) {
297 this->setDone();
298 return nullptr;
299 }
300 }
301 if (loc) {
302 *loc = fLoc;
303 }
304 return fPM.writable_addr(fLoc.fX, fLoc.fY);
305 }
306
setDone()307 void setDone() { fPM.reset(); }
308
309 private:
310 SkPixmap fPM;
311 SkIPoint fLoc;
312 };
313
314 using PathSniffCallback = void(const SkMatrix&, const SkPath&, const SkPaint&);
315
316 // Calls the provided PathSniffCallback for each path in the given file.
317 // Supported file formats are .svg and .skp.
318 void sniff_paths(const char filepath[], std::function<PathSniffCallback>);
319
320 #if defined(SK_GANESH)
321 sk_sp<SkImage> MakeTextureImage(SkCanvas* canvas, sk_sp<SkImage> orig);
322 #endif
323
324 // Initialised with a font, this class can be called to setup GM UI with sliders for font
325 // variations, and returns a set of variation coordinates that matches what the sliders in the UI
326 // are set to. Useful for testing variable font properties, see colrv1.cpp.
327 class VariationSliders {
328 public:
VariationSliders()329 VariationSliders() {}
330
331 VariationSliders(SkTypeface*,
332 SkFontArguments::VariationPosition variationPosition = {nullptr, 0});
333
334 bool writeControls(SkMetaData* controls);
335
336 /* Scans controls for information about the variation axes that the user may have configured.
337 * Optionally pass in a boolean to receive information on whether the axes were updated. */
338 void readControls(const SkMetaData& controls, bool* changed = nullptr);
339
340 SkSpan<const SkFontArguments::VariationPosition::Coordinate> getCoordinates();
341
342 static SkString tagToString(SkFourByteTag tag);
343
344 private:
345 struct AxisSlider {
346 SkScalar current;
347 SkFontParameters::Variation::Axis axis;
348 SkString name;
349 };
350
351 std::vector<AxisSlider> fAxisSliders;
352 std::unique_ptr<SkFontArguments::VariationPosition::Coordinate[]> fCoords;
353 static constexpr size_t kAxisVarsSize = 3;
354 };
355
356 #if defined(SK_GRAPHITE)
357 skgpu::graphite::RecorderOptions CreateTestingRecorderOptions();
358 #endif
359
360 } // namespace ToolUtils
361
362 #endif // ToolUtils_DEFINED
363