Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / tests / PathOpsSkpClipTest.cpp
1 #include "CrashHandler.h"
2 // #include "OverwriteLine.h"
3 #include "Resources.h"
4 #include "SkBitmap.h"
5 #include "SkCanvas.h"
6 #include "SkColor.h"
7 #include "SkColorPriv.h"
8 #include "SkCommandLineFlags.h"
9 #include "SkDevice.h"
10 #include "SkForceLinking.h"
11 #include "SkGraphics.h"
12 #include "SkImageDecoder.h"
13 #include "SkImageEncoder.h"
14 #include "SkOSFile.h"
15 #include "SkPathOpsDebug.h"
16 #include "SkPicture.h"
17 #include "SkRTConf.h"
18 #include "SkTSort.h"
19 #include "SkStream.h"
20 #include "SkString.h"
21 #include "SkTArray.h"
22 #include "SkTDArray.h"
23 #include "SkTemplates.h"
24 #include "SkThreadPool.h"
25 #include "SkTime.h"
26
27 __SK_FORCE_IMAGE_DECODER_LINKING;
28
29 /* add local exceptions here */
30 /* TODO : add command flag interface */
31 const struct SkipOverTest {
32     int directory;
33     const char* filename;
34     bool blamePathOps;
35 } skipOver[] = {
36     { 2, "http___www_groupon_sg_.skp", false},  // SkAAClip::Builder::addRun SkASSERT(fBounds.contains(x, y));
37     { 6, "http___www_googleventures_com_.skp", true},  // addTCoincident SkASSERT(test->fT < 1);
38     { 7, "http___www_foxsports_nl_.skp", true},  // (no repro on mac) addT SkASSERT(this != other || fVerb == SkPath::kCubic_Verb)
39     {13, "http___www_modernqigong_com_.skp", false},  // SkAAClip::Builder::addRun SkASSERT(fBounds.contains(x, y));
40     {14, "http___www_devbridge_com_.skp", true},  // checkSmallCoincidence SkASSERT(!next->fSmall || checkMultiple);
41     {16, "http___www_1023world_net_.skp", false},  // bitmap decode assert (corrupt skp?)
42     {19, "http___www_alamdi_com_.skp", true},  // cubic/quad intersection
43     {26, "http___www_liveencounters_net_.skp", true},  // (no repro on mac) checkSmall addT:549 (line, expects cubic)
44     {28, "http___www_encros_fr_.skp", false},  // SkAAClip::Builder::addRun SkASSERT(fBounds.contains(x, y));
45     {37, "http___www_familysurvivalprotocol_wordpress_com_.skp", true},  // bumpSpan SkASSERT(span->fOppValue >= 0);
46     {39, "http___sufeinet_com_.skp", false}, // bitmap decode assert (corrupt skp?)
47     {41, "http___www_rano360_com_.skp", true}, // checkSmallCoincidence SkASSERT(!next->fSmall || checkMultiple);
48     {44, "http___www_firstunitedbank_com_.skp", true},  // addTCancel SkASSERT(oIndex > 0);
49     {46, "http___www_shinydemos_com_.skp", true},  // addSimpleAngle SkASSERT(index == count() - 2);
50     {48, "http___www_familysurvivalprotocol_com_.skp", true},  // bumpSpan SkASSERT "span->fOppValue >= 0"
51     {57, "http___www_lptemp_com_.skp", true}, // addTCoincident oPeek = &other->fTs[++oPeekIndex];
52     {71, "http___www_1milyonkahraman_org_.skp", true},  // addTCoincident SkASSERT(test->fT < 1);
53     {88, "http___www_apuntesdelechuza_wordpress_com_.skp", true},  // bumpSpan SkASSERT "span->fOppValue >= 0"
54     {89, "http___www_mobilizedconsulting_com_.skp", true}, // addTCancel SkASSERT(oIndex > 0);
55     {93, "http___www_simple_living_in_suffolk_co_uk_.skp", true},  // bumpSpan SkASSERT "span->fOppValue >= 0"
56 };
57
58 size_t skipOverCount = sizeof(skipOver) / sizeof(skipOver[0]);
59
60
61 /* customize file in/out here */
62 /* TODO : add command flag interface */
63 #define CHROME_VERSION "1e5dfa4-4a995df"
64 #define SUMMARY_RUN 1
65
66 #ifdef SK_BUILD_FOR_WIN
67     #define DRIVE_SPEC "D:"
68     #define PATH_SLASH "\\"
69 #else
70     #define DRIVE_SPEC ""
71     #define PATH_SLASH "/"
72 #endif
73
74 #define IN_DIR_PRE  DRIVE_SPEC PATH_SLASH "skps"   PATH_SLASH "slave"
75 #define OUT_DIR_PRE DRIVE_SPEC PATH_SLASH "skpOut" PATH_SLASH "slave"
76 #define OUT_DIR_SUM DRIVE_SPEC PATH_SLASH "skpOut" PATH_SLASH "summary"
77 #define DIR_POST               PATH_SLASH "All"    PATH_SLASH CHROME_VERSION
78
79 static const char outOpDir[]     = "opClip";
80 static const char outOldDir[]    = "oldClip";
81 static const char outStatusDir[] = "statusTest";
82
83 static SkString get_in_path(int dirNo, const char* filename) {
84     SkString path;
85     SkASSERT(dirNo);
86     path.appendf("%s%d%s", IN_DIR_PRE, dirNo, DIR_POST);
87     if (!sk_exists(path.c_str())) {
88         SkDebugf("could not read %s\n", path.c_str());
89         return SkString();
90     }
91     if (filename) {
92         path.appendf("%s%s", PATH_SLASH, filename);
93         if (!sk_exists(path.c_str())) {        
94             SkDebugf("could not read %s\n", path.c_str());
95             return SkString();
96         }
97     }
98     return path;
99 }
100     
101 static void make_recursive_dir(const SkString& path) {
102     if (sk_exists(path.c_str())) {
103         return;
104     }
105     const char* pathStr = path.c_str();
106     int last = (int) path.size();
107     do {
108         while (last > 0 && pathStr[--last] != PATH_SLASH[0])
109             ;
110         SkASSERT(last > 0);
111         SkString shorter(pathStr, last);
112         if (sk_mkdir(shorter.c_str())) {
113             break;
114         }
115     } while (true);
116     do {
117         while (last < (int) path.size() && pathStr[++last] != PATH_SLASH[0])
118             ;
119         SkString shorter(pathStr, last);
120         SkAssertResult(sk_mkdir(shorter.c_str()));
121     } while (last < (int) path.size());
122 }
123
124 static SkString get_out_path(int dirNo, const char* dirName) {
125     SkString path;
126     SkASSERT(dirNo);
127     SkASSERT(dirName);
128     path.appendf("%s%d%s%s%s", OUT_DIR_PRE, dirNo, DIR_POST, PATH_SLASH, dirName);
129     make_recursive_dir(path);
130     return path;
131 }
132   
133 static SkString get_sum_path(const char* dirName) {
134     SkString path;
135     SkASSERT(dirName);
136     path.appendf("%s%d%s%s", OUT_DIR_SUM, SUMMARY_RUN, PATH_SLASH, dirName);
137     SkDebugf("%s\n", path.c_str());
138     make_recursive_dir(path);
139     return path;
140 }
141
142 static SkString make_png_name(const char* filename) {
143     SkString pngName = SkString(filename);
144     pngName.remove(pngName.size() - 3, 3);
145     pngName.append("png");
146     return pngName;
147 }
148
149 ////////////////////////////////////////////////////////
150
151 enum TestStep {
152     kCompareBits,
153     kEncodeFiles,
154 };
155
156 enum {
157     kMaxLength = 256,
158     kMaxFiles = 128,
159     kSmallLimit = 1000,
160 };
161
162 struct TestResult {
163     void init(int dirNo) {
164         fDirNo = dirNo;
165         sk_bzero(fFilename, sizeof(fFilename));
166         fTestStep = kCompareBits;
167         fScale = 1;
168     }
169     
170     void init(int dirNo, const SkString& filename) {
171         fDirNo = dirNo;
172         strcpy(fFilename, filename.c_str());
173         fTestStep = kCompareBits;
174         fScale = 1;       
175     }
176
177     SkString status() {
178         SkString outStr;
179         outStr.printf("%s %d %d\n", fFilename, fPixelError, fTime);
180         return outStr;
181     }
182
183     SkString progress() {
184         SkString outStr;
185         outStr.printf("dir=%d %s ", fDirNo, fFilename);
186         if (fPixelError) {
187             outStr.appendf(" err=%d", fPixelError);
188         }
189         if (fTime) {
190             outStr.appendf(" time=%d", fTime);
191         }
192         if (fScale != 1) {
193             outStr.appendf(" scale=%d", fScale);
194         }
195         outStr.appendf("\n");
196         return outStr;
197
198     }
199
200     void test(int dirNo, const SkString& filename) {
201         init(dirNo);
202         strcpy(fFilename, filename.c_str());
203         testOne();
204     }
205
206     void testOne();
207     
208     char fFilename[kMaxLength];
209     TestStep fTestStep;
210     int fDirNo;
211     int fPixelError;
212     int fTime;
213     int fScale;
214 };
215
216 class SortByPixel : public TestResult {
217 public:
218     bool operator<(const SortByPixel& rh) const {
219         return fPixelError < rh.fPixelError;
220     }
221 };
222
223 class SortByTime : public TestResult {
224 public:
225     bool operator<(const SortByTime& rh) const {
226         return fTime < rh.fTime;
227     }
228 };
229
230 class SortByName : public TestResult {
231 public:
232     bool operator<(const SortByName& rh) const {
233         return strcmp(fFilename, rh.fFilename) < 0;
234     }
235 };
236
237 struct TestState {
238     void init(int dirNo) {
239         fResult.init(dirNo);
240     }
241
242     SkTDArray<SortByPixel> fPixelWorst;
243     SkTDArray<SortByTime> fSlowest;
244     TestResult fResult;
245 };
246
247 struct TestRunner {
248     TestRunner(int threadCount)
249         : fNumThreads(threadCount) {
250     }
251
252     ~TestRunner();
253     void render();
254     int fNumThreads;
255     SkTDArray<class TestRunnable*> fRunnables;
256 };
257
258 class TestRunnable : public SkRunnable {
259 public:
260     virtual void run() SK_OVERRIDE {
261         SkGraphics::SetTLSFontCacheLimit(1 * 1024 * 1024);
262         (*fTestFun)(&fState);
263     }
264
265     TestState fState;
266     void (*fTestFun)(TestState*);
267 };
268
269
270 class TestRunnableDir : public TestRunnable {
271 public:
272     TestRunnableDir(void (*testFun)(TestState*), int dirNo, TestRunner* runner) {
273         fState.init(dirNo);
274         fTestFun = testFun;
275     }
276
277 };
278
279 class TestRunnableFile : public TestRunnable {
280 public:
281     TestRunnableFile(void (*testFun)(TestState*), int dirNo, const char* name, TestRunner* runner) {
282         fState.init(dirNo);
283         strcpy(fState.fResult.fFilename, name);
284         fTestFun = testFun;
285     }
286 };
287
288 class TestRunnableEncode : public TestRunnableFile {
289 public:
290     TestRunnableEncode(void (*testFun)(TestState*), int dirNo, const char* name, TestRunner* runner)
291         : TestRunnableFile(testFun, dirNo, name, runner) {
292         fState.fResult.fTestStep = kEncodeFiles;
293     }
294 };
295
296 TestRunner::~TestRunner() {
297     for (int index = 0; index < fRunnables.count(); index++) {
298         SkDELETE(fRunnables[index]);
299     }
300 }
301
302 void TestRunner::render() {
303     SkThreadPool pool(fNumThreads);
304     for (int index = 0; index < fRunnables.count(); ++ index) {
305         pool.add(fRunnables[index]);
306     }
307 }
308
309 ////////////////////////////////////////////////
310
311
312 static int similarBits(const SkBitmap& gr, const SkBitmap& sk) {
313     const int kRowCount = 3;
314     const int kThreshold = 3;
315     int width = SkTMin(gr.width(), sk.width());
316     if (width < kRowCount) {
317         return true;
318     }
319     int height = SkTMin(gr.height(), sk.height());
320     if (height < kRowCount) {
321         return true;
322     }
323     int errorTotal = 0;
324     SkTArray<int, true> errorRows;
325     errorRows.push_back_n(width * kRowCount);
326     SkAutoLockPixels autoGr(gr);
327     SkAutoLockPixels autoSk(sk);
328     for (int y = 0; y < height; ++y) {
329         SkPMColor* grRow = gr.getAddr32(0, y);
330         SkPMColor* skRow = sk.getAddr32(0, y);
331         int* base = &errorRows[0];
332         int* cOut = &errorRows[y % kRowCount];
333         for (int x = 0; x < width; ++x) {
334             SkPMColor grColor = grRow[x];
335             SkPMColor skColor = skRow[x];
336             int dr = SkGetPackedR32(grColor) - SkGetPackedR32(skColor);
337             int dg = SkGetPackedG32(grColor) - SkGetPackedG32(skColor);
338             int db = SkGetPackedB32(grColor) - SkGetPackedB32(skColor);
339             int error = cOut[x] = SkTMax(SkAbs32(dr), SkTMax(SkAbs32(dg), SkAbs32(db)));
340             if (error < kThreshold || x < 2) {
341                 continue;
342             }
343             if (base[x - 2] < kThreshold
344                     || base[width + x - 2] < kThreshold
345                     || base[width * 2 + x - 2] < kThreshold
346                     || base[x - 1] < kThreshold
347                     || base[width + x - 1] < kThreshold
348                     || base[width * 2 + x - 1] < kThreshold
349                     || base[x] < kThreshold
350                     || base[width + x] < kThreshold
351                     || base[width * 2 + x] < kThreshold) {
352                 continue;
353             }
354             errorTotal += error;
355         }
356     }
357     return errorTotal;
358 }
359
360 static bool addError(TestState* data, const TestResult& testResult) {
361     if (testResult.fPixelError <= 0 && testResult.fTime <= 0) {
362         return false;
363     }
364     int worstCount = data->fPixelWorst.count();
365     int pixelError = testResult.fPixelError;
366     if (pixelError > 0) {
367         for (int index = 0; index < worstCount; ++index) {
368             if (pixelError > data->fPixelWorst[index].fPixelError) {
369                 data->fPixelWorst[index] = *(SortByPixel*) &testResult;
370                 return true;
371             }
372         }
373     }
374     int slowCount = data->fSlowest.count();
375     int time = testResult.fTime;
376     if (time > 0) {
377         for (int index = 0; index < slowCount; ++index) {
378             if (time > data->fSlowest[index].fTime) {
379                 data->fSlowest[index] = *(SortByTime*) &testResult;
380                 return true;
381             }
382         }
383     }
384     if (pixelError > 0 && worstCount < kMaxFiles) {
385         *data->fPixelWorst.append() = *(SortByPixel*) &testResult;
386         return true;
387     }
388     if (time > 0 && slowCount < kMaxFiles) {
389         *data->fSlowest.append() = *(SortByTime*) &testResult;
390         return true;
391     }
392     return false;
393 }
394
395 static SkMSec timePict(SkPicture* pic, SkCanvas* canvas) {
396     canvas->save();
397     int pWidth = pic->width();
398     int pHeight = pic->height();
399     const int maxDimension = 1000;
400     const int slices = 3;
401     int xInterval = SkTMax(pWidth - maxDimension, 0) / (slices - 1);
402     int yInterval = SkTMax(pHeight - maxDimension, 0) / (slices - 1);
403     SkRect rect = {0, 0, SkIntToScalar(SkTMin(maxDimension, pWidth)),
404             SkIntToScalar(SkTMin(maxDimension, pHeight))};
405     canvas->clipRect(rect);
406     SkMSec start = SkTime::GetMSecs();
407     for (int x = 0; x < slices; ++x) {
408         for (int y = 0; y < slices; ++y) {
409             pic->draw(canvas);
410             canvas->translate(0, SkIntToScalar(yInterval));
411         }
412         canvas->translate(SkIntToScalar(xInterval), SkIntToScalar(-yInterval * slices));
413     }
414     SkMSec end = SkTime::GetMSecs();
415     canvas->restore();
416     return end - start;
417 }
418
419 static void drawPict(SkPicture* pic, SkCanvas* canvas, int scale) {
420     canvas->clear(SK_ColorWHITE);
421     if (scale != 1) {
422         canvas->save();
423         canvas->scale(1.0f / scale, 1.0f / scale);
424     }
425     pic->draw(canvas);
426     if (scale != 1) {
427         canvas->restore();
428     }
429 }
430
431 static void writePict(const SkBitmap& bitmap, const char* outDir, const char* pngName) {
432     SkString outFile = get_sum_path(outDir);
433     outFile.appendf("%s%s", PATH_SLASH, pngName);
434     if (!SkImageEncoder::EncodeFile(outFile.c_str(), bitmap, SkImageEncoder::kPNG_Type, 100)) {
435         SkDebugf("unable to encode gr %s (width=%d height=%d)\n", pngName,
436                     bitmap.width(), bitmap.height());
437     }
438 }
439
440 void TestResult::testOne() {
441     SkPicture* pic = NULL;
442     {
443     #if DEBUG_SHOW_TEST_NAME
444         if (fTestStep == kCompareBits) {
445             SkString testName(fFilename);
446             const char http[] = "http";
447             if (testName.startsWith(http)) {
448                 testName.remove(0, sizeof(http) - 1);
449             }
450             while (testName.startsWith("_")) {
451                 testName.remove(0, 1);
452             }
453             const char dotSkp[] = ".skp";
454             if (testName.endsWith(dotSkp)) {
455                 size_t len = testName.size();
456                 testName.remove(len - (sizeof(dotSkp) - 1), sizeof(dotSkp) - 1);
457             }
458             testName.prepend("skp");
459             testName.append("1");
460             strncpy(DEBUG_FILENAME_STRING, testName.c_str(), DEBUG_FILENAME_STRING_LENGTH);
461         } else if (fTestStep == kEncodeFiles) {
462             strncpy(DEBUG_FILENAME_STRING, "", DEBUG_FILENAME_STRING_LENGTH);
463         }
464     #endif
465         SkString path = get_in_path(fDirNo, fFilename);
466         SkFILEStream stream(path.c_str());
467         if (!stream.isValid()) {
468             SkDebugf("invalid stream %s\n", path.c_str());
469             goto finish;
470         }
471         pic = SkPicture::CreateFromStream(&stream, &SkImageDecoder::DecodeMemory);
472         if (!pic) {
473             SkDebugf("unable to decode %s\n", fFilename);
474             goto finish;
475         }
476         int width = pic->width();
477         int height = pic->height();
478         SkBitmap oldBitmap, opBitmap;
479         fScale = 1;
480         while (width / fScale > 32767 || height / fScale > 32767) {
481             ++fScale;
482         }
483         do {
484             int dimX = (width + fScale - 1) / fScale;
485             int dimY = (height + fScale - 1) / fScale;
486             if (oldBitmap.allocN32Pixels(dimX, dimY) &&
487                 opBitmap.allocN32Pixels(dimX, dimY)) {
488                 break;
489             }
490             SkDebugf("-%d-", fScale);
491         } while (++fScale < 256);
492         if (fScale >= 256) {
493             SkDebugf("unable to allocate bitmap for %s (w=%d h=%d)\n", fFilename,
494                     width, height);
495             goto finish;
496         }
497         oldBitmap.eraseColor(SK_ColorWHITE);
498         SkCanvas oldCanvas(oldBitmap);
499         oldCanvas.setAllowSimplifyClip(false);
500         opBitmap.eraseColor(SK_ColorWHITE);
501         SkCanvas opCanvas(opBitmap);
502         opCanvas.setAllowSimplifyClip(true);
503         drawPict(pic, &oldCanvas, fScale);
504         drawPict(pic, &opCanvas, fScale);
505         if (fTestStep == kCompareBits) {
506             fPixelError = similarBits(oldBitmap, opBitmap);
507             int oldTime = timePict(pic, &oldCanvas);
508             int opTime = timePict(pic, &opCanvas);
509             fTime = SkTMax(0, oldTime - opTime);
510         } else if (fTestStep == kEncodeFiles) {
511             SkString pngStr = make_png_name(fFilename);
512             const char* pngName = pngStr.c_str();
513             writePict(oldBitmap, outOldDir, pngName);
514             writePict(opBitmap, outOpDir, pngName);
515         }
516     }
517 finish:
518     if (pic) {
519         pic->unref();
520     }
521 }
522
523 DEFINE_string2(match, m, "PathOpsSkpClipThreaded",
524         "[~][^]substring[$] [...] of test name to run.\n"
525         "Multiple matches may be separated by spaces.\n"
526         "~ causes a matching test to always be skipped\n"
527         "^ requires the start of the test to match\n"
528         "$ requires the end of the test to match\n"
529         "^ and $ requires an exact match\n"
530         "If a test does not match any list entry,\n"
531         "it is skipped unless some list entry starts with ~");
532 DEFINE_string2(dir, d, NULL, "range of directories (e.g., 1-100)");
533 DEFINE_string2(skp, s, NULL, "skp to test");
534 DEFINE_bool2(single, z, false, "run tests on a single thread internally.");
535 DEFINE_int32(testIndex, 0, "override local test index (PathOpsSkpClipOneOff only).");
536 DEFINE_int32(threads, SkThreadPool::kThreadPerCore,
537         "Run threadsafe tests on a threadpool with this many threads.");
538 DEFINE_bool2(verbose, v, false, "enable verbose output.");
539
540 static bool verbose() {
541     return FLAGS_verbose;
542 }
543
544 static int getThreadCount() {
545     return FLAGS_single ? 1 : FLAGS_threads;
546 }
547
548 class Dirs {
549 public:
550     Dirs() {
551         reset();
552         sk_bzero(fRun, sizeof(fRun));
553         fSet = false;
554     }
555
556     int first() const {
557         int index = 0;
558         while (++index < kMaxDir) {
559             if (fRun[index]) {
560                 return index;
561             }
562         }
563         SkASSERT(0);
564         return -1;
565     }
566
567     int last() const {
568         int index = kMaxDir;
569         while (--index > 0 && !fRun[index])
570             ;
571         return index;
572     }
573
574     int next() {
575         while (++fIndex < kMaxDir) {
576             if (fRun[fIndex]) {
577                 return fIndex;
578             }
579         }
580         return -1;
581     }
582
583     void reset() {
584         fIndex = -1;
585     }
586
587     void set(int start, int end) {
588         while (start < end) {
589             fRun[start++] = 1;
590         }
591         fSet = true;
592     }
593
594     void setDefault() {
595         if (!fSet) {
596             set(1, 100);
597         }
598     }
599
600 private:
601     enum {
602          kMaxDir = 101
603     };
604     char fRun[kMaxDir];
605     int fIndex;
606     bool fSet;
607 } gDirs;
608
609 class Filenames {
610 public:
611     Filenames()
612         : fIndex(-1) {
613     }
614
615     const char* next() {
616         while (fNames && ++fIndex < fNames->count()) {
617             return (*fNames)[fIndex];
618         }
619         return NULL;
620     }
621     
622     void set(const SkCommandLineFlags::StringArray& names) {
623         fNames = &names;
624     }
625
626 private:
627     int fIndex;
628     const SkCommandLineFlags::StringArray* fNames;
629 } gNames;
630
631 static bool buildTestDir(int dirNo, int firstDirNo, 
632         SkTDArray<TestResult>* tests, SkTDArray<SortByName*>* sorted) {
633     SkString dirName = get_out_path(dirNo, outStatusDir);
634     if (!dirName.size()) {
635         return false;
636     }
637     SkOSFile::Iter iter(dirName.c_str(), "skp");
638     SkString filename;
639     while (iter.next(&filename)) {
640         TestResult test;
641         test.init(dirNo);
642         SkString spaceFile(filename);
643         char* spaces = spaceFile.writable_str();
644         int spaceSize = (int) spaceFile.size();
645         for (int index = 0; index < spaceSize; ++index) {
646             if (spaces[index] == '.') {
647                 spaces[index] = ' ';
648             }
649         }
650         int success = sscanf(spaces, "%s %d %d skp", test.fFilename,
651                 &test.fPixelError, &test.fTime);
652         if (success < 3) {
653             SkDebugf("failed to scan %s matched=%d\n", filename.c_str(), success);
654             return false;
655         }
656         *tests[dirNo - firstDirNo].append() = test;
657     }
658     if (!sorted) {
659         return true;
660     }
661     SkTDArray<TestResult>& testSet = tests[dirNo - firstDirNo];
662     int count = testSet.count();
663     for (int index = 0; index < count; ++index) {
664         *sorted[dirNo - firstDirNo].append() = (SortByName*) &testSet[index];
665     }
666     if (sorted[dirNo - firstDirNo].count()) {
667         SkTQSort<SortByName>(sorted[dirNo - firstDirNo].begin(),
668                 sorted[dirNo - firstDirNo].end() - 1);
669         if (verbose()) {
670             SkDebugf("+");
671         }
672     }
673     return true;
674 }
675
676 static void testSkpClip(TestState* data) {
677     data->fResult.testOne();
678     SkString statName(data->fResult.fFilename);
679     SkASSERT(statName.endsWith(".skp"));
680     statName.remove(statName.size() - 4, 4);
681     statName.appendf(".%d.%d.skp", data->fResult.fPixelError, data->fResult.fTime);
682     SkString statusFile = get_out_path(data->fResult.fDirNo, outStatusDir);
683     if (!statusFile.size()) {
684         SkDebugf("failed to create %s", statusFile.c_str());
685         return;
686     }
687     statusFile.appendf("%s%s", PATH_SLASH, statName.c_str());
688     SkFILE* file = sk_fopen(statusFile.c_str(), kWrite_SkFILE_Flag);
689     if (!file) {
690             SkDebugf("failed to create %s", statusFile.c_str());
691             return;
692     }
693     sk_fclose(file);
694     if (verbose()) {
695         if (data->fResult.fPixelError || data->fResult.fTime) {
696             SkDebugf("%s", data->fResult.progress().c_str());
697         } else {
698             SkDebugf(".");
699         }
700     }
701 }
702
703 bool Less(const SortByName& a, const SortByName& b);
704 bool Less(const SortByName& a, const SortByName& b) {
705     return a < b;
706 }
707
708 static bool doOneDir(TestState* state, bool threaded) {
709     int dirNo = state->fResult.fDirNo;
710     SkString dirName = get_in_path(dirNo, NULL);
711     if (!dirName.size()) {
712         return false;
713     }
714     SkTDArray<TestResult> tests[1];
715     SkTDArray<SortByName*> sorted[1];
716     if (!buildTestDir(dirNo, dirNo, tests, sorted)) {
717         return false;
718     }
719     SkOSFile::Iter iter(dirName.c_str(), "skp");
720     SkString filename;
721     while (iter.next(&filename)) {
722         for (size_t index = 0; index < skipOverCount; ++index) {
723             if (skipOver[index].directory == dirNo
724                     && strcmp(filename.c_str(), skipOver[index].filename) == 0) {
725                 goto checkEarlyExit;
726             }
727         }
728         {
729             SortByName name;
730             name.init(dirNo);
731             strncpy(name.fFilename, filename.c_str(), filename.size() - 4);  // drop .skp
732             int count = sorted[0].count();
733             int idx = SkTSearch<SortByName, Less>(sorted[0].begin(), count, &name, sizeof(&name));
734             if (idx >= 0) {
735                 SortByName* found = sorted[0][idx];
736                 (void) addError(state, *found);
737                 continue;
738             }
739             TestResult test;
740             test.init(dirNo, filename);
741             state->fResult = test;
742             testSkpClip(state);
743 #if 0 // artificially limit to a few while debugging code
744             static int debugLimit = 0;
745             if (++debugLimit == 5) {
746                 return true;
747             }
748 #endif
749         }
750 checkEarlyExit:
751         ;
752     }
753     return true;
754 }
755
756 static void initTest() {
757 #if !defined SK_BUILD_FOR_WIN && !defined SK_BUILD_FOR_MAC
758     SK_CONF_SET("images.jpeg.suppressDecoderWarnings", true);
759     SK_CONF_SET("images.png.suppressDecoderWarnings", true);
760 #endif
761 }
762
763 static void testSkpClipEncode(TestState* data) {
764     data->fResult.testOne();
765     if (verbose()) {
766         SkDebugf("+");
767     }
768 }
769
770 static void encodeFound(TestState& state) {
771     if (verbose()) {
772         if (state.fPixelWorst.count()) {
773             SkTDArray<SortByPixel*> worst;
774             for (int index = 0; index < state.fPixelWorst.count(); ++index) {
775                 *worst.append() = &state.fPixelWorst[index];
776             }
777             SkTQSort<SortByPixel>(worst.begin(), worst.end() - 1);
778             for (int index = 0; index < state.fPixelWorst.count(); ++index) {
779                 const TestResult& result = *worst[index];
780                 SkDebugf("%d %s pixelError=%d\n", result.fDirNo, result.fFilename, result.fPixelError);
781             }
782         }
783         if (state.fSlowest.count()) {
784             SkTDArray<SortByTime*> slowest;
785             for (int index = 0; index < state.fSlowest.count(); ++index) {
786                 *slowest.append() = &state.fSlowest[index];
787             }
788             if (slowest.count() > 0) {
789                 SkTQSort<SortByTime>(slowest.begin(), slowest.end() - 1);
790                 for (int index = 0; index < slowest.count(); ++index) {
791                     const TestResult& result = *slowest[index];
792                     SkDebugf("%d %s time=%d\n", result.fDirNo, result.fFilename, result.fTime);
793                 }
794             }
795         }
796     }
797     int threadCount = getThreadCount();
798     TestRunner testRunner(threadCount);
799     for (int index = 0; index < state.fPixelWorst.count(); ++index) {
800         const TestResult& result = state.fPixelWorst[index];
801         SkString filename(result.fFilename);
802         if (!filename.endsWith(".skp")) {
803             filename.append(".skp");
804         }
805         *testRunner.fRunnables.append() = SkNEW_ARGS(TestRunnableEncode,
806                 (&testSkpClipEncode, result.fDirNo, filename.c_str(), &testRunner));
807     }
808     testRunner.render();
809 }
810
811 class Test {
812 public:
813     Test() {}
814     virtual ~Test() {}
815
816     const char* getName() { onGetName(&fName); return fName.c_str(); }
817     void run() { onRun(); }
818
819 protected:
820     virtual void onGetName(SkString*) = 0;
821     virtual void onRun() = 0;
822
823 private:
824     SkString    fName;
825 };
826
827 typedef SkTRegistry<Test*(*)(void*)> TestRegistry;
828
829 #define DEF_TEST(name)                                        \
830     static void test_##name();                       \
831     class name##Class : public Test {                                   \
832     public:                                                             \
833         static Test* Factory(void*) { return SkNEW(name##Class); }      \
834     protected:                                                          \
835         virtual void onGetName(SkString* name) SK_OVERRIDE {            \
836             name->set(#name);                                           \
837         }                                                               \
838         virtual void onRun() SK_OVERRIDE { test_##name(); } \
839     };                                                                  \
840     static TestRegistry gReg_##name##Class(name##Class::Factory);       \
841     static void test_##name()
842
843 DEF_TEST(PathOpsSkpClip) {
844     gDirs.setDefault();
845     initTest();
846     SkTArray<TestResult, true> errors;
847     TestState state;
848     state.init(0);
849     int dirNo;
850     gDirs.reset();
851     while ((dirNo = gDirs.next()) > 0) {
852         if (verbose()) {
853             SkDebugf("dirNo=%d\n", dirNo);
854         }
855         state.fResult.fDirNo = dirNo;
856         if (!doOneDir(&state, false)) {
857             break;
858         }
859     }
860     encodeFound(state);
861 }
862
863 static void testSkpClipMain(TestState* data) {
864         (void) doOneDir(data, true);
865 }
866
867 DEF_TEST(PathOpsSkpClipThreaded) {
868     gDirs.setDefault();
869     initTest();
870     int threadCount = getThreadCount();
871     TestRunner testRunner(threadCount);
872     int dirNo;
873     gDirs.reset();
874     while ((dirNo = gDirs.next()) > 0) {
875         *testRunner.fRunnables.append() = SkNEW_ARGS(TestRunnableDir,
876                 (&testSkpClipMain, dirNo, &testRunner));
877     }
878     testRunner.render();
879     TestState state;
880     state.init(0);
881     gDirs.reset();
882     while ((dirNo = gDirs.next()) > 0) {
883         TestState& testState = testRunner.fRunnables[dirNo - 1]->fState;
884         SkASSERT(testState.fResult.fDirNo == dirNo);
885         for (int inner = 0; inner < testState.fPixelWorst.count(); ++inner) {
886             addError(&state, testState.fPixelWorst[inner]);
887         }
888         for (int inner = 0; inner < testState.fSlowest.count(); ++inner) {
889             addError(&state, testState.fSlowest[inner]);
890         }
891     }
892     encodeFound(state);
893 }
894  
895 static bool buildTests(SkTDArray<TestResult>* tests, SkTDArray<SortByName*>* sorted) {
896     int firstDirNo = gDirs.first();
897     int dirNo;
898     while ((dirNo = gDirs.next()) > 0) {
899         if (!buildTestDir(dirNo, firstDirNo, tests, sorted)) {
900             return false;
901         }
902     }
903     return true;
904 }
905
906 DEF_TEST(PathOpsSkpClipUberThreaded) {
907     gDirs.setDefault();
908     const int firstDirNo = gDirs.next();
909     const int lastDirNo = gDirs.last();
910     initTest();
911     int dirCount = lastDirNo - firstDirNo + 1;
912     SkAutoTDeleteArray<SkTDArray<TestResult> > tests(new SkTDArray<TestResult>[dirCount]);
913     SkAutoTDeleteArray<SkTDArray<SortByName*> > sorted(new SkTDArray<SortByName*>[dirCount]);
914     if (!buildTests(tests.get(), sorted.get())) {
915         return;
916     }
917     int threadCount = getThreadCount();
918     TestRunner testRunner(threadCount);
919     int dirNo;
920     gDirs.reset();
921     while ((dirNo = gDirs.next()) > 0) {
922         SkString dirName = get_in_path(dirNo, NULL);
923         if (!dirName.size()) {
924             continue;
925         }
926         SkOSFile::Iter iter(dirName.c_str(), "skp");
927         SkString filename;
928         while (iter.next(&filename)) {
929             for (size_t index = 0; index < skipOverCount; ++index) {
930                 if (skipOver[index].directory == dirNo
931                         && strcmp(filename.c_str(), skipOver[index].filename) == 0) {
932                     goto checkEarlyExit;
933                 }
934             }
935             {
936                 SortByName name;
937                 name.init(dirNo);
938                 strncpy(name.fFilename, filename.c_str(), filename.size() - 4);  // drop .skp
939                 int count = sorted.get()[dirNo - firstDirNo].count();
940                 if (SkTSearch<SortByName, Less>(sorted.get()[dirNo - firstDirNo].begin(),
941                         count, &name, sizeof(&name)) < 0) {
942                     *testRunner.fRunnables.append() = SkNEW_ARGS(TestRunnableFile,
943                             (&testSkpClip, dirNo, filename.c_str(), &testRunner));
944                 }
945             }
946     checkEarlyExit:
947             ;
948         }
949
950     }
951     testRunner.render();
952     SkAutoTDeleteArray<SkTDArray<TestResult> > results(new SkTDArray<TestResult>[dirCount]);
953     if (!buildTests(results.get(), NULL)) {
954         return;
955     }
956     SkTDArray<TestResult> allResults;
957     for (int dirNo = firstDirNo; dirNo <= lastDirNo; ++dirNo) {
958         SkTDArray<TestResult>& array = results.get()[dirNo - firstDirNo];
959         allResults.append(array.count(), array.begin());
960     }
961     int allCount = allResults.count();
962     SkTDArray<SortByPixel*> pixels;
963     SkTDArray<SortByTime*> times;
964     for (int index = 0; index < allCount; ++index) {
965         *pixels.append() = (SortByPixel*) &allResults[index];
966         *times.append() = (SortByTime*) &allResults[index];
967     }
968     TestState state;
969     if (pixels.count()) {
970         SkTQSort<SortByPixel>(pixels.begin(), pixels.end() - 1);
971         for (int inner = 0; inner < kMaxFiles; ++inner) {
972             *state.fPixelWorst.append() = *pixels[allCount - inner - 1];
973         }
974     }
975     if (times.count()) {
976         SkTQSort<SortByTime>(times.begin(), times.end() - 1);
977         for (int inner = 0; inner < kMaxFiles; ++inner) {
978             *state.fSlowest.append() = *times[allCount - inner - 1];
979         }
980     }
981     encodeFound(state);
982 }
983
984 DEF_TEST(PathOpsSkpClipOneOff) {
985     const int testIndex = FLAGS_testIndex;
986     int dirNo = gDirs.next();
987     if (dirNo < 0) {
988         dirNo = skipOver[testIndex].directory;
989     }
990     const char* skp = gNames.next();
991     if (!skp) {
992         skp = skipOver[testIndex].filename;
993     }
994     initTest();
995     SkAssertResult(get_in_path(dirNo, skp).size());
996     SkString filename(skp);
997     TestResult state;
998     state.test(dirNo, filename);
999     if (verbose()) {
1000         SkDebugf("%s", state.status().c_str());
1001     }
1002     state.fTestStep = kEncodeFiles;
1003     state.testOne();
1004 }
1005
1006 DEF_TEST(PathOpsTestSkipped) {
1007     for (size_t index = 0; index < skipOverCount; ++index) {
1008         const SkipOverTest& skip = skipOver[index];
1009         if (!skip.blamePathOps) {
1010             continue;
1011         }
1012         int dirNo = skip.directory;
1013         const char* skp = skip.filename;
1014         initTest();
1015         SkAssertResult(get_in_path(dirNo, skp).size());
1016         SkString filename(skp);
1017         TestResult state;
1018         state.test(dirNo, filename);
1019         if (verbose()) {
1020             SkDebugf("%s", state.status().c_str());
1021         }
1022         state.fTestStep = kEncodeFiles;
1023         state.testOne();
1024     }
1025 }
1026
1027 DEF_TEST(PathOpsCopyFails) {
1028     FLAGS_verbose = true;
1029     for (size_t index = 0; index < skipOverCount; ++index) {
1030         int dirNo = skipOver[index].directory;
1031         SkDebugf("mkdir -p " IN_DIR_PRE "%d" DIR_POST "\n", dirNo);
1032     }
1033     for (size_t index = 0; index < skipOverCount; ++index) {
1034         int dirNo = skipOver[index].directory;
1035         const char* filename = skipOver[index].filename;
1036         SkDebugf("rsync -av cary-linux.cnc:/tera" PATH_SLASH "skps" PATH_SLASH "slave"
1037             "%d" DIR_POST "/%s " IN_DIR_PRE "%d" DIR_POST "\n", dirNo, filename, dirNo);
1038     }
1039 }
1040
1041 template TestRegistry* TestRegistry::gHead;
1042
1043 class Iter {
1044 public:
1045     Iter() { this->reset(); }
1046     void reset() { fReg = TestRegistry::Head(); }
1047
1048     Test* next() {
1049         if (fReg) {
1050             TestRegistry::Factory fact = fReg->factory();
1051             fReg = fReg->next();
1052             Test* test = fact(NULL);
1053             return test;
1054         }
1055         return NULL;
1056     }
1057
1058 private:
1059     const TestRegistry* fReg;
1060 };
1061
1062 int tool_main(int argc, char** argv);
1063 int tool_main(int argc, char** argv) {
1064     SetupCrashHandler();
1065     SkCommandLineFlags::SetUsage("");
1066     SkCommandLineFlags::Parse(argc, argv);
1067     SkGraphics::Init();
1068     SkString header("PathOps SkpClip:");
1069     if (!FLAGS_match.isEmpty()) {
1070         header.appendf(" --match");
1071         for (int index = 0; index < FLAGS_match.count(); ++index) {
1072             header.appendf(" %s", FLAGS_match[index]);
1073         }
1074     }
1075     if (!FLAGS_dir.isEmpty()) {
1076         int count = FLAGS_dir.count();
1077         for (int i = 0; i < count; ++i) {
1078             const char* range = FLAGS_dir[i];
1079             const char* dash = strchr(range, '-');
1080             if (!dash) {
1081                 dash = strchr(range, ',');
1082             }
1083             int first = atoi(range);
1084             int last = dash ? atoi(dash + 1) : first;
1085             if (!first || !last) {
1086                 SkDebugf("couldn't parse --dir %s\n", range);
1087                 return 1;
1088             }
1089             gDirs.set(first, last);
1090         }
1091     }
1092     if (!FLAGS_skp.isEmpty()) {
1093         gNames.set(FLAGS_skp);
1094     }
1095 #ifdef SK_DEBUG
1096     header.append(" SK_DEBUG");
1097 #else
1098     header.append(" SK_RELEASE");
1099 #endif
1100     header.appendf(" skia_arch_width=%d", (int)sizeof(void*) * 8);
1101     if (FLAGS_verbose) {
1102         header.appendf("\n");
1103     }
1104     SkDebugf(header.c_str());
1105     Iter iter;
1106     Test* test;
1107     while ((test = iter.next()) != NULL) {
1108         SkAutoTDelete<Test> owned(test);
1109         if (!SkCommandLineFlags::ShouldSkip(FLAGS_match, test->getName())) {
1110             test->run();
1111         }
1112     }
1113     SkGraphics::Term();
1114     return 0;
1115 }
1116
1117 #if !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_NACL)
1118 int main(int argc, char * const argv[]) {
1119     return tool_main(argc, (char**) argv);
1120 }
1121 #endif