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 sk_tool_utils_DEFINED
9#define sk_tool_utils_DEFINED
10
11#include "SkColor.h"
12#include "SkImageEncoder.h"
13#include "SkImageInfo.h"
14#include "SkRandom.h"
15#include "SkRefCnt.h"
16#include "SkStream.h"
17#include "SkTDArray.h"
18#include "SkTypeface.h"
19
20class SkBitmap;
21class SkCanvas;
22class SkColorFilter;
23class SkImage;
24class SkPaint;
25class SkPath;
26class SkRRect;
27class SkShader;
28class SkSurface;
29class SkSurfaceProps;
30class SkTestFont;
31class SkTextBlobBuilder;
32
33namespace sk_tool_utils {
34
35    const char* alphatype_name(SkAlphaType);
36    const char* colortype_name(SkColorType);
37
38    /**
39     * Map opaque colors from 8888 to 565.
40     */
41    SkColor color_to_565(SkColor color);
42
43    /**
44     * Return a color emoji typeface if available.
45     */
46    sk_sp<SkTypeface> emoji_typeface();
47
48    /**
49     * If the platform supports color emoji, return sample text the emoji can render.
50     */
51    const char* emoji_sample_text();
52
53    /**
54     * Returns a string describing the platform font manager, if we're using one, otherwise "".
55     */
56    const char* platform_font_manager();
57
58    /**
59     * Sets the paint to use a platform-independent text renderer
60     */
61    void set_portable_typeface(SkPaint* paint, const char* name = nullptr,
62                               SkFontStyle style = SkFontStyle());
63
64    /**
65     * Returns a platform-independent text renderer.
66     */
67    sk_sp<SkTypeface> create_portable_typeface(const char* name, SkFontStyle style);
68
69    /** Call to clean up portable font references. */
70    void release_portable_typefaces();
71
72    /**
73     *  Call writePixels() by using the pixels from bitmap, but with an info that claims
74     *  the pixels are colorType + alphaType
75     */
76    void write_pixels(SkCanvas*, const SkBitmap&, int x, int y, SkColorType, SkAlphaType);
77    void write_pixels(SkSurface*, const SkBitmap&, int x, int y, SkColorType, SkAlphaType);
78
79    /**
80     *  Returns true iff all of the pixels between the two images differ by <= the maxDiff value
81     *  per component.
82     *
83     *  If the configs differ, return false.
84     *
85     *  If the colorType is half-float, then maxDiff is interpreted as 0..255 --> 0..1
86     */
87    bool equal_pixels(const SkPixmap&, const SkPixmap&, unsigned maxDiff = 0,
88                      bool respectColorSpaces = false);
89    bool equal_pixels(const SkBitmap&, const SkBitmap&, unsigned maxDiff = 0,
90                      bool respectColorSpaces = false);
91    bool equal_pixels(const SkImage* a, const SkImage* b, unsigned maxDiff = 0,
92                      bool respectColorSpaces = false);
93
94    // private to sk_tool_utils
95    sk_sp<SkTypeface> create_font(const char* name, SkFontStyle);
96
97    /** Returns a newly created CheckerboardShader. */
98    sk_sp<SkShader> create_checkerboard_shader(SkColor c1, SkColor c2, int size);
99
100    /** Draw a checkerboard pattern in the current canvas, restricted to
101        the current clip, using SkXfermode::kSrc_Mode. */
102    void draw_checkerboard(SkCanvas* canvas,
103                           SkColor color1,
104                           SkColor color2,
105                           int checkSize);
106
107    /** Make it easier to create a bitmap-based checkerboard */
108    SkBitmap create_checkerboard_bitmap(int w, int h,
109                                        SkColor c1, SkColor c2,
110                                        int checkSize);
111
112    /** A default checkerboard. */
113    inline void draw_checkerboard(SkCanvas* canvas) {
114        sk_tool_utils::draw_checkerboard(canvas, 0xFF999999, 0xFF666666, 8);
115    }
116
117    SkBitmap create_string_bitmap(int w, int h, SkColor c, int x, int y,
118                                  int textSize, const char* str);
119
120    // If the canvas does't make a surface (e.g. recording), make a raster surface
121    sk_sp<SkSurface> makeSurface(SkCanvas*, const SkImageInfo&, const SkSurfaceProps* = nullptr);
122
123    // A helper for inserting a drawtext call into a SkTextBlobBuilder
124    void add_to_text_blob_w_len(SkTextBlobBuilder* builder, const char* text, size_t len,
125                                const SkPaint& origPaint, SkScalar x, SkScalar y);
126
127    void add_to_text_blob(SkTextBlobBuilder* builder, const char* text,
128                          const SkPaint& origPaint, SkScalar x, SkScalar y);
129
130    // Constructs a star by walking a 'numPts'-sided regular polygon with even/odd fill:
131    //
132    //   moveTo(pts[0]);
133    //   lineTo(pts[step % numPts]);
134    //   ...
135    //   lineTo(pts[(step * (N - 1)) % numPts]);
136    //
137    // numPts=5, step=2 will produce a classic five-point star.
138    //
139    // numPts and step must be co-prime.
140    SkPath make_star(const SkRect& bounds, int numPts = 5, int step = 2);
141
142    void make_big_path(SkPath& path);
143
144    // Return a blurred version of 'src'. This doesn't use a separable filter
145    // so it is slow!
146    SkBitmap slow_blur(const SkBitmap& src, float sigma);
147
148    SkRect compute_central_occluder(const SkRRect& rr);
149    SkRect compute_widest_occluder(const SkRRect& rr);
150    SkRect compute_tallest_occluder(const SkRRect& rr);
151
152    // A helper object to test the topological sorting code (TopoSortBench.cpp & TopoSortTest.cpp)
153    class TopoTestNode : public SkRefCnt {
154    public:
155        TopoTestNode(int id) : fID(id), fOutputPos(-1), fTempMark(false) { }
156
157        void dependsOn(TopoTestNode* src) {
158            *fDependencies.append() = src;
159        }
160
161        int id() const { return fID; }
162        void reset() { fOutputPos = -1; }
163
164        int outputPos() const { return fOutputPos; }
165
166        // check that the topological sort is valid for this node
167        bool check() {
168            if (-1 == fOutputPos) {
169                return false;
170            }
171
172            for (int i = 0; i < fDependencies.count(); ++i) {
173                if (-1 == fDependencies[i]->outputPos()) {
174                    return false;
175                }
176                // This node should've been output after all the nodes on which it depends
177                if (fOutputPos < fDependencies[i]->outputPos()) {
178                    return false;
179                }
180            }
181
182            return true;
183        }
184
185        // The following 7 methods are needed by the topological sort
186        static void SetTempMark(TopoTestNode* node) { node->fTempMark = true; }
187        static void ResetTempMark(TopoTestNode* node) { node->fTempMark = false; }
188        static bool IsTempMarked(TopoTestNode* node) { return node->fTempMark; }
189        static void Output(TopoTestNode* node, int outputPos) {
190            SkASSERT(-1 != outputPos);
191            node->fOutputPos = outputPos;
192        }
193        static bool WasOutput(TopoTestNode* node) { return (-1 != node->fOutputPos); }
194        static int NumDependencies(TopoTestNode* node) { return node->fDependencies.count(); }
195        static TopoTestNode* Dependency(TopoTestNode* node, int index) {
196            return node->fDependencies[index];
197        }
198
199        // Helper functions for TopoSortBench & TopoSortTest
200        static void AllocNodes(SkTArray<sk_sp<sk_tool_utils::TopoTestNode>>* graph, int num) {
201            graph->reserve(num);
202
203            for (int i = 0; i < num; ++i) {
204                graph->push_back(sk_sp<TopoTestNode>(new TopoTestNode(i)));
205            }
206        }
207
208#ifdef SK_DEBUG
209        static void Print(const SkTArray<TopoTestNode*>& graph) {
210            for (int i = 0; i < graph.count(); ++i) {
211                SkDebugf("%d, ", graph[i]->id());
212            }
213            SkDebugf("\n");
214        }
215#endif
216
217        // randomize the array
218        static void Shuffle(SkTArray<sk_sp<TopoTestNode>>* graph, SkRandom* rand) {
219            for (int i = graph->count()-1; i > 0; --i) {
220                int swap = rand->nextU() % (i+1);
221
222                (*graph)[i].swap((*graph)[swap]);
223            }
224        }
225
226    private:
227        int  fID;
228        int  fOutputPos;
229        bool fTempMark;
230
231        SkTDArray<TopoTestNode*> fDependencies;
232    };
233
234    template <typename T>
235    inline bool EncodeImageToFile(const char* path, const T& src, SkEncodedImageFormat f, int q) {
236        SkFILEWStream file(path);
237        return file.isValid() && SkEncodeImage(&file, src, f, q);
238    }
239
240    template <typename T>
241    inline sk_sp<SkData> EncodeImageToData(const T& src, SkEncodedImageFormat f, int q) {
242        SkDynamicMemoryWStream buf;
243        return SkEncodeImage(&buf, src , f, q) ? buf.detachAsData() : nullptr;
244    }
245
246    bool copy_to(SkBitmap* dst, SkColorType dstCT, const SkBitmap& src);
247    void copy_to_g8(SkBitmap* dst, const SkBitmap& src);
248}  // namespace sk_tool_utils
249
250#endif  // sk_tool_utils_DEFINED
251