Home | History | Annotate | Download | only in gm
      1 /*
      2  * Copyright 2011 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 /*
      9  * Code for the "gm" (Golden Master) rendering comparison tool.
     10  *
     11  * If you make changes to this, re-run the self-tests at gm/tests/run.sh
     12  * to make sure they still pass... you may need to change the expected
     13  * results of the self-test.
     14  */
     15 
     16 #include "gm.h"
     17 #include "gm_error.h"
     18 #include "gm_expectations.h"
     19 #include "system_preferences.h"
     20 #include "SkBitmap.h"
     21 #include "SkColorPriv.h"
     22 #include "SkCommandLineFlags.h"
     23 #include "SkData.h"
     24 #include "SkDeferredCanvas.h"
     25 #include "SkDevice.h"
     26 #include "SkDocument.h"
     27 #include "SkDrawFilter.h"
     28 #include "SkForceLinking.h"
     29 #include "SkGPipe.h"
     30 #include "SkGraphics.h"
     31 #include "SkImageDecoder.h"
     32 #include "SkImageEncoder.h"
     33 #include "SkJSONCPP.h"
     34 #include "SkOSFile.h"
     35 #include "SkPDFRasterizer.h"
     36 #include "SkPicture.h"
     37 #include "SkRefCnt.h"
     38 #include "SkScalar.h"
     39 #include "SkStream.h"
     40 #include "SkString.h"
     41 #include "SkTArray.h"
     42 #include "SkTDict.h"
     43 #include "SkTileGridPicture.h"
     44 #include "SamplePipeControllers.h"
     45 
     46 #ifdef SK_DEBUG
     47 static const bool kDebugOnly = true;
     48 #else
     49 static const bool kDebugOnly = false;
     50 #endif
     51 
     52 __SK_FORCE_IMAGE_DECODER_LINKING;
     53 
     54 #if SK_SUPPORT_GPU
     55 #include "GrContextFactory.h"
     56 #include "SkGpuDevice.h"
     57 typedef GrContextFactory::GLContextType GLContextType;
     58 #define DEFAULT_CACHE_VALUE -1
     59 static int gGpuCacheSizeBytes;
     60 static int gGpuCacheSizeCount;
     61 #else
     62 class GrContextFactory;
     63 class GrContext;
     64 class GrSurface;
     65 typedef int GLContextType;
     66 #endif
     67 
     68 #define DEBUGFAIL_SEE_STDERR SkDEBUGFAIL("see stderr for message")
     69 
     70 extern bool gSkSuppressFontCachePurgeSpew;
     71 DECLARE_bool(useDocumentInsteadOfDevice);
     72 
     73 #ifdef SK_SUPPORT_PDF
     74     #include "SkPDFDevice.h"
     75     #include "SkPDFDocument.h"
     76 #endif
     77 
     78 // Until we resolve http://code.google.com/p/skia/issues/detail?id=455 ,
     79 // stop writing out XPS-format image baselines in gm.
     80 #undef SK_SUPPORT_XPS
     81 #ifdef SK_SUPPORT_XPS
     82     #include "SkXPSDevice.h"
     83 #endif
     84 
     85 #ifdef SK_BUILD_FOR_MAC
     86     #include "SkCGUtils.h"
     87 #endif
     88 
     89 using namespace skiagm;
     90 
     91 class Iter {
     92 public:
     93     Iter() {
     94         this->reset();
     95     }
     96 
     97     void reset() {
     98         fReg = GMRegistry::Head();
     99     }
    100 
    101     GM* next() {
    102         if (fReg) {
    103             GMRegistry::Factory fact = fReg->factory();
    104             fReg = fReg->next();
    105             return fact(0);
    106         }
    107         return NULL;
    108     }
    109 
    110     static int Count() {
    111         const GMRegistry* reg = GMRegistry::Head();
    112         int count = 0;
    113         while (reg) {
    114             count += 1;
    115             reg = reg->next();
    116         }
    117         return count;
    118     }
    119 
    120 private:
    121     const GMRegistry* fReg;
    122 };
    123 
    124 // TODO(epoger): Right now, various places in this code assume that all the
    125 // image files read/written by GM use this file extension.
    126 // Search for references to this constant to find these assumptions.
    127 const static char kPNG_FileExtension[] = "png";
    128 
    129 enum Backend {
    130     kRaster_Backend,
    131     kGPU_Backend,
    132     kPDF_Backend,
    133     kXPS_Backend,
    134 };
    135 
    136 enum BbhType {
    137     kNone_BbhType,
    138     kRTree_BbhType,
    139     kTileGrid_BbhType,
    140 };
    141 
    142 enum ConfigFlags {
    143     kNone_ConfigFlag  = 0x0,
    144     /* Write GM images if a write path is provided. */
    145     kWrite_ConfigFlag = 0x1,
    146     /* Read reference GM images if a read path is provided. */
    147     kRead_ConfigFlag  = 0x2,
    148     kRW_ConfigFlag    = (kWrite_ConfigFlag | kRead_ConfigFlag),
    149 };
    150 
    151 struct ConfigData {
    152     SkBitmap::Config                fConfig;
    153     Backend                         fBackend;
    154     GLContextType                   fGLContextType; // GPU backend only
    155     int                             fSampleCnt;     // GPU backend only
    156     ConfigFlags                     fFlags;
    157     const char*                     fName;
    158     bool                            fRunByDefault;
    159 };
    160 
    161 struct PDFRasterizerData {
    162     bool        (*fRasterizerFunction)(SkStream*, SkBitmap*);
    163     const char* fName;
    164     bool        fRunByDefault;
    165 };
    166 
    167 class BWTextDrawFilter : public SkDrawFilter {
    168 public:
    169     virtual bool filter(SkPaint*, Type) SK_OVERRIDE;
    170 };
    171 bool BWTextDrawFilter::filter(SkPaint* p, Type t) {
    172     if (kText_Type == t) {
    173         p->setAntiAlias(false);
    174     }
    175     return true;
    176 }
    177 
    178 struct PipeFlagComboData {
    179     const char* name;
    180     uint32_t flags;
    181 };
    182 
    183 static PipeFlagComboData gPipeWritingFlagCombos[] = {
    184     { "", 0 },
    185     { " cross-process", SkGPipeWriter::kCrossProcess_Flag },
    186     { " cross-process, shared address", SkGPipeWriter::kCrossProcess_Flag
    187         | SkGPipeWriter::kSharedAddressSpace_Flag }
    188 };
    189 
    190 static SkData* encode_to_dct_data(size_t* pixelRefOffset, const SkBitmap& bitmap);
    191 DECLARE_int32(pdfRasterDpi);
    192 
    193 const static ErrorCombination kDefaultIgnorableErrorTypes = ErrorCombination()
    194     .plus(kMissingExpectations_ErrorType)
    195     .plus(kIntentionallySkipped_ErrorType);
    196 
    197 class GMMain {
    198 public:
    199     GMMain() : fUseFileHierarchy(false), fWriteChecksumBasedFilenames(false),
    200                fIgnorableErrorTypes(kDefaultIgnorableErrorTypes),
    201                fMismatchPath(NULL), fMissingExpectationsPath(NULL), fTestsRun(0),
    202                fRenderModesEncountered(1) {}
    203 
    204     /**
    205      * Assemble shortNamePlusConfig from (surprise!) shortName and configName.
    206      *
    207      * The method for doing so depends on whether we are using hierarchical naming.
    208      * For example, shortName "selftest1" and configName "8888" could be assembled into
    209      * either "selftest1_8888" or "8888/selftest1".
    210      */
    211     SkString make_shortname_plus_config(const char *shortName, const char *configName) {
    212         SkString name;
    213         if (0 == strlen(configName)) {
    214             name.append(shortName);
    215         } else if (fUseFileHierarchy) {
    216             name.appendf("%s%c%s", configName, SkPATH_SEPARATOR, shortName);
    217         } else {
    218             name.appendf("%s_%s", shortName, configName);
    219         }
    220         return name;
    221     }
    222 
    223     /**
    224      * Assemble filename, suitable for writing out the results of a particular test.
    225      */
    226     SkString make_filename(const char *path,
    227                            const char *shortName,
    228                            const char *configName,
    229                            const char *renderModeDescriptor,
    230                            const char *suffix) {
    231         SkString filename = make_shortname_plus_config(shortName, configName);
    232         filename.append(renderModeDescriptor);
    233         filename.appendUnichar('.');
    234         filename.append(suffix);
    235         return SkOSPath::SkPathJoin(path, filename.c_str());
    236     }
    237 
    238     /**
    239      * Assemble filename suitable for writing out an SkBitmap.
    240      */
    241     SkString make_bitmap_filename(const char *path,
    242                                   const char *shortName,
    243                                   const char *configName,
    244                                   const char *renderModeDescriptor,
    245                                   const GmResultDigest &bitmapDigest) {
    246         if (fWriteChecksumBasedFilenames) {
    247             SkString filename;
    248             filename.append(bitmapDigest.getHashType());
    249             filename.appendUnichar('_');
    250             filename.append(shortName);
    251             filename.appendUnichar('_');
    252             filename.append(bitmapDigest.getDigestValue());
    253             filename.appendUnichar('.');
    254             filename.append(kPNG_FileExtension);
    255             return SkOSPath::SkPathJoin(path, filename.c_str());
    256         } else {
    257             return make_filename(path, shortName, configName, renderModeDescriptor,
    258                                  kPNG_FileExtension);
    259         }
    260     }
    261 
    262     /* since PNG insists on unpremultiplying our alpha, we take no
    263        precision chances and force all pixels to be 100% opaque,
    264        otherwise on compare we may not get a perfect match.
    265     */
    266     static void force_all_opaque(const SkBitmap& bitmap) {
    267         SkBitmap::Config config = bitmap.config();
    268         switch (config) {
    269         case SkBitmap::kARGB_8888_Config:
    270             force_all_opaque_8888(bitmap);
    271             break;
    272         case SkBitmap::kRGB_565_Config:
    273             // nothing to do here; 565 bitmaps are inherently opaque
    274             break;
    275         default:
    276             gm_fprintf(stderr, "unsupported bitmap config %d\n", config);
    277             DEBUGFAIL_SEE_STDERR;
    278         }
    279     }
    280 
    281     static void force_all_opaque_8888(const SkBitmap& bitmap) {
    282         SkAutoLockPixels lock(bitmap);
    283         for (int y = 0; y < bitmap.height(); y++) {
    284             for (int x = 0; x < bitmap.width(); x++) {
    285                 *bitmap.getAddr32(x, y) |= (SK_A32_MASK << SK_A32_SHIFT);
    286             }
    287         }
    288     }
    289 
    290     static ErrorCombination write_bitmap(const SkString& path, const SkBitmap& bitmap) {
    291         // TODO(epoger): Now that we have removed force_all_opaque()
    292         // from this method, we should be able to get rid of the
    293         // transformation to 8888 format also.
    294         SkBitmap copy;
    295         bitmap.copyTo(&copy, SkBitmap::kARGB_8888_Config);
    296         if (!SkImageEncoder::EncodeFile(path.c_str(), copy,
    297                                         SkImageEncoder::kPNG_Type,
    298                                         100)) {
    299             gm_fprintf(stderr, "FAILED to write bitmap: %s\n", path.c_str());
    300             return ErrorCombination(kWritingReferenceImage_ErrorType);
    301         }
    302         return kEmpty_ErrorCombination;
    303     }
    304 
    305     /**
    306      * Add all render modes encountered thus far to the "modes" array.
    307      */
    308     void GetRenderModesEncountered(SkTArray<SkString> &modes) {
    309         SkTDict<int>::Iter iter(this->fRenderModesEncountered);
    310         const char* mode;
    311         while ((mode = iter.next(NULL)) != NULL) {
    312             SkString modeAsString = SkString(mode);
    313             // TODO(epoger): It seems a bit silly that all of these modes were
    314             // recorded with a leading "-" which we have to remove here
    315             // (except for mode "", which means plain old original mode).
    316             // But that's how renderModeDescriptor has been passed into
    317             // compare_test_results_to_reference_bitmap() historically,
    318             // and changing that now may affect other parts of our code.
    319             if (modeAsString.startsWith("-")) {
    320                 modeAsString.remove(0, 1);
    321                 modes.push_back(modeAsString);
    322             }
    323         }
    324     }
    325 
    326     /**
    327      * Returns true if failures on this test should be ignored.
    328      */
    329     bool ShouldIgnoreTest(const SkString &name) const {
    330         for (int i = 0; i < fIgnorableTestSubstrings.count(); i++) {
    331             if (name.contains(fIgnorableTestSubstrings[i].c_str())) {
    332                 return true;
    333             }
    334         }
    335         return false;
    336     }
    337 
    338     /**
    339      * Records the results of this test in fTestsRun and fFailedTests.
    340      *
    341      * We even record successes, and errors that we regard as
    342      * "ignorable"; we can filter them out later.
    343      */
    344     void RecordTestResults(const ErrorCombination& errorCombination,
    345                            const SkString& shortNamePlusConfig,
    346                            const char renderModeDescriptor []) {
    347         // Things to do regardless of errorCombination.
    348         fTestsRun++;
    349         int renderModeCount = 0;
    350         this->fRenderModesEncountered.find(renderModeDescriptor, &renderModeCount);
    351         renderModeCount++;
    352         this->fRenderModesEncountered.set(renderModeDescriptor, renderModeCount);
    353 
    354         if (errorCombination.isEmpty()) {
    355             return;
    356         }
    357 
    358         // Things to do only if there is some error condition.
    359         SkString fullName = shortNamePlusConfig;
    360         fullName.append(renderModeDescriptor);
    361         for (int typeInt = 0; typeInt <= kLast_ErrorType; typeInt++) {
    362             ErrorType type = static_cast<ErrorType>(typeInt);
    363             if (errorCombination.includes(type)) {
    364                 fFailedTests[type].push_back(fullName);
    365             }
    366         }
    367     }
    368 
    369     /**
    370      * Return the number of significant (non-ignorable) errors we have
    371      * encountered so far.
    372      */
    373     int NumSignificantErrors() {
    374         int significantErrors = 0;
    375         for (int typeInt = 0; typeInt <= kLast_ErrorType; typeInt++) {
    376             ErrorType type = static_cast<ErrorType>(typeInt);
    377             if (!fIgnorableErrorTypes.includes(type)) {
    378                 significantErrors += fFailedTests[type].count();
    379             }
    380         }
    381         return significantErrors;
    382     }
    383 
    384     /**
    385      * Display the summary of results with this ErrorType.
    386      *
    387      * @param type which ErrorType
    388      * @param verbose whether to be all verbose about it
    389      */
    390     void DisplayResultTypeSummary(ErrorType type, bool verbose) {
    391         bool isIgnorableType = fIgnorableErrorTypes.includes(type);
    392 
    393         SkString line;
    394         if (isIgnorableType) {
    395             line.append("[ ] ");
    396         } else {
    397             line.append("[*] ");
    398         }
    399 
    400         SkTArray<SkString> *failedTestsOfThisType = &fFailedTests[type];
    401         int count = failedTestsOfThisType->count();
    402         line.appendf("%d %s", count, getErrorTypeName(type));
    403         if (!isIgnorableType || verbose) {
    404             line.append(":");
    405             for (int i = 0; i < count; ++i) {
    406                 line.append(" ");
    407                 line.append((*failedTestsOfThisType)[i]);
    408             }
    409         }
    410         gm_fprintf(stdout, "%s\n", line.c_str());
    411     }
    412 
    413     /**
    414      * List contents of fFailedTests to stdout.
    415      *
    416      * @param verbose whether to be all verbose about it
    417      */
    418     void ListErrors(bool verbose) {
    419         // First, print a single summary line.
    420         SkString summary;
    421         summary.appendf("Ran %d tests:", fTestsRun);
    422         for (int typeInt = 0; typeInt <= kLast_ErrorType; typeInt++) {
    423             ErrorType type = static_cast<ErrorType>(typeInt);
    424             summary.appendf(" %s=%d", getErrorTypeName(type), fFailedTests[type].count());
    425         }
    426         gm_fprintf(stdout, "%s\n", summary.c_str());
    427 
    428         // Now, for each failure type, list the tests that failed that way.
    429         for (int typeInt = 0; typeInt <= kLast_ErrorType; typeInt++) {
    430             this->DisplayResultTypeSummary(static_cast<ErrorType>(typeInt), verbose);
    431         }
    432         gm_fprintf(stdout, "(results marked with [*] will cause nonzero return value)\n");
    433     }
    434 
    435     static ErrorCombination write_document(const SkString& path, SkStreamAsset* asset) {
    436         SkFILEWStream stream(path.c_str());
    437         if (!stream.writeStream(asset, asset->getLength())) {
    438             gm_fprintf(stderr, "FAILED to write document: %s\n", path.c_str());
    439             return ErrorCombination(kWritingReferenceImage_ErrorType);
    440         }
    441         return kEmpty_ErrorCombination;
    442     }
    443 
    444     /**
    445      * Prepare an SkBitmap to render a GM into.
    446      *
    447      * After you've rendered the GM into the SkBitmap, you must call
    448      * complete_bitmap()!
    449      *
    450      * @todo thudson 22 April 2011 - could refactor this to take in
    451      * a factory to generate the context, always call readPixels()
    452      * (logically a noop for rasters, if wasted time), and thus collapse the
    453      * GPU special case and also let this be used for SkPicture testing.
    454      */
    455     static void setup_bitmap(const ConfigData& gRec, SkISize& size,
    456                              SkBitmap* bitmap) {
    457         bitmap->setConfig(gRec.fConfig, size.width(), size.height());
    458         bitmap->allocPixels();
    459         bitmap->eraseColor(SK_ColorTRANSPARENT);
    460     }
    461 
    462     /**
    463      * Any finalization steps we need to perform on the SkBitmap after
    464      * we have rendered the GM into it.
    465      *
    466      * It's too bad that we are throwing away alpha channel data
    467      * we could otherwise be examining, but this had always been happening
    468      * before... it was buried within the compare() method at
    469      * https://code.google.com/p/skia/source/browse/trunk/gm/gmmain.cpp?r=7289#305 .
    470      *
    471      * Apparently we need this, at least for bitmaps that are either:
    472      * (a) destined to be written out as PNG files, or
    473      * (b) compared against bitmaps read in from PNG files
    474      * for the reasons described just above the force_all_opaque() method.
    475      *
    476      * Neglecting to do this led to the difficult-to-diagnose
    477      * http://code.google.com/p/skia/issues/detail?id=1079 ('gm generating
    478      * spurious pixel_error messages as of r7258')
    479      *
    480      * TODO(epoger): Come up with a better solution that allows us to
    481      * compare full pixel data, including alpha channel, while still being
    482      * robust in the face of transformations to/from PNG files.
    483      * Options include:
    484      *
    485      * 1. Continue to call force_all_opaque(), but ONLY for bitmaps that
    486      *    will be written to, or compared against, PNG files.
    487      *    PRO: Preserve/compare alpha channel info for the non-PNG cases
    488      *         (comparing different renderModes in-memory)
    489      *    CON: The bitmaps (and hash digests) for these non-PNG cases would be
    490      *         different than those for the PNG-compared cases, and in the
    491      *         case of a failed renderMode comparison, how would we write the
    492      *         image to disk for examination?
    493      *
    494      * 2. Always compute image hash digests from PNG format (either
    495      *    directly from the the bytes of a PNG file, or capturing the
    496      *    bytes we would have written to disk if we were writing the
    497      *    bitmap out as a PNG).
    498      *    PRO: I think this would allow us to never force opaque, and to
    499      *         the extent that alpha channel data can be preserved in a PNG
    500      *         file, we could observe it.
    501      *    CON: If we read a bitmap from disk, we need to take its hash digest
    502      *         from the source PNG (we can't compute it from the bitmap we
    503      *         read out of the PNG, because we will have already premultiplied
    504      *         the alpha).
    505      *    CON: Seems wasteful to convert a bitmap to PNG format just to take
    506      *         its hash digest. (Although we're wasting lots of effort already
    507      *         calling force_all_opaque().)
    508      *
    509      * 3. Make the alpha premultiply/unpremultiply routines 100% consistent,
    510      *    so we can transform images back and forth without fear of off-by-one
    511      *    errors.
    512      *    CON: Math is hard.
    513      *
    514      * 4. Perform a "close enough" comparison of bitmaps (+/- 1 bit in each
    515      *    channel), rather than demanding absolute equality.
    516      *    CON: Can't do this with hash digests.
    517      */
    518     static void complete_bitmap(SkBitmap* bitmap) {
    519         force_all_opaque(*bitmap);
    520     }
    521 
    522     static void installFilter(SkCanvas* canvas);
    523 
    524     static void invokeGM(GM* gm, SkCanvas* canvas, bool isPDF, bool isDeferred) {
    525         SkAutoCanvasRestore acr(canvas, true);
    526 
    527         if (!isPDF) {
    528             canvas->concat(gm->getInitialTransform());
    529         }
    530         installFilter(canvas);
    531         gm->setCanvasIsDeferred(isDeferred);
    532         gm->draw(canvas);
    533         canvas->setDrawFilter(NULL);
    534     }
    535 
    536     static ErrorCombination generate_image(GM* gm, const ConfigData& gRec,
    537                                            GrSurface* gpuTarget,
    538                                            SkBitmap* bitmap,
    539                                            bool deferred) {
    540         SkISize size (gm->getISize());
    541         setup_bitmap(gRec, size, bitmap);
    542 
    543         SkAutoTUnref<SkCanvas> canvas;
    544 
    545         if (gRec.fBackend == kRaster_Backend) {
    546             SkAutoTUnref<SkBaseDevice> device(SkNEW_ARGS(SkBitmapDevice, (*bitmap)));
    547             if (deferred) {
    548                 canvas.reset(SkDeferredCanvas::Create(device));
    549             } else {
    550                 canvas.reset(SkNEW_ARGS(SkCanvas, (device)));
    551             }
    552             invokeGM(gm, canvas, false, deferred);
    553             canvas->flush();
    554         }
    555 #if SK_SUPPORT_GPU
    556         else {  // GPU
    557             SkAutoTUnref<SkBaseDevice> device(SkGpuDevice::Create(gpuTarget));
    558             if (deferred) {
    559                 canvas.reset(SkDeferredCanvas::Create(device));
    560             } else {
    561                 canvas.reset(SkNEW_ARGS(SkCanvas, (device)));
    562             }
    563             invokeGM(gm, canvas, false, deferred);
    564             // the device is as large as the current rendertarget, so
    565             // we explicitly only readback the amount we expect (in
    566             // size) overwrite our previous allocation
    567             bitmap->setConfig(SkBitmap::kARGB_8888_Config, size.fWidth,
    568                               size.fHeight);
    569             canvas->readPixels(bitmap, 0, 0);
    570         }
    571 #endif
    572         complete_bitmap(bitmap);
    573         return kEmpty_ErrorCombination;
    574     }
    575 
    576     static void generate_image_from_picture(GM* gm, const ConfigData& gRec,
    577                                             SkPicture* pict, SkBitmap* bitmap,
    578                                             SkScalar scale = SK_Scalar1,
    579                                             bool tile = false) {
    580         SkISize size = gm->getISize();
    581         setup_bitmap(gRec, size, bitmap);
    582 
    583         if (tile) {
    584             // Generate the result image by rendering to tiles and accumulating
    585             // the results in 'bitmap'
    586 
    587             // This 16x16 tiling matches the settings applied to 'pict' in
    588             // 'generate_new_picture'
    589             SkISize tileSize = SkISize::Make(16, 16);
    590 
    591             SkBitmap tileBM;
    592             setup_bitmap(gRec, tileSize, &tileBM);
    593             SkCanvas tileCanvas(tileBM);
    594             installFilter(&tileCanvas);
    595 
    596             SkCanvas bmpCanvas(*bitmap);
    597             SkPaint bmpPaint;
    598             bmpPaint.setXfermodeMode(SkXfermode::kSrc_Mode);
    599 
    600             for (int yTile = 0; yTile < (size.height()+15)/16; ++yTile) {
    601                 for (int xTile = 0; xTile < (size.width()+15)/16; ++xTile) {
    602                     int saveCount = tileCanvas.save();
    603                     SkMatrix mat(tileCanvas.getTotalMatrix());
    604                     mat.postTranslate(SkIntToScalar(-xTile*tileSize.width()),
    605                                       SkIntToScalar(-yTile*tileSize.height()));
    606                     tileCanvas.setMatrix(mat);
    607                     pict->draw(&tileCanvas);
    608                     tileCanvas.flush();
    609                     tileCanvas.restoreToCount(saveCount);
    610                     bmpCanvas.drawBitmap(tileBM,
    611                                          SkIntToScalar(xTile * tileSize.width()),
    612                                          SkIntToScalar(yTile * tileSize.height()),
    613                                          &bmpPaint);
    614                 }
    615             }
    616         } else {
    617             SkCanvas canvas(*bitmap);
    618             installFilter(&canvas);
    619             canvas.scale(scale, scale);
    620             canvas.drawPicture(*pict);
    621             complete_bitmap(bitmap);
    622         }
    623     }
    624 
    625     static bool generate_pdf(GM* gm, SkDynamicMemoryWStream& pdf) {
    626 #ifdef SK_SUPPORT_PDF
    627         SkMatrix initialTransform = gm->getInitialTransform();
    628         if (FLAGS_useDocumentInsteadOfDevice) {
    629             SkISize pageISize = gm->getISize();
    630             SkAutoTUnref<SkDocument> pdfDoc(
    631                     SkDocument::CreatePDF(&pdf, NULL,
    632                                           encode_to_dct_data,
    633                                           SkIntToScalar(FLAGS_pdfRasterDpi)));
    634 
    635             if (!pdfDoc.get()) {
    636                 return false;
    637             }
    638 
    639             SkCanvas* canvas = NULL;
    640             canvas = pdfDoc->beginPage(SkIntToScalar(pageISize.width()),
    641                                        SkIntToScalar(pageISize.height()));
    642             canvas->concat(initialTransform);
    643 
    644             invokeGM(gm, canvas, true, false);
    645 
    646             return pdfDoc->close();
    647         } else {
    648             SkISize pageSize = gm->getISize();
    649             SkPDFDevice* dev = NULL;
    650             if (initialTransform.isIdentity()) {
    651                 dev = new SkPDFDevice(pageSize, pageSize, initialTransform);
    652             } else {
    653                 SkRect content = SkRect::MakeWH(SkIntToScalar(pageSize.width()),
    654                                                 SkIntToScalar(pageSize.height()));
    655                 initialTransform.mapRect(&content);
    656                 content.intersect(0, 0, SkIntToScalar(pageSize.width()),
    657                                   SkIntToScalar(pageSize.height()));
    658                 SkISize contentSize =
    659                     SkISize::Make(SkScalarRoundToInt(content.width()),
    660                                   SkScalarRoundToInt(content.height()));
    661                 dev = new SkPDFDevice(pageSize, contentSize, initialTransform);
    662             }
    663             dev->setDCTEncoder(encode_to_dct_data);
    664             dev->setRasterDpi(SkIntToScalar(FLAGS_pdfRasterDpi));
    665             SkAutoUnref aur(dev);
    666             SkCanvas c(dev);
    667             invokeGM(gm, &c, true, false);
    668             SkPDFDocument doc;
    669             doc.appendPage(dev);
    670             doc.emitPDF(&pdf);
    671         }
    672 #endif  // SK_SUPPORT_PDF
    673         return true; // Do not report failure if pdf is not supported.
    674     }
    675 
    676     static void generate_xps(GM* gm, SkDynamicMemoryWStream& xps) {
    677 #ifdef SK_SUPPORT_XPS
    678         SkISize size = gm->getISize();
    679 
    680         SkSize trimSize = SkSize::Make(SkIntToScalar(size.width()),
    681                                        SkIntToScalar(size.height()));
    682         static const SkScalar inchesPerMeter = SkScalarDiv(10000, 254);
    683         static const SkScalar upm = 72 * inchesPerMeter;
    684         SkVector unitsPerMeter = SkPoint::Make(upm, upm);
    685         static const SkScalar ppm = 200 * inchesPerMeter;
    686         SkVector pixelsPerMeter = SkPoint::Make(ppm, ppm);
    687 
    688         SkXPSDevice* dev = new SkXPSDevice();
    689         SkAutoUnref aur(dev);
    690 
    691         SkCanvas c(dev);
    692         dev->beginPortfolio(&xps);
    693         dev->beginSheet(unitsPerMeter, pixelsPerMeter, trimSize);
    694         invokeGM(gm, &c, false, false);
    695         dev->endSheet();
    696         dev->endPortfolio();
    697 
    698 #endif
    699     }
    700 
    701     /**
    702      * Log more detail about the mistmatch between expectedBitmap and
    703      * actualBitmap.
    704      */
    705     void report_bitmap_diffs(const SkBitmap& expectedBitmap, const SkBitmap& actualBitmap,
    706                              const char *testName) {
    707         const int expectedWidth = expectedBitmap.width();
    708         const int expectedHeight = expectedBitmap.height();
    709         const int width = actualBitmap.width();
    710         const int height = actualBitmap.height();
    711         if ((expectedWidth != width) || (expectedHeight != height)) {
    712             gm_fprintf(stderr, "---- %s: dimension mismatch --"
    713                        " expected [%d %d], actual [%d %d]\n",
    714                        testName, expectedWidth, expectedHeight, width, height);
    715             return;
    716         }
    717 
    718         if ((SkBitmap::kARGB_8888_Config != expectedBitmap.config()) ||
    719             (SkBitmap::kARGB_8888_Config != actualBitmap.config())) {
    720             gm_fprintf(stderr, "---- %s: not computing max per-channel"
    721                        " pixel mismatch because non-8888\n", testName);
    722             return;
    723         }
    724 
    725         SkAutoLockPixels alp0(expectedBitmap);
    726         SkAutoLockPixels alp1(actualBitmap);
    727         int errR = 0;
    728         int errG = 0;
    729         int errB = 0;
    730         int errA = 0;
    731         int differingPixels = 0;
    732 
    733         for (int y = 0; y < height; ++y) {
    734             const SkPMColor* expectedPixelPtr = expectedBitmap.getAddr32(0, y);
    735             const SkPMColor* actualPixelPtr = actualBitmap.getAddr32(0, y);
    736             for (int x = 0; x < width; ++x) {
    737                 SkPMColor expectedPixel = *expectedPixelPtr++;
    738                 SkPMColor actualPixel = *actualPixelPtr++;
    739                 if (expectedPixel != actualPixel) {
    740                     differingPixels++;
    741                     errR = SkMax32(errR, SkAbs32((int)SkGetPackedR32(expectedPixel) -
    742                                                  (int)SkGetPackedR32(actualPixel)));
    743                     errG = SkMax32(errG, SkAbs32((int)SkGetPackedG32(expectedPixel) -
    744                                                  (int)SkGetPackedG32(actualPixel)));
    745                     errB = SkMax32(errB, SkAbs32((int)SkGetPackedB32(expectedPixel) -
    746                                                  (int)SkGetPackedB32(actualPixel)));
    747                     errA = SkMax32(errA, SkAbs32((int)SkGetPackedA32(expectedPixel) -
    748                                                  (int)SkGetPackedA32(actualPixel)));
    749                 }
    750             }
    751         }
    752         gm_fprintf(stderr, "---- %s: %d (of %d) differing pixels,"
    753                    " max per-channel mismatch R=%d G=%d B=%d A=%d\n",
    754                    testName, differingPixels, width*height, errR, errG, errB, errA);
    755     }
    756 
    757     /**
    758      * Compares actual hash digest to expectations, returning the set of errors
    759      * (if any) that we saw along the way.
    760      *
    761      * If fMismatchPath has been set, and there are pixel diffs, then the
    762      * actual bitmap will be written out to a file within fMismatchPath.
    763      * And similarly for fMissingExpectationsPath...
    764      *
    765      * @param expectations what expectations to compare actualBitmap against
    766      * @param actualBitmapAndDigest the SkBitmap we actually generated, and its GmResultDigest
    767      * @param shortName name of test, e.g. "selftest1"
    768      * @param configName name of config, e.g. "8888"
    769      * @param renderModeDescriptor e.g., "-rtree", "-deferred"
    770      * @param addToJsonSummary whether to add these results (both actual and
    771      *        expected) to the JSON summary. Regardless of this setting, if
    772      *        we find an image mismatch in this test, we will write these
    773      *        results to the JSON summary.  (This is so that we will always
    774      *        report errors across rendering modes, such as pipe vs tiled.
    775      *        See https://codereview.chromium.org/13650002/ )
    776      */
    777     ErrorCombination compare_to_expectations(Expectations expectations,
    778                                              const BitmapAndDigest& actualBitmapAndDigest,
    779                                              const char *shortName, const char *configName,
    780                                              const char *renderModeDescriptor,
    781                                              bool addToJsonSummary) {
    782         ErrorCombination errors;
    783         SkString shortNamePlusConfig = make_shortname_plus_config(shortName, configName);
    784         SkString completeNameString(shortNamePlusConfig);
    785         completeNameString.append(renderModeDescriptor);
    786         completeNameString.append(".");
    787         completeNameString.append(kPNG_FileExtension);
    788         const char* completeName = completeNameString.c_str();
    789 
    790         if (expectations.empty()) {
    791             errors.add(kMissingExpectations_ErrorType);
    792 
    793             // Write out the "actuals" for any tests without expectations, if we have
    794             // been directed to do so.
    795             if (fMissingExpectationsPath) {
    796                 SkString path = make_bitmap_filename(fMissingExpectationsPath, shortName,
    797                                                      configName, renderModeDescriptor,
    798                                                      actualBitmapAndDigest.fDigest);
    799                 write_bitmap(path, actualBitmapAndDigest.fBitmap);
    800             }
    801 
    802         } else if (!expectations.match(actualBitmapAndDigest.fDigest)) {
    803             addToJsonSummary = true;
    804             // The error mode we record depends on whether this was running
    805             // in a non-standard renderMode.
    806             if ('\0' == *renderModeDescriptor) {
    807                 errors.add(kExpectationsMismatch_ErrorType);
    808             } else {
    809                 errors.add(kRenderModeMismatch_ErrorType);
    810             }
    811 
    812             // Write out the "actuals" for any mismatches, if we have
    813             // been directed to do so.
    814             if (fMismatchPath) {
    815                 SkString path = make_bitmap_filename(fMismatchPath, shortName, configName,
    816                                                      renderModeDescriptor,
    817                                                      actualBitmapAndDigest.fDigest);
    818                 write_bitmap(path, actualBitmapAndDigest.fBitmap);
    819             }
    820 
    821             // If we have access to a single expected bitmap, log more
    822             // detail about the mismatch.
    823             const SkBitmap *expectedBitmapPtr = expectations.asBitmap();
    824             if (NULL != expectedBitmapPtr) {
    825                 report_bitmap_diffs(*expectedBitmapPtr, actualBitmapAndDigest.fBitmap,
    826                                     completeName);
    827             }
    828         }
    829 
    830         if (addToJsonSummary) {
    831             add_actual_results_to_json_summary(completeName, actualBitmapAndDigest.fDigest, errors,
    832                                                expectations.ignoreFailure());
    833             add_expected_results_to_json_summary(completeName, expectations);
    834         }
    835 
    836         return errors;
    837     }
    838 
    839     /**
    840      * Add this result to the appropriate JSON collection of actual results (but just ONE),
    841      * depending on errors encountered.
    842      */
    843     void add_actual_results_to_json_summary(const char testName[],
    844                                             const GmResultDigest &actualResultDigest,
    845                                             ErrorCombination errors,
    846                                             bool ignoreFailure) {
    847         Json::Value jsonActualResults = actualResultDigest.asJsonTypeValuePair();
    848         Json::Value *resultCollection = NULL;
    849 
    850         if (errors.isEmpty()) {
    851             resultCollection = &this->fJsonActualResults_Succeeded;
    852         } else if (errors.includes(kRenderModeMismatch_ErrorType)) {
    853             resultCollection = &this->fJsonActualResults_Failed;
    854         } else if (errors.includes(kExpectationsMismatch_ErrorType)) {
    855             if (ignoreFailure) {
    856                 resultCollection = &this->fJsonActualResults_FailureIgnored;
    857             } else {
    858                 resultCollection = &this->fJsonActualResults_Failed;
    859             }
    860         } else if (errors.includes(kMissingExpectations_ErrorType)) {
    861             // TODO: What about the case where there IS an expected
    862             // image hash digest, but that gm test doesn't actually
    863             // run?  For now, those cases will always be ignored,
    864             // because gm only looks at expectations that correspond
    865             // to gm tests that were actually run.
    866             //
    867             // Once we have the ability to express expectations as a
    868             // JSON file, we should fix this (and add a test case for
    869             // which an expectation is given but the test is never
    870             // run).
    871             resultCollection = &this->fJsonActualResults_NoComparison;
    872         }
    873 
    874         // If none of the above cases match, we don't add it to ANY tally of actual results.
    875         if (resultCollection) {
    876             (*resultCollection)[testName] = jsonActualResults;
    877         }
    878     }
    879 
    880     /**
    881      * Add this test to the JSON collection of expected results.
    882      */
    883     void add_expected_results_to_json_summary(const char testName[],
    884                                               Expectations expectations) {
    885         this->fJsonExpectedResults[testName] = expectations.asJsonValue();
    886     }
    887 
    888     /**
    889      * Compare actualBitmap to expectations stored in this->fExpectationsSource.
    890      *
    891      * @param gm which test generated the actualBitmap
    892      * @param gRec
    893      * @param configName The config name to look for in the expectation file.
    894      * @param actualBitmapAndDigest ptr to bitmap generated by this run, or NULL
    895      *        if we don't have a usable bitmap representation
    896      */
    897     ErrorCombination compare_test_results_to_stored_expectations(
    898         GM* gm, const ConfigData& gRec, const char* configName,
    899         const BitmapAndDigest* actualBitmapAndDigest) {
    900 
    901         SkString shortNamePlusConfig = make_shortname_plus_config(gm->shortName(), configName);
    902 
    903         ErrorCombination errors;
    904 
    905         if (NULL == actualBitmapAndDigest) {
    906             // Note that we intentionally skipped validating the results for
    907             // this test, because we don't know how to generate an SkBitmap
    908             // version of the output.
    909             errors.add(ErrorCombination(kIntentionallySkipped_ErrorType));
    910         } else if (!(gRec.fFlags & kWrite_ConfigFlag)) {
    911             // We don't record the results for this test or compare them
    912             // against any expectations, because the output image isn't
    913             // meaningful.
    914             // See https://code.google.com/p/skia/issues/detail?id=1410 ('some
    915             // GM result images not available for download from Google Storage')
    916             errors.add(ErrorCombination(kIntentionallySkipped_ErrorType));
    917         } else {
    918             ExpectationsSource *expectationsSource = this->fExpectationsSource.get();
    919             SkString nameWithExtension(shortNamePlusConfig);
    920             nameWithExtension.append(".");
    921             nameWithExtension.append(kPNG_FileExtension);
    922 
    923             if (expectationsSource && (gRec.fFlags & kRead_ConfigFlag)) {
    924                 /*
    925                  * Get the expected results for this test, as one or more allowed
    926                  * hash digests. The current implementation of expectationsSource
    927                  * get this by computing the hash digest of a single PNG file on disk.
    928                  *
    929                  * TODO(epoger): This relies on the fact that
    930                  * force_all_opaque() was called on the bitmap before it
    931                  * was written to disk as a PNG in the first place. If
    932                  * not, the hash digest returned here may not match the
    933                  * hash digest of actualBitmap, which *has* been run through
    934                  * force_all_opaque().
    935                  * See comments above complete_bitmap() for more detail.
    936                  */
    937                 Expectations expectations = expectationsSource->get(nameWithExtension.c_str());
    938                 if (this->ShouldIgnoreTest(shortNamePlusConfig)) {
    939                     expectations.setIgnoreFailure(true);
    940                 }
    941                 errors.add(compare_to_expectations(expectations, *actualBitmapAndDigest,
    942                                                    gm->shortName(), configName, "", true));
    943             } else {
    944                 // If we are running without expectations, we still want to
    945                 // record the actual results.
    946                 add_actual_results_to_json_summary(nameWithExtension.c_str(),
    947                                                    actualBitmapAndDigest->fDigest,
    948                                                    ErrorCombination(kMissingExpectations_ErrorType),
    949                                                    false);
    950                 errors.add(ErrorCombination(kMissingExpectations_ErrorType));
    951             }
    952         }
    953         return errors;
    954     }
    955 
    956     /**
    957      * Compare actualBitmap to referenceBitmap.
    958      *
    959      * @param shortName test name, e.g. "selftest1"
    960      * @param configName configuration name, e.g. "8888"
    961      * @param renderModeDescriptor
    962      * @param actualBitmap actual bitmap generated by this run
    963      * @param referenceBitmap bitmap we expected to be generated
    964      */
    965     ErrorCombination compare_test_results_to_reference_bitmap(
    966         const char *shortName, const char *configName, const char *renderModeDescriptor,
    967         SkBitmap& actualBitmap, const SkBitmap* referenceBitmap) {
    968 
    969         SkASSERT(referenceBitmap);
    970         Expectations expectations(*referenceBitmap);
    971         BitmapAndDigest actualBitmapAndDigest(actualBitmap);
    972 
    973         // TODO: Eliminate RecordTestResults from here.
    974         // Results recording code for the test_drawing path has been refactored so that
    975         // RecordTestResults is only called once, at the topmost level. However, the
    976         // other paths have not yet been refactored, and RecordTestResults has been added
    977         // here to maintain proper behavior for calls not coming from the test_drawing path.
    978         ErrorCombination errors;
    979         errors.add(compare_to_expectations(expectations, actualBitmapAndDigest, shortName,
    980                                            configName, renderModeDescriptor, false));
    981         SkString shortNamePlusConfig = make_shortname_plus_config(shortName, configName);
    982         RecordTestResults(errors, shortNamePlusConfig, renderModeDescriptor);
    983 
    984         return errors;
    985     }
    986 
    987     static SkPicture* generate_new_picture(GM* gm, BbhType bbhType, uint32_t recordFlags,
    988                                            SkScalar scale = SK_Scalar1) {
    989         // Pictures are refcounted so must be on heap
    990         SkPicture* pict;
    991         int width = SkScalarCeilToInt(SkScalarMul(SkIntToScalar(gm->getISize().width()), scale));
    992         int height = SkScalarCeilToInt(SkScalarMul(SkIntToScalar(gm->getISize().height()), scale));
    993 
    994         if (kTileGrid_BbhType == bbhType) {
    995             SkTileGridPicture::TileGridInfo info;
    996             info.fMargin.setEmpty();
    997             info.fOffset.setZero();
    998             info.fTileInterval.set(16, 16);
    999             pict = new SkTileGridPicture(width, height, info);
   1000         } else {
   1001             pict = new SkPicture;
   1002         }
   1003         if (kNone_BbhType != bbhType) {
   1004             recordFlags |= SkPicture::kOptimizeForClippedPlayback_RecordingFlag;
   1005         }
   1006         SkCanvas* cv = pict->beginRecording(width, height, recordFlags);
   1007         cv->scale(scale, scale);
   1008         invokeGM(gm, cv, false, false);
   1009         pict->endRecording();
   1010 
   1011         return pict;
   1012     }
   1013 
   1014     static SkData* bitmap_encoder(size_t* pixelRefOffset, const SkBitmap& bm) {
   1015         SkPixelRef* pr = bm.pixelRef();
   1016         if (pr != NULL) {
   1017             SkData* data = pr->refEncodedData();
   1018             if (data != NULL) {
   1019                 *pixelRefOffset = bm.pixelRefOffset();
   1020                 return data;
   1021             }
   1022         }
   1023         return NULL;
   1024     }
   1025 
   1026     static SkPicture* stream_to_new_picture(const SkPicture& src) {
   1027         SkDynamicMemoryWStream storage;
   1028         src.serialize(&storage, &bitmap_encoder);
   1029         SkAutoTUnref<SkStreamAsset> pictReadback(storage.detachAsStream());
   1030         SkPicture* retval = SkPicture::CreateFromStream(pictReadback,
   1031                                                         &SkImageDecoder::DecodeMemory);
   1032         return retval;
   1033     }
   1034 
   1035     // Test: draw into a bitmap or pdf.
   1036     // Depending on flags, possibly compare to an expected image.
   1037     // If writePath is not NULL, also write images (or documents) to the specified path.
   1038     ErrorCombination test_drawing(GM* gm, const ConfigData& gRec,
   1039                                   const SkTDArray<const PDFRasterizerData*> &pdfRasterizers,
   1040                                   const char writePath [],
   1041                                   GrSurface* gpuTarget,
   1042                                   SkBitmap* bitmap) {
   1043         ErrorCombination errors;
   1044         SkDynamicMemoryWStream document;
   1045         SkString path;
   1046 
   1047         if (gRec.fBackend == kRaster_Backend ||
   1048             gRec.fBackend == kGPU_Backend) {
   1049             // Early exit if we can't generate the image.
   1050             errors.add(generate_image(gm, gRec, gpuTarget, bitmap, false));
   1051             if (!errors.isEmpty()) {
   1052                 // TODO: Add a test to exercise what the stdout and
   1053                 // JSON look like if we get an "early error" while
   1054                 // trying to generate the image.
   1055                 return errors;
   1056             }
   1057             BitmapAndDigest bitmapAndDigest(*bitmap);
   1058             errors.add(compare_test_results_to_stored_expectations(
   1059                            gm, gRec, gRec.fName, &bitmapAndDigest));
   1060 
   1061             if (writePath && (gRec.fFlags & kWrite_ConfigFlag)) {
   1062                 path = make_bitmap_filename(writePath, gm->shortName(), gRec.fName,
   1063                                             "", bitmapAndDigest.fDigest);
   1064                 errors.add(write_bitmap(path, bitmapAndDigest.fBitmap));
   1065             }
   1066         } else if (gRec.fBackend == kPDF_Backend) {
   1067             if (!generate_pdf(gm, document)) {
   1068                 errors.add(kGeneratePdfFailed_ErrorType);
   1069             } else {
   1070                 SkAutoTUnref<SkStreamAsset> documentStream(document.detachAsStream());
   1071                 if (writePath && (gRec.fFlags & kWrite_ConfigFlag)) {
   1072                     path = make_filename(writePath, gm->shortName(), gRec.fName, "", "pdf");
   1073                     errors.add(write_document(path, documentStream));
   1074                 }
   1075 
   1076                 if (!(gm->getFlags() & GM::kSkipPDFRasterization_Flag)) {
   1077                     for (int i = 0; i < pdfRasterizers.count(); i++) {
   1078                         SkBitmap pdfBitmap;
   1079                         documentStream->rewind();
   1080                         bool success = (*pdfRasterizers[i]->fRasterizerFunction)(
   1081                                 documentStream.get(), &pdfBitmap);
   1082                         if (!success) {
   1083                             gm_fprintf(stderr, "FAILED to render PDF for %s using renderer %s\n",
   1084                                        gm->shortName(),
   1085                                        pdfRasterizers[i]->fName);
   1086                             continue;
   1087                         }
   1088 
   1089                         SkString configName(gRec.fName);
   1090                         configName.append("-");
   1091                         configName.append(pdfRasterizers[i]->fName);
   1092 
   1093                         BitmapAndDigest bitmapAndDigest(pdfBitmap);
   1094                         errors.add(compare_test_results_to_stored_expectations(
   1095                                    gm, gRec, configName.c_str(), &bitmapAndDigest));
   1096 
   1097                         if (writePath && (gRec.fFlags & kWrite_ConfigFlag)) {
   1098                             path = make_bitmap_filename(writePath, gm->shortName(),
   1099                                                         configName.c_str(),
   1100                                                         "", bitmapAndDigest.fDigest);
   1101                             errors.add(write_bitmap(path, bitmapAndDigest.fBitmap));
   1102                         }
   1103                     }
   1104                 } else {
   1105                     errors.add(kIntentionallySkipped_ErrorType);
   1106                 }
   1107             }
   1108         } else if (gRec.fBackend == kXPS_Backend) {
   1109             generate_xps(gm, document);
   1110             SkAutoTUnref<SkStreamAsset> documentStream(document.detachAsStream());
   1111 
   1112             errors.add(compare_test_results_to_stored_expectations(
   1113                            gm, gRec, gRec.fName, NULL));
   1114 
   1115             if (writePath && (gRec.fFlags & kWrite_ConfigFlag)) {
   1116                 path = make_filename(writePath, gm->shortName(), gRec.fName, "", "xps");
   1117                 errors.add(write_document(path, documentStream));
   1118             }
   1119         } else {
   1120             SkASSERT(false);
   1121         }
   1122         return errors;
   1123     }
   1124 
   1125     ErrorCombination test_deferred_drawing(GM* gm,
   1126                                            const ConfigData& gRec,
   1127                                            const SkBitmap& referenceBitmap,
   1128                                            GrSurface* gpuTarget) {
   1129         if (gRec.fBackend == kRaster_Backend ||
   1130             gRec.fBackend == kGPU_Backend) {
   1131             const char renderModeDescriptor[] = "-deferred";
   1132             SkBitmap bitmap;
   1133             // Early exit if we can't generate the image, but this is
   1134             // expected in some cases, so don't report a test failure.
   1135             ErrorCombination errors = generate_image(gm, gRec, gpuTarget, &bitmap, true);
   1136             // TODO(epoger): This logic is the opposite of what is
   1137             // described above... if we succeeded in generating the
   1138             // -deferred image, we exit early!  We should fix this
   1139             // ASAP, because it is hiding -deferred errors... but for
   1140             // now, I'm leaving the logic as it is so that the
   1141             // refactoring change
   1142             // https://codereview.chromium.org/12992003/ is unblocked.
   1143             //
   1144             // Filed as https://code.google.com/p/skia/issues/detail?id=1180
   1145             // ('image-surface gm test is failing in "deferred" mode,
   1146             // and gm is not reporting the failure')
   1147             if (errors.isEmpty()) {
   1148                 // TODO(epoger): Report this as a new ErrorType,
   1149                 // something like kImageGeneration_ErrorType?
   1150                 return kEmpty_ErrorCombination;
   1151             }
   1152             return compare_test_results_to_reference_bitmap(
   1153                 gm->shortName(), gRec.fName, renderModeDescriptor, bitmap, &referenceBitmap);
   1154         }
   1155         return kEmpty_ErrorCombination;
   1156     }
   1157 
   1158     ErrorCombination test_pipe_playback(GM* gm, const ConfigData& gRec,
   1159                                         const SkBitmap& referenceBitmap, bool simulateFailure) {
   1160         const SkString shortNamePlusConfig = make_shortname_plus_config(gm->shortName(),
   1161                                                                         gRec.fName);
   1162         ErrorCombination errors;
   1163         for (size_t i = 0; i < SK_ARRAY_COUNT(gPipeWritingFlagCombos); ++i) {
   1164             SkString renderModeDescriptor("-pipe");
   1165             renderModeDescriptor.append(gPipeWritingFlagCombos[i].name);
   1166 
   1167             if (gm->getFlags() & GM::kSkipPipe_Flag
   1168                 || (gPipeWritingFlagCombos[i].flags == SkGPipeWriter::kCrossProcess_Flag
   1169                     && gm->getFlags() & GM::kSkipPipeCrossProcess_Flag)) {
   1170                 RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1171                                   renderModeDescriptor.c_str());
   1172                 errors.add(kIntentionallySkipped_ErrorType);
   1173             } else {
   1174                 SkBitmap bitmap;
   1175                 SkISize size = gm->getISize();
   1176                 setup_bitmap(gRec, size, &bitmap);
   1177                 SkCanvas canvas(bitmap);
   1178                 installFilter(&canvas);
   1179                 // Pass a decoding function so the factory GM (which has an SkBitmap
   1180                 // with encoded data) will not fail playback.
   1181                 PipeController pipeController(&canvas, &SkImageDecoder::DecodeMemory);
   1182                 SkGPipeWriter writer;
   1183                 SkCanvas* pipeCanvas = writer.startRecording(&pipeController,
   1184                                                              gPipeWritingFlagCombos[i].flags,
   1185                                                              size.width(), size.height());
   1186                 if (!simulateFailure) {
   1187                     invokeGM(gm, pipeCanvas, false, false);
   1188                 }
   1189                 complete_bitmap(&bitmap);
   1190                 writer.endRecording();
   1191                 errors.add(compare_test_results_to_reference_bitmap(
   1192                     gm->shortName(), gRec.fName, renderModeDescriptor.c_str(), bitmap,
   1193                     &referenceBitmap));
   1194                 if (!errors.isEmpty()) {
   1195                     break;
   1196                 }
   1197             }
   1198         }
   1199         return errors;
   1200     }
   1201 
   1202     ErrorCombination test_tiled_pipe_playback(GM* gm, const ConfigData& gRec,
   1203                                               const SkBitmap& referenceBitmap) {
   1204         const SkString shortNamePlusConfig = make_shortname_plus_config(gm->shortName(),
   1205                                                                         gRec.fName);
   1206         ErrorCombination errors;
   1207         for (size_t i = 0; i < SK_ARRAY_COUNT(gPipeWritingFlagCombos); ++i) {
   1208             SkString renderModeDescriptor("-tiled pipe");
   1209             renderModeDescriptor.append(gPipeWritingFlagCombos[i].name);
   1210 
   1211             if ((gm->getFlags() & GM::kSkipPipe_Flag) ||
   1212                 (gm->getFlags() & GM::kSkipTiled_Flag)) {
   1213                 RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1214                                   renderModeDescriptor.c_str());
   1215                 errors.add(kIntentionallySkipped_ErrorType);
   1216             } else {
   1217                 SkBitmap bitmap;
   1218                 SkISize size = gm->getISize();
   1219                 setup_bitmap(gRec, size, &bitmap);
   1220                 SkCanvas canvas(bitmap);
   1221                 installFilter(&canvas);
   1222                 TiledPipeController pipeController(bitmap, &SkImageDecoder::DecodeMemory);
   1223                 SkGPipeWriter writer;
   1224                 SkCanvas* pipeCanvas = writer.startRecording(&pipeController,
   1225                                                              gPipeWritingFlagCombos[i].flags,
   1226                                                              size.width(), size.height());
   1227                 invokeGM(gm, pipeCanvas, false, false);
   1228                 complete_bitmap(&bitmap);
   1229                 writer.endRecording();
   1230                 errors.add(compare_test_results_to_reference_bitmap(gm->shortName(), gRec.fName,
   1231                                                                     renderModeDescriptor.c_str(),
   1232                                                                     bitmap, &referenceBitmap));
   1233                 if (!errors.isEmpty()) {
   1234                     break;
   1235                 }
   1236             }
   1237         }
   1238         return errors;
   1239     }
   1240 
   1241     //
   1242     // member variables.
   1243     // They are public for now, to allow easier setting by tool_main().
   1244     //
   1245 
   1246     bool fUseFileHierarchy, fWriteChecksumBasedFilenames;
   1247     ErrorCombination fIgnorableErrorTypes;
   1248     SkTArray<SkString> fIgnorableTestSubstrings;
   1249 
   1250     const char* fMismatchPath;
   1251     const char* fMissingExpectationsPath;
   1252 
   1253     // collection of tests that have failed with each ErrorType
   1254     SkTArray<SkString> fFailedTests[kLast_ErrorType+1];
   1255     int fTestsRun;
   1256     SkTDict<int> fRenderModesEncountered;
   1257 
   1258     // Where to read expectations (expected image hash digests, etc.) from.
   1259     // If unset, we don't do comparisons.
   1260     SkAutoTUnref<ExpectationsSource> fExpectationsSource;
   1261 
   1262     // JSON summaries that we generate as we go (just for output).
   1263     Json::Value fJsonExpectedResults;
   1264     Json::Value fJsonActualResults_Failed;
   1265     Json::Value fJsonActualResults_FailureIgnored;
   1266     Json::Value fJsonActualResults_NoComparison;
   1267     Json::Value fJsonActualResults_Succeeded;
   1268 
   1269 }; // end of GMMain class definition
   1270 
   1271 #if SK_SUPPORT_GPU
   1272 static const GLContextType kDontCare_GLContextType = GrContextFactory::kNative_GLContextType;
   1273 #else
   1274 static const GLContextType kDontCare_GLContextType = 0;
   1275 #endif
   1276 
   1277 static const ConfigData gRec[] = {
   1278     { SkBitmap::kARGB_8888_Config, kRaster_Backend, kDontCare_GLContextType,                  0, kRW_ConfigFlag,    "8888",         true },
   1279 #if 0   // stop testing this (for now at least) since we want to remove support for it (soon please!!!)
   1280     { SkBitmap::kARGB_4444_Config, kRaster_Backend, kDontCare_GLContextType,                  0, kRW_ConfigFlag,    "4444",         true },
   1281 #endif
   1282     { SkBitmap::kRGB_565_Config,   kRaster_Backend, kDontCare_GLContextType,                  0, kRW_ConfigFlag,    "565",          true },
   1283 #if SK_SUPPORT_GPU
   1284     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kNative_GLContextType,  0, kRW_ConfigFlag,    "gpu",          true },
   1285     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kNative_GLContextType, 16, kRW_ConfigFlag,    "msaa16",       false},
   1286     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kNative_GLContextType,  4, kRW_ConfigFlag,    "msaa4",        false},
   1287     /* The gpudebug context does not generate meaningful images, so don't record
   1288      * the images it generates!  We only run it to look for asserts. */
   1289     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kDebug_GLContextType,   0, kNone_ConfigFlag,  "gpudebug",     kDebugOnly},
   1290     /* The gpunull context does the least amount of work possible and doesn't
   1291        generate meaninful images, so don't record them!. It can be run to
   1292        isolate the CPU-side processing expense from the GPU-side.
   1293       */
   1294     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kNull_GLContextType,    0, kNone_ConfigFlag,  "gpunull",      kDebugOnly},
   1295 #if SK_ANGLE
   1296     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kANGLE_GLContextType,   0, kRW_ConfigFlag,    "angle",        true },
   1297     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kANGLE_GLContextType,  16, kRW_ConfigFlag,    "anglemsaa16",  true },
   1298 #endif // SK_ANGLE
   1299 #ifdef SK_MESA
   1300     { SkBitmap::kARGB_8888_Config, kGPU_Backend,    GrContextFactory::kMESA_GLContextType,    0, kRW_ConfigFlag,    "mesa",         true },
   1301 #endif // SK_MESA
   1302 #endif // SK_SUPPORT_GPU
   1303 #ifdef SK_SUPPORT_XPS
   1304     /* At present we have no way of comparing XPS files (either natively or by converting to PNG). */
   1305     { SkBitmap::kARGB_8888_Config, kXPS_Backend,    kDontCare_GLContextType,                  0, kWrite_ConfigFlag, "xps",          true },
   1306 #endif // SK_SUPPORT_XPS
   1307 #ifdef SK_SUPPORT_PDF
   1308     { SkBitmap::kARGB_8888_Config, kPDF_Backend,    kDontCare_GLContextType,                  0, kRW_ConfigFlag,    "pdf",          true },
   1309 #endif // SK_SUPPORT_PDF
   1310 };
   1311 
   1312 static const PDFRasterizerData kPDFRasterizers[] = {
   1313 #ifdef SK_BUILD_FOR_MAC
   1314     { &SkPDFDocumentToBitmap, "mac",     true },
   1315 #endif
   1316 #ifdef SK_BUILD_POPPLER
   1317     { &SkPopplerRasterizePDF, "poppler", true },
   1318 #endif
   1319 #ifdef SK_BUILD_NATIVE_PDF_RENDERER
   1320     { &SkNativeRasterizePDF,  "native",  true },
   1321 #endif  // SK_BUILD_NATIVE_PDF_RENDERER
   1322 };
   1323 
   1324 static const char kDefaultsConfigStr[] = "defaults";
   1325 static const char kExcludeConfigChar = '~';
   1326 
   1327 static SkString configUsage() {
   1328     SkString result;
   1329     result.appendf("Space delimited list of which configs to run. Possible options: [");
   1330     for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {
   1331         SkASSERT(gRec[i].fName != kDefaultsConfigStr);
   1332         if (i > 0) {
   1333             result.append("|");
   1334         }
   1335         result.appendf("%s", gRec[i].fName);
   1336     }
   1337     result.append("]\n");
   1338     result.appendf("The default value is: \"");
   1339     SkString firstDefault;
   1340     SkString allButFirstDefaults;
   1341     SkString nonDefault;
   1342     for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {
   1343         if (gRec[i].fRunByDefault) {
   1344             if (i > 0) {
   1345                 result.append(" ");
   1346             }
   1347             result.append(gRec[i].fName);
   1348             if (firstDefault.isEmpty()) {
   1349                 firstDefault = gRec[i].fName;
   1350             } else {
   1351                 if (!allButFirstDefaults.isEmpty()) {
   1352                     allButFirstDefaults.append(" ");
   1353                 }
   1354                 allButFirstDefaults.append(gRec[i].fName);
   1355             }
   1356         } else {
   1357             nonDefault = gRec[i].fName;
   1358         }
   1359     }
   1360     result.append("\"\n");
   1361     result.appendf("\"%s\" evaluates to the default set of configs.\n", kDefaultsConfigStr);
   1362     result.appendf("Prepending \"%c\" on a config name excludes it from the set of configs to run.\n"
   1363                    "Exclusions always override inclusions regardless of order.\n",
   1364                    kExcludeConfigChar);
   1365     result.appendf("E.g. \"--config %s %c%s %s\" will run these configs:\n\t%s %s",
   1366                    kDefaultsConfigStr,
   1367                    kExcludeConfigChar,
   1368                    firstDefault.c_str(),
   1369                    nonDefault.c_str(),
   1370                    allButFirstDefaults.c_str(),
   1371                    nonDefault.c_str());
   1372     return result;
   1373 }
   1374 
   1375 static SkString pdfRasterizerUsage() {
   1376     SkString result;
   1377     result.appendf("Space delimited list of which PDF rasterizers to run. Possible options: [");
   1378     // For this (and further) loops through kPDFRasterizers, there is a typecast to int to avoid
   1379     // the compiler giving an "comparison of unsigned expression < 0 is always false" warning
   1380     // and turning it into a build-breaking error.
   1381     for (int i = 0; i < (int)SK_ARRAY_COUNT(kPDFRasterizers); ++i) {
   1382         if (i > 0) {
   1383             result.append(" ");
   1384         }
   1385         result.append(kPDFRasterizers[i].fName);
   1386     }
   1387     result.append("]\n");
   1388     result.append("The default value is: \"");
   1389     for (int i = 0; i < (int)SK_ARRAY_COUNT(kPDFRasterizers); ++i) {
   1390         if (kPDFRasterizers[i].fRunByDefault) {
   1391             if (i > 0) {
   1392                 result.append(" ");
   1393             }
   1394             result.append(kPDFRasterizers[i].fName);
   1395         }
   1396     }
   1397     result.append("\"");
   1398     return result;
   1399 }
   1400 
   1401 // Macro magic to convert a numeric preprocessor token into a string.
   1402 // Adapted from http://stackoverflow.com/questions/240353/convert-a-preprocessor-token-to-a-string
   1403 // This should probably be moved into one of our common headers...
   1404 #define TOSTRING_INTERNAL(x) #x
   1405 #define TOSTRING(x) TOSTRING_INTERNAL(x)
   1406 
   1407 // Alphabetized ignoring "no" prefix ("readPath", "noreplay", "resourcePath").
   1408 DEFINE_string(config, "", configUsage().c_str());
   1409 DEFINE_string(pdfRasterizers, "default", pdfRasterizerUsage().c_str());
   1410 DEFINE_bool(deferred, false, "Exercise the deferred rendering test pass.");
   1411 DEFINE_string(excludeConfig, "", "Space delimited list of configs to skip.");
   1412 DEFINE_bool(forceBWtext, false, "Disable text anti-aliasing.");
   1413 #if SK_SUPPORT_GPU
   1414 DEFINE_string(gpuCacheSize, "", "<bytes> <count>: Limit the gpu cache to byte size or "
   1415               "object count. " TOSTRING(DEFAULT_CACHE_VALUE) " for either value means "
   1416               "use the default. 0 for either disables the cache.");
   1417 #endif
   1418 DEFINE_bool(hierarchy, false, "Whether to use multilevel directory structure "
   1419             "when reading/writing files.");
   1420 DEFINE_string(ignoreErrorTypes, kDefaultIgnorableErrorTypes.asString(" ").c_str(),
   1421               "Space-separated list of ErrorTypes that should be ignored. If any *other* error "
   1422               "types are encountered, the tool will exit with a nonzero return value.");
   1423 DEFINE_string(ignoreFailuresFile, "", "Path to file containing a list of tests for which we "
   1424               "should ignore failures.\n"
   1425               "The file should list one test per line, except for comment lines starting with #");
   1426 DEFINE_string(match, "", "[~][^]substring[$] [...] of test name to run.\n"
   1427               "Multiple matches may be separated by spaces.\n"
   1428               "~ causes a matching test to always be skipped\n"
   1429               "^ requires the start of the test to match\n"
   1430               "$ requires the end of the test to match\n"
   1431               "^ and $ requires an exact match\n"
   1432               "If a test does not match any list entry,\n"
   1433               "it is skipped unless some list entry starts with ~");
   1434 DEFINE_string(missingExpectationsPath, "", "Write images for tests without expectations "
   1435               "into this directory.");
   1436 DEFINE_string(mismatchPath, "", "Write images for tests that failed due to "
   1437               "pixel mismatches into this directory.");
   1438 DEFINE_string(modulo, "", "[--modulo <remainder> <divisor>]: only run tests for which "
   1439               "testIndex %% divisor == remainder.");
   1440 DEFINE_bool(pipe, false, "Exercise the SkGPipe replay test pass.");
   1441 DEFINE_string2(readPath, r, "", "Read reference images from this dir, and report "
   1442                "any differences between those and the newly generated ones.");
   1443 DEFINE_bool(replay, false, "Exercise the SkPicture replay test pass.");
   1444 #if SK_SUPPORT_GPU
   1445 DEFINE_bool(resetGpuContext, false, "Reset the GrContext prior to running each GM.");
   1446 #endif
   1447 DEFINE_string2(resourcePath, i, "", "Directory that stores image resources.");
   1448 DEFINE_bool(rtree, false, "Exercise the R-Tree variant of SkPicture test pass.");
   1449 DEFINE_bool(serialize, false, "Exercise the SkPicture serialization & deserialization test pass.");
   1450 DEFINE_bool(simulatePipePlaybackFailure, false, "Simulate a rendering failure in pipe mode only.");
   1451 DEFINE_bool(tiledPipe, false, "Exercise tiled SkGPipe replay.");
   1452 DEFINE_bool(tileGrid, false, "Exercise the tile grid variant of SkPicture.");
   1453 DEFINE_string(tileGridReplayScales, "", "Space separated list of floating-point scale "
   1454               "factors to be used for tileGrid playback testing. Default value: 1.0");
   1455 DEFINE_bool2(verbose, v, false, "Give more detail (e.g. list all GMs run, more info about "
   1456              "each test).");
   1457 DEFINE_bool(writeChecksumBasedFilenames, false, "When writing out actual images, use checksum-"
   1458             "based filenames, as rebaseline.py will use when downloading them from Google Storage");
   1459 DEFINE_string(writeJsonSummaryPath, "", "Write a JSON-formatted result summary to this file.");
   1460 DEFINE_string2(writePath, w, "",  "Write rendered images into this directory.");
   1461 DEFINE_string2(writePicturePath, p, "", "Write .skp files into this directory.");
   1462 DEFINE_int32(pdfJpegQuality, -1, "Encodes images in JPEG at quality level N, "
   1463              "which can be in range 0-100). N = -1 will disable JPEG compression. "
   1464              "Default is N = 100, maximum quality.");
   1465 // TODO(edisonn): pass a matrix instead of forcePerspectiveMatrix
   1466 // Either the 9 numbers defining the matrix
   1467 // or probably more readable would be to replace it with a set of a few predicates
   1468 // Like --prerotate 100 200 10 --posttranslate 10, 10
   1469 // Probably define spacial names like centerx, centery, top, bottom, left, right
   1470 // then we can write something reabable like --rotate centerx centery 90
   1471 DEFINE_bool(forcePerspectiveMatrix, false, "Force a perspective matrix.");
   1472 DEFINE_bool(useDocumentInsteadOfDevice, false, "Use SkDocument::CreateFoo instead of SkFooDevice.");
   1473 DEFINE_int32(pdfRasterDpi, 72, "Scale at which at which the non suported "
   1474              "features in PDF are rasterized. Must be be in range 0-10000. "
   1475              "Default is 72. N = 0 will disable rasterizing features like "
   1476              "text shadows or perspective bitmaps.");
   1477 static SkData* encode_to_dct_data(size_t* pixelRefOffset, const SkBitmap& bitmap) {
   1478     // Filter output of warnings that JPEG is not available for the image.
   1479     if (bitmap.width() >= 65500 || bitmap.height() >= 65500) return NULL;
   1480     if (FLAGS_pdfJpegQuality == -1) return NULL;
   1481 
   1482     SkBitmap bm = bitmap;
   1483 #if defined(SK_BUILD_FOR_MAC)
   1484     // Workaround bug #1043 where bitmaps with referenced pixels cause
   1485     // CGImageDestinationFinalize to crash
   1486     SkBitmap copy;
   1487     bitmap.deepCopyTo(&copy, bitmap.config());
   1488     bm = copy;
   1489 #endif
   1490 
   1491     SkPixelRef* pr = bm.pixelRef();
   1492     if (pr != NULL) {
   1493         SkData* data = pr->refEncodedData();
   1494         if (data != NULL) {
   1495             *pixelRefOffset = bm.pixelRefOffset();
   1496             return data;
   1497         }
   1498     }
   1499 
   1500     *pixelRefOffset = 0;
   1501     return SkImageEncoder::EncodeData(bm,
   1502                                       SkImageEncoder::kJPEG_Type,
   1503                                       FLAGS_pdfJpegQuality);
   1504 }
   1505 
   1506 static int findConfig(const char config[]) {
   1507     for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); i++) {
   1508         if (!strcmp(config, gRec[i].fName)) {
   1509             return (int) i;
   1510         }
   1511     }
   1512     return -1;
   1513 }
   1514 
   1515 static const PDFRasterizerData* findPDFRasterizer(const char rasterizer[]) {
   1516     for (int i = 0; i < (int)SK_ARRAY_COUNT(kPDFRasterizers); i++) {
   1517         if (!strcmp(rasterizer, kPDFRasterizers[i].fName)) {
   1518             return &kPDFRasterizers[i];
   1519         }
   1520     }
   1521     return NULL;
   1522 }
   1523 
   1524 template <typename T> void appendUnique(SkTDArray<T>* array, const T& value) {
   1525     int index = array->find(value);
   1526     if (index < 0) {
   1527         *array->append() = value;
   1528     }
   1529 }
   1530 
   1531 /**
   1532  * Run this test in a number of different configs (8888, 565, PDF,
   1533  * etc.), confirming that the resulting bitmaps match expectations
   1534  * (which may be different for each config).
   1535  *
   1536  * Returns all errors encountered while doing so.
   1537  */
   1538 ErrorCombination run_multiple_configs(GMMain &gmmain, GM *gm,
   1539                                       const SkTDArray<size_t> &configs,
   1540                                       const SkTDArray<const PDFRasterizerData*> &pdfRasterizers,
   1541                                       GrContextFactory *grFactory);
   1542 ErrorCombination run_multiple_configs(GMMain &gmmain, GM *gm,
   1543                                       const SkTDArray<size_t> &configs,
   1544                                       const SkTDArray<const PDFRasterizerData*> &pdfRasterizers,
   1545                                       GrContextFactory *grFactory) {
   1546     const char renderModeDescriptor[] = "";
   1547     ErrorCombination errorsForAllConfigs;
   1548     uint32_t gmFlags = gm->getFlags();
   1549 
   1550     for (int i = 0; i < configs.count(); i++) {
   1551         ConfigData config = gRec[configs[i]];
   1552         const SkString shortNamePlusConfig = gmmain.make_shortname_plus_config(gm->shortName(),
   1553                                                                                config.fName);
   1554 
   1555         // Skip any tests that we don't even need to try.
   1556         // If any of these were skipped on a per-GM basis, record them as
   1557         // kIntentionallySkipped.
   1558         if (kPDF_Backend == config.fBackend) {
   1559             if (gmFlags & GM::kSkipPDF_Flag) {
   1560                 gmmain.RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1561                                          renderModeDescriptor);
   1562                 errorsForAllConfigs.add(kIntentionallySkipped_ErrorType);
   1563                 continue;
   1564             }
   1565         }
   1566         if ((gmFlags & GM::kSkip565_Flag) &&
   1567             (kRaster_Backend == config.fBackend) &&
   1568             (SkBitmap::kRGB_565_Config == config.fConfig)) {
   1569             gmmain.RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1570                                      renderModeDescriptor);
   1571             errorsForAllConfigs.add(kIntentionallySkipped_ErrorType);
   1572             continue;
   1573         }
   1574         if (((gmFlags & GM::kSkipGPU_Flag) && kGPU_Backend == config.fBackend) ||
   1575             ((gmFlags & GM::kGPUOnly_Flag) && kGPU_Backend != config.fBackend)) {
   1576             gmmain.RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1577                                      renderModeDescriptor);
   1578             errorsForAllConfigs.add(kIntentionallySkipped_ErrorType);
   1579             continue;
   1580         }
   1581 
   1582         // Now we know that we want to run this test and record its
   1583         // success or failure.
   1584         ErrorCombination errorsForThisConfig;
   1585         GrSurface* gpuTarget = NULL;
   1586 #if SK_SUPPORT_GPU
   1587         SkAutoTUnref<GrSurface> auGpuTarget;
   1588         if ((errorsForThisConfig.isEmpty()) && (kGPU_Backend == config.fBackend)) {
   1589             if (FLAGS_resetGpuContext) {
   1590                 grFactory->destroyContexts();
   1591             }
   1592             GrContext* gr = grFactory->get(config.fGLContextType);
   1593             bool grSuccess = false;
   1594             if (gr) {
   1595                 // create a render target to back the device
   1596                 GrTextureDesc desc;
   1597                 desc.fConfig = kSkia8888_GrPixelConfig;
   1598                 desc.fFlags = kRenderTarget_GrTextureFlagBit;
   1599                 desc.fWidth = gm->getISize().width();
   1600                 desc.fHeight = gm->getISize().height();
   1601                 desc.fSampleCnt = config.fSampleCnt;
   1602                 auGpuTarget.reset(gr->createUncachedTexture(desc, NULL, 0));
   1603                 if (NULL != auGpuTarget) {
   1604                     gpuTarget = auGpuTarget;
   1605                     grSuccess = true;
   1606                     // Set the user specified cache limits if non-default.
   1607                     size_t bytes;
   1608                     int count;
   1609                     gr->getTextureCacheLimits(&count, &bytes);
   1610                     if (DEFAULT_CACHE_VALUE != gGpuCacheSizeBytes) {
   1611                         bytes = static_cast<size_t>(gGpuCacheSizeBytes);
   1612                     }
   1613                     if (DEFAULT_CACHE_VALUE != gGpuCacheSizeCount) {
   1614                         count = gGpuCacheSizeCount;
   1615                     }
   1616                     gr->setTextureCacheLimits(count, bytes);
   1617                 }
   1618             }
   1619             if (!grSuccess) {
   1620                 errorsForThisConfig.add(kNoGpuContext_ErrorType);
   1621             }
   1622         }
   1623 #endif
   1624 
   1625         SkBitmap comparisonBitmap;
   1626 
   1627         const char* writePath;
   1628         if (FLAGS_writePath.count() == 1) {
   1629             writePath = FLAGS_writePath[0];
   1630         } else {
   1631             writePath = NULL;
   1632         }
   1633 
   1634         if (errorsForThisConfig.isEmpty()) {
   1635             errorsForThisConfig.add(gmmain.test_drawing(gm, config, pdfRasterizers,
   1636                                                         writePath, gpuTarget,
   1637                                                         &comparisonBitmap));
   1638             gmmain.RecordTestResults(errorsForThisConfig, shortNamePlusConfig, "");
   1639         }
   1640 
   1641         if (FLAGS_deferred && errorsForThisConfig.isEmpty() &&
   1642             (kGPU_Backend == config.fBackend || kRaster_Backend == config.fBackend)) {
   1643             errorsForThisConfig.add(gmmain.test_deferred_drawing(gm, config, comparisonBitmap,
   1644                                                                  gpuTarget));
   1645         }
   1646 
   1647         errorsForAllConfigs.add(errorsForThisConfig);
   1648     }
   1649     return errorsForAllConfigs;
   1650 }
   1651 
   1652 /**
   1653  * Run this test in a number of different drawing modes (pipe,
   1654  * deferred, tiled, etc.), confirming that the resulting bitmaps all
   1655  * *exactly* match comparisonBitmap.
   1656  *
   1657  * Returns all errors encountered while doing so.
   1658  */
   1659 ErrorCombination run_multiple_modes(GMMain &gmmain, GM *gm, const ConfigData &compareConfig,
   1660                                     const SkBitmap &comparisonBitmap,
   1661                                     const SkTDArray<SkScalar> &tileGridReplayScales);
   1662 ErrorCombination run_multiple_modes(GMMain &gmmain, GM *gm, const ConfigData &compareConfig,
   1663                                     const SkBitmap &comparisonBitmap,
   1664                                     const SkTDArray<SkScalar> &tileGridReplayScales) {
   1665     ErrorCombination errorsForAllModes;
   1666     uint32_t gmFlags = gm->getFlags();
   1667     const SkString shortNamePlusConfig = gmmain.make_shortname_plus_config(gm->shortName(),
   1668                                                                            compareConfig.fName);
   1669 
   1670     SkPicture* pict = gmmain.generate_new_picture(gm, kNone_BbhType, 0);
   1671     SkAutoUnref aur(pict);
   1672     if (FLAGS_replay) {
   1673         const char renderModeDescriptor[] = "-replay";
   1674         if (gmFlags & GM::kSkipPicture_Flag) {
   1675             gmmain.RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1676                                      renderModeDescriptor);
   1677             errorsForAllModes.add(kIntentionallySkipped_ErrorType);
   1678         } else {
   1679             SkBitmap bitmap;
   1680             gmmain.generate_image_from_picture(gm, compareConfig, pict, &bitmap);
   1681             errorsForAllModes.add(gmmain.compare_test_results_to_reference_bitmap(
   1682                 gm->shortName(), compareConfig.fName, renderModeDescriptor, bitmap,
   1683                 &comparisonBitmap));
   1684         }
   1685     }
   1686 
   1687     if (FLAGS_serialize) {
   1688         const char renderModeDescriptor[] = "-serialize";
   1689         if (gmFlags & GM::kSkipPicture_Flag) {
   1690             gmmain.RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1691                                      renderModeDescriptor);
   1692             errorsForAllModes.add(kIntentionallySkipped_ErrorType);
   1693         } else {
   1694             SkPicture* repict = gmmain.stream_to_new_picture(*pict);
   1695             SkAutoUnref aurr(repict);
   1696             SkBitmap bitmap;
   1697             gmmain.generate_image_from_picture(gm, compareConfig, repict, &bitmap);
   1698             errorsForAllModes.add(gmmain.compare_test_results_to_reference_bitmap(
   1699                 gm->shortName(), compareConfig.fName, renderModeDescriptor, bitmap,
   1700                 &comparisonBitmap));
   1701         }
   1702     }
   1703 
   1704     if ((1 == FLAGS_writePicturePath.count()) &&
   1705         !(gmFlags & GM::kSkipPicture_Flag)) {
   1706         const char* pictureSuffix = "skp";
   1707         // TODO(epoger): Make sure this still works even though the
   1708         // filename now contains the config name (it used to contain
   1709         // just the shortName).  I think this is actually an
   1710         // *improvement*, because now runs with different configs will
   1711         // write out their SkPictures to separate files rather than
   1712         // overwriting each other.  But we should make sure it doesn't
   1713         // break anybody.
   1714         SkString path = gmmain.make_filename(FLAGS_writePicturePath[0], gm->shortName(),
   1715                                              compareConfig.fName, "", pictureSuffix);
   1716         SkFILEWStream stream(path.c_str());
   1717         pict->serialize(&stream);
   1718     }
   1719 
   1720     if (FLAGS_rtree) {
   1721         const char renderModeDescriptor[] = "-rtree";
   1722         if (gmFlags & GM::kSkipPicture_Flag) {
   1723             gmmain.RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1724                                      renderModeDescriptor);
   1725             errorsForAllModes.add(kIntentionallySkipped_ErrorType);
   1726         } else {
   1727             SkPicture* pict = gmmain.generate_new_picture(
   1728                 gm, kRTree_BbhType, SkPicture::kOptimizeForClippedPlayback_RecordingFlag);
   1729             SkAutoUnref aur(pict);
   1730             SkBitmap bitmap;
   1731             gmmain.generate_image_from_picture(gm, compareConfig, pict, &bitmap);
   1732             errorsForAllModes.add(gmmain.compare_test_results_to_reference_bitmap(
   1733                 gm->shortName(), compareConfig.fName, renderModeDescriptor, bitmap,
   1734                 &comparisonBitmap));
   1735         }
   1736     }
   1737 
   1738     if (FLAGS_tileGrid) {
   1739         for(int scaleIndex = 0; scaleIndex < tileGridReplayScales.count(); ++scaleIndex) {
   1740             SkScalar replayScale = tileGridReplayScales[scaleIndex];
   1741             SkString renderModeDescriptor("-tilegrid");
   1742             if (SK_Scalar1 != replayScale) {
   1743                 renderModeDescriptor += "-scale-";
   1744                 renderModeDescriptor.appendScalar(replayScale);
   1745             }
   1746 
   1747             if ((gmFlags & GM::kSkipPicture_Flag) ||
   1748                 ((gmFlags & GM::kSkipScaledReplay_Flag) && replayScale != 1)) {
   1749                 gmmain.RecordTestResults(kIntentionallySkipped_ErrorType, shortNamePlusConfig,
   1750                                          renderModeDescriptor.c_str());
   1751                 errorsForAllModes.add(kIntentionallySkipped_ErrorType);
   1752             } else {
   1753                 // We record with the reciprocal scale to obtain a replay
   1754                 // result that can be validated against comparisonBitmap.
   1755                 SkScalar recordScale = SkScalarInvert(replayScale);
   1756                 SkPicture* pict = gmmain.generate_new_picture(
   1757                     gm, kTileGrid_BbhType, SkPicture::kUsePathBoundsForClip_RecordingFlag,
   1758                     recordScale);
   1759                 SkAutoUnref aur(pict);
   1760                 SkBitmap bitmap;
   1761                 // We cannot yet pass 'true' to generate_image_from_picture to
   1762                 // perform actual tiled rendering (see Issue 1198 -
   1763                 // https://code.google.com/p/skia/issues/detail?id=1198)
   1764                 gmmain.generate_image_from_picture(gm, compareConfig, pict, &bitmap,
   1765                                                    replayScale /*, true */);
   1766                 errorsForAllModes.add(gmmain.compare_test_results_to_reference_bitmap(
   1767                     gm->shortName(), compareConfig.fName, renderModeDescriptor.c_str(), bitmap,
   1768                     &comparisonBitmap));
   1769             }
   1770         }
   1771     }
   1772 
   1773     // run the pipe centric GM steps
   1774     if (FLAGS_pipe) {
   1775         errorsForAllModes.add(gmmain.test_pipe_playback(gm, compareConfig, comparisonBitmap,
   1776                                                         FLAGS_simulatePipePlaybackFailure));
   1777         if (FLAGS_tiledPipe) {
   1778             errorsForAllModes.add(gmmain.test_tiled_pipe_playback(gm, compareConfig,
   1779                                                                   comparisonBitmap));
   1780         }
   1781     }
   1782     return errorsForAllModes;
   1783 }
   1784 
   1785 /**
   1786  * Read individual lines from a file, pushing them into the given array.
   1787  *
   1788  * @param filename path to the file to read
   1789  * @param lines array of strings to add the lines to
   1790  * @returns true if able to read lines from the file
   1791  */
   1792 static bool read_lines_from_file(const char* filename, SkTArray<SkString> &lines) {
   1793     SkAutoTUnref<SkStream> streamWrapper(SkStream::NewFromFile(filename));
   1794     SkStream *stream = streamWrapper.get();
   1795     if (!stream) {
   1796         gm_fprintf(stderr, "unable to read file '%s'\n", filename);
   1797         return false;
   1798     }
   1799 
   1800     char c;
   1801     SkString line;
   1802     while (1 == stream->read(&c, 1)) {
   1803         // If we hit either CR or LF, we've completed a line.
   1804         //
   1805         // TODO: If the file uses both CR and LF, this will return an extra blank
   1806         // line for each line of the file.  Which is OK for current purposes...
   1807         //
   1808         // TODO: Does this properly handle unicode?  It doesn't matter for
   1809         // current purposes...
   1810         if ((c == 0x0d) || (c == 0x0a)) {
   1811             lines.push_back(line);
   1812             line.reset();
   1813         } else {
   1814             line.append(&c, 1);
   1815         }
   1816     }
   1817     lines.push_back(line);
   1818     return true;
   1819 }
   1820 
   1821 /**
   1822  * Return a list of all entries in an array of strings as a single string
   1823  * of this form:
   1824  * "item1", "item2", "item3"
   1825  */
   1826 SkString list_all(const SkTArray<SkString> &stringArray);
   1827 SkString list_all(const SkTArray<SkString> &stringArray) {
   1828     SkString total;
   1829     for (int i = 0; i < stringArray.count(); i++) {
   1830         if (i > 0) {
   1831             total.append(", ");
   1832         }
   1833         total.append("\"");
   1834         total.append(stringArray[i]);
   1835         total.append("\"");
   1836     }
   1837     return total;
   1838 }
   1839 
   1840 /**
   1841  * Return a list of configuration names, as a single string of this form:
   1842  * "item1", "item2", "item3"
   1843  *
   1844  * @param configs configurations, as a list of indices into gRec
   1845  */
   1846 SkString list_all_config_names(const SkTDArray<size_t> &configs);
   1847 SkString list_all_config_names(const SkTDArray<size_t> &configs) {
   1848     SkString total;
   1849     for (int i = 0; i < configs.count(); i++) {
   1850         if (i > 0) {
   1851             total.append(", ");
   1852         }
   1853         total.append("\"");
   1854         total.append(gRec[configs[i]].fName);
   1855         total.append("\"");
   1856     }
   1857     return total;
   1858 }
   1859 
   1860 static bool prepare_subdirectories(const char *root, bool useFileHierarchy,
   1861                                    const SkTDArray<size_t> &configs,
   1862                                    const SkTDArray<const PDFRasterizerData*>& pdfRasterizers) {
   1863     if (!sk_mkdir(root)) {
   1864         return false;
   1865     }
   1866     if (useFileHierarchy) {
   1867         for (int i = 0; i < configs.count(); i++) {
   1868             ConfigData config = gRec[configs[i]];
   1869             SkString subdir;
   1870             subdir.appendf("%s%c%s", root, SkPATH_SEPARATOR, config.fName);
   1871             if (!sk_mkdir(subdir.c_str())) {
   1872                 return false;
   1873             }
   1874 
   1875             if (config.fBackend == kPDF_Backend) {
   1876                 for (int j = 0; j < pdfRasterizers.count(); j++) {
   1877                     SkString pdfSubdir = subdir;
   1878                     pdfSubdir.appendf("-%s", pdfRasterizers[j]->fName);
   1879                     if (!sk_mkdir(pdfSubdir.c_str())) {
   1880                         return false;
   1881                     }
   1882                 }
   1883             }
   1884         }
   1885     }
   1886     return true;
   1887 }
   1888 
   1889 static bool parse_flags_configs(SkTDArray<size_t>* outConfigs,
   1890                          GrContextFactory* grFactory) {
   1891     SkTDArray<size_t> excludeConfigs;
   1892 
   1893     for (int i = 0; i < FLAGS_config.count(); i++) {
   1894         const char* config = FLAGS_config[i];
   1895         bool exclude = false;
   1896         if (*config == kExcludeConfigChar) {
   1897             exclude = true;
   1898             config += 1;
   1899         }
   1900         int index = findConfig(config);
   1901         if (index >= 0) {
   1902             if (exclude) {
   1903                 *excludeConfigs.append() = index;
   1904             } else {
   1905                 appendUnique<size_t>(outConfigs, index);
   1906             }
   1907         } else if (0 == strcmp(kDefaultsConfigStr, config)) {
   1908             if (exclude) {
   1909                 gm_fprintf(stderr, "%c%s is not allowed.\n",
   1910                            kExcludeConfigChar, kDefaultsConfigStr);
   1911                 return false;
   1912             }
   1913             for (size_t c = 0; c < SK_ARRAY_COUNT(gRec); ++c) {
   1914                 if (gRec[c].fRunByDefault) {
   1915                     appendUnique<size_t>(outConfigs, c);
   1916                 }
   1917             }
   1918         } else {
   1919             gm_fprintf(stderr, "unrecognized config %s\n", config);
   1920             return false;
   1921         }
   1922     }
   1923 
   1924     for (int i = 0; i < FLAGS_excludeConfig.count(); i++) {
   1925         int index = findConfig(FLAGS_excludeConfig[i]);
   1926         if (index >= 0) {
   1927             *excludeConfigs.append() = index;
   1928         } else {
   1929             gm_fprintf(stderr, "unrecognized excludeConfig %s\n", FLAGS_excludeConfig[i]);
   1930             return false;
   1931         }
   1932     }
   1933 
   1934     if (outConfigs->count() == 0) {
   1935         // if no config is specified by user, add the defaults
   1936         for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {
   1937             if (gRec[i].fRunByDefault) {
   1938                 *outConfigs->append() = i;
   1939             }
   1940         }
   1941     }
   1942     // now remove any explicitly excluded configs
   1943     for (int i = 0; i < excludeConfigs.count(); ++i) {
   1944         int index = outConfigs->find(excludeConfigs[i]);
   1945         if (index >= 0) {
   1946             outConfigs->remove(index);
   1947             // now assert that there was only one copy in configs[]
   1948             SkASSERT(outConfigs->find(excludeConfigs[i]) < 0);
   1949         }
   1950     }
   1951 
   1952 #if SK_SUPPORT_GPU
   1953     SkASSERT(grFactory != NULL);
   1954     for (int i = 0; i < outConfigs->count(); ++i) {
   1955         size_t index = (*outConfigs)[i];
   1956         if (kGPU_Backend == gRec[index].fBackend) {
   1957             GrContext* ctx = grFactory->get(gRec[index].fGLContextType);
   1958             if (NULL == ctx) {
   1959                 gm_fprintf(stderr, "GrContext could not be created for config %s."
   1960                            " Config will be skipped.\n", gRec[index].fName);
   1961                 outConfigs->remove(i);
   1962                 --i;
   1963                 continue;
   1964             }
   1965             if (gRec[index].fSampleCnt > ctx->getMaxSampleCount()) {
   1966                 gm_fprintf(stderr, "Sample count (%d) of config %s is not supported."
   1967                            " Config will be skipped.\n",
   1968                            gRec[index].fSampleCnt, gRec[index].fName);
   1969                 outConfigs->remove(i);
   1970                 --i;
   1971             }
   1972         }
   1973     }
   1974 #endif
   1975 
   1976     if (outConfigs->isEmpty()) {
   1977         gm_fprintf(stderr, "No configs to run.");
   1978         return false;
   1979     }
   1980 
   1981     // now show the user the set of configs that will be run.
   1982     SkString configStr("These configs will be run:");
   1983     // show the user the config that will run.
   1984     for (int i = 0; i < outConfigs->count(); ++i) {
   1985         configStr.appendf(" %s", gRec[(*outConfigs)[i]].fName);
   1986     }
   1987     gm_fprintf(stdout, "%s\n", configStr.c_str());
   1988 
   1989     return true;
   1990 }
   1991 
   1992 static bool parse_flags_pdf_rasterizers(const SkTDArray<size_t>& configs,
   1993                                         SkTDArray<const PDFRasterizerData*>* outRasterizers) {
   1994     // No need to run this check (and display the PDF rasterizers message)
   1995     // if no PDF backends are in the configs.
   1996     bool configHasPDF = false;
   1997     for (int i = 0; i < configs.count(); i++) {
   1998         if (gRec[configs[i]].fBackend == kPDF_Backend) {
   1999             configHasPDF = true;
   2000             break;
   2001         }
   2002     }
   2003     if (!configHasPDF) {
   2004         return true;
   2005     }
   2006 
   2007     if (FLAGS_pdfRasterizers.count() == 1 &&
   2008             !strcmp(FLAGS_pdfRasterizers[0], "default")) {
   2009         for (int i = 0; i < (int)SK_ARRAY_COUNT(kPDFRasterizers); ++i) {
   2010             if (kPDFRasterizers[i].fRunByDefault) {
   2011                 *outRasterizers->append() = &kPDFRasterizers[i];
   2012             }
   2013         }
   2014     } else {
   2015         for (int i = 0; i < FLAGS_pdfRasterizers.count(); i++) {
   2016             const char* rasterizer = FLAGS_pdfRasterizers[i];
   2017             const PDFRasterizerData* rasterizerPtr =
   2018                     findPDFRasterizer(rasterizer);
   2019             if (rasterizerPtr == NULL) {
   2020                 gm_fprintf(stderr, "unrecognized rasterizer %s\n", rasterizer);
   2021                 return false;
   2022             }
   2023             appendUnique<const PDFRasterizerData*>(outRasterizers,
   2024                                                    rasterizerPtr);
   2025         }
   2026     }
   2027 
   2028     // now show the user the set of configs that will be run.
   2029     SkString configStr("These PDF rasterizers will be run:");
   2030     // show the user the config that will run.
   2031     for (int i = 0; i < outRasterizers->count(); ++i) {
   2032         configStr.appendf(" %s", (*outRasterizers)[i]->fName);
   2033     }
   2034     gm_fprintf(stdout, "%s\n", configStr.c_str());
   2035 
   2036     return true;
   2037 }
   2038 
   2039 static bool parse_flags_ignore_error_types(ErrorCombination* outErrorTypes) {
   2040     if (FLAGS_ignoreErrorTypes.count() > 0) {
   2041         *outErrorTypes = ErrorCombination();
   2042         for (int i = 0; i < FLAGS_ignoreErrorTypes.count(); i++) {
   2043             ErrorType type;
   2044             const char *name = FLAGS_ignoreErrorTypes[i];
   2045             if (!getErrorTypeByName(name, &type)) {
   2046                 gm_fprintf(stderr, "cannot find ErrorType with name '%s'\n", name);
   2047                 return false;
   2048             } else {
   2049                 outErrorTypes->add(type);
   2050             }
   2051         }
   2052     }
   2053     return true;
   2054 }
   2055 
   2056 /**
   2057  * Replace contents of ignoreTestSubstrings with a list of testname/config substrings, indicating
   2058  * which tests' failures should be ignored.
   2059  */
   2060 static bool parse_flags_ignore_tests(SkTArray<SkString> &ignoreTestSubstrings) {
   2061     ignoreTestSubstrings.reset();
   2062 
   2063     // Parse --ignoreFailuresFile
   2064     for (int i = 0; i < FLAGS_ignoreFailuresFile.count(); i++) {
   2065         SkTArray<SkString> linesFromFile;
   2066         if (!read_lines_from_file(FLAGS_ignoreFailuresFile[i], linesFromFile)) {
   2067             return false;
   2068         } else {
   2069             for (int j = 0; j < linesFromFile.count(); j++) {
   2070                 SkString thisLine = linesFromFile[j];
   2071                 if (thisLine.isEmpty() || thisLine.startsWith('#')) {
   2072                     // skip this line
   2073                 } else {
   2074                     ignoreTestSubstrings.push_back(thisLine);
   2075                 }
   2076             }
   2077         }
   2078     }
   2079 
   2080     return true;
   2081 }
   2082 
   2083 static bool parse_flags_modulo(int* moduloRemainder, int* moduloDivisor) {
   2084     if (FLAGS_modulo.count() == 2) {
   2085         *moduloRemainder = atoi(FLAGS_modulo[0]);
   2086         *moduloDivisor = atoi(FLAGS_modulo[1]);
   2087         if (*moduloRemainder < 0 || *moduloDivisor <= 0 ||
   2088                 *moduloRemainder >= *moduloDivisor) {
   2089             gm_fprintf(stderr, "invalid modulo values.");
   2090             return false;
   2091         }
   2092     }
   2093     return true;
   2094 }
   2095 
   2096 #if SK_SUPPORT_GPU
   2097 static bool parse_flags_gpu_cache(int* sizeBytes, int* sizeCount) {
   2098     if (FLAGS_gpuCacheSize.count() > 0) {
   2099         if (FLAGS_gpuCacheSize.count() != 2) {
   2100             gm_fprintf(stderr, "--gpuCacheSize requires two arguments\n");
   2101             return false;
   2102         }
   2103         *sizeBytes = atoi(FLAGS_gpuCacheSize[0]);
   2104         *sizeCount = atoi(FLAGS_gpuCacheSize[1]);
   2105     } else {
   2106         *sizeBytes = DEFAULT_CACHE_VALUE;
   2107         *sizeCount = DEFAULT_CACHE_VALUE;
   2108     }
   2109     return true;
   2110 }
   2111 #endif
   2112 
   2113 static bool parse_flags_tile_grid_replay_scales(SkTDArray<SkScalar>* outScales) {
   2114     *outScales->append() = SK_Scalar1; // By default only test at scale 1.0
   2115     if (FLAGS_tileGridReplayScales.count() > 0) {
   2116         outScales->reset();
   2117         for (int i = 0; i < FLAGS_tileGridReplayScales.count(); i++) {
   2118             double val = atof(FLAGS_tileGridReplayScales[i]);
   2119             if (0 < val) {
   2120                 *outScales->append() = SkDoubleToScalar(val);
   2121             }
   2122         }
   2123         if (0 == outScales->count()) {
   2124             // Should have at least one scale
   2125             gm_fprintf(stderr, "--tileGridReplayScales requires at least one scale.\n");
   2126             return false;
   2127         }
   2128     }
   2129     return true;
   2130 }
   2131 
   2132 static bool parse_flags_gmmain_paths(GMMain* gmmain) {
   2133     gmmain->fUseFileHierarchy = FLAGS_hierarchy;
   2134     gmmain->fWriteChecksumBasedFilenames = FLAGS_writeChecksumBasedFilenames;
   2135 
   2136     if (FLAGS_mismatchPath.count() == 1) {
   2137         gmmain->fMismatchPath = FLAGS_mismatchPath[0];
   2138     }
   2139 
   2140     if (FLAGS_missingExpectationsPath.count() == 1) {
   2141         gmmain->fMissingExpectationsPath = FLAGS_missingExpectationsPath[0];
   2142     }
   2143 
   2144     if (FLAGS_readPath.count() == 1) {
   2145         const char* readPath = FLAGS_readPath[0];
   2146         if (!sk_exists(readPath)) {
   2147             gm_fprintf(stderr, "readPath %s does not exist!\n", readPath);
   2148             return false;
   2149         }
   2150         if (sk_isdir(readPath)) {
   2151             if (FLAGS_verbose) {
   2152                 gm_fprintf(stdout, "reading from %s\n", readPath);
   2153             }
   2154             gmmain->fExpectationsSource.reset(SkNEW_ARGS(
   2155                 IndividualImageExpectationsSource, (readPath)));
   2156         } else {
   2157             if (FLAGS_verbose) {
   2158                 gm_fprintf(stdout, "reading expectations from JSON summary file %s\n", readPath);
   2159             }
   2160             gmmain->fExpectationsSource.reset(SkNEW_ARGS(JsonExpectationsSource, (readPath)));
   2161         }
   2162     }
   2163     return true;
   2164 }
   2165 
   2166 static bool parse_flags_resource_path() {
   2167     if (FLAGS_resourcePath.count() == 1) {
   2168         GM::SetResourcePath(FLAGS_resourcePath[0]);
   2169     }
   2170     return true;
   2171 }
   2172 
   2173 static bool parse_flags_jpeg_quality() {
   2174     if (FLAGS_pdfJpegQuality < -1 || FLAGS_pdfJpegQuality > 100) {
   2175         gm_fprintf(stderr, "%s\n", "pdfJpegQuality must be in [-1 .. 100] range.");
   2176         return false;
   2177     }
   2178     return true;
   2179 }
   2180 
   2181 int tool_main(int argc, char** argv);
   2182 int tool_main(int argc, char** argv) {
   2183 
   2184 #if SK_ENABLE_INST_COUNT
   2185     gPrintInstCount = true;
   2186 #endif
   2187 
   2188     SkGraphics::Init();
   2189     // we don't need to see this during a run
   2190     gSkSuppressFontCachePurgeSpew = true;
   2191 
   2192     setSystemPreferences();
   2193     GMMain gmmain;
   2194 
   2195     SkString usage;
   2196     usage.printf("Run the golden master tests.\n");
   2197     SkCommandLineFlags::SetUsage(usage.c_str());
   2198     SkCommandLineFlags::Parse(argc, argv);
   2199 
   2200     SkTDArray<size_t> configs;
   2201 
   2202     int moduloRemainder = -1;
   2203     int moduloDivisor = -1;
   2204     SkTDArray<const PDFRasterizerData*> pdfRasterizers;
   2205     SkTDArray<SkScalar> tileGridReplayScales;
   2206 #if SK_SUPPORT_GPU
   2207     GrContextFactory* grFactory = new GrContextFactory;
   2208 #else
   2209     GrContextFactory* grFactory = NULL;
   2210 #endif
   2211 
   2212     if (!parse_flags_modulo(&moduloRemainder, &moduloDivisor) ||
   2213         !parse_flags_ignore_error_types(&gmmain.fIgnorableErrorTypes) ||
   2214         !parse_flags_ignore_tests(gmmain.fIgnorableTestSubstrings) ||
   2215 #if SK_SUPPORT_GPU
   2216         !parse_flags_gpu_cache(&gGpuCacheSizeBytes, &gGpuCacheSizeCount) ||
   2217 #endif
   2218         !parse_flags_tile_grid_replay_scales(&tileGridReplayScales) ||
   2219         !parse_flags_resource_path() ||
   2220         !parse_flags_jpeg_quality() ||
   2221         !parse_flags_configs(&configs, grFactory) ||
   2222         !parse_flags_pdf_rasterizers(configs, &pdfRasterizers) ||
   2223         !parse_flags_gmmain_paths(&gmmain)) {
   2224         return -1;
   2225     }
   2226 
   2227     if (FLAGS_verbose) {
   2228         if (FLAGS_writePath.count() == 1) {
   2229             gm_fprintf(stdout, "writing to %s\n", FLAGS_writePath[0]);
   2230         }
   2231         if (NULL != gmmain.fMismatchPath) {
   2232             gm_fprintf(stdout, "writing mismatches to %s\n", gmmain.fMismatchPath);
   2233         }
   2234         if (NULL != gmmain.fMissingExpectationsPath) {
   2235             gm_fprintf(stdout, "writing images without expectations to %s\n",
   2236                        gmmain.fMissingExpectationsPath);
   2237         }
   2238         if (FLAGS_writePicturePath.count() == 1) {
   2239             gm_fprintf(stdout, "writing pictures to %s\n", FLAGS_writePicturePath[0]);
   2240         }
   2241         if (FLAGS_resourcePath.count() == 1) {
   2242             gm_fprintf(stdout, "reading resources from %s\n", FLAGS_resourcePath[0]);
   2243         }
   2244     }
   2245 
   2246     int gmsRun = 0;
   2247     int gmIndex = -1;
   2248     SkString moduloStr;
   2249 
   2250     // If we will be writing out files, prepare subdirectories.
   2251     if (FLAGS_writePath.count() == 1) {
   2252         if (!prepare_subdirectories(FLAGS_writePath[0], gmmain.fUseFileHierarchy,
   2253                                     configs, pdfRasterizers)) {
   2254             return -1;
   2255         }
   2256     }
   2257     if (NULL != gmmain.fMismatchPath) {
   2258         if (!prepare_subdirectories(gmmain.fMismatchPath, gmmain.fUseFileHierarchy,
   2259                                     configs, pdfRasterizers)) {
   2260             return -1;
   2261         }
   2262     }
   2263     if (NULL != gmmain.fMissingExpectationsPath) {
   2264         if (!prepare_subdirectories(gmmain.fMissingExpectationsPath, gmmain.fUseFileHierarchy,
   2265                                     configs, pdfRasterizers)) {
   2266             return -1;
   2267         }
   2268     }
   2269 
   2270     Iter iter;
   2271     GM* gm;
   2272     while ((gm = iter.next()) != NULL) {
   2273         if (FLAGS_forcePerspectiveMatrix) {
   2274             SkMatrix perspective;
   2275             perspective.setIdentity();
   2276             perspective.setPerspY(SkScalarDiv(SK_Scalar1, SkIntToScalar(1000)));
   2277             perspective.setSkewX(SkScalarDiv(SkIntToScalar(8),
   2278                                  SkIntToScalar(25)));
   2279 
   2280             gm->setStarterMatrix(perspective);
   2281         }
   2282         SkAutoTDelete<GM> adgm(gm);
   2283         ++gmIndex;
   2284         if (moduloRemainder >= 0) {
   2285             if ((gmIndex % moduloDivisor) != moduloRemainder) {
   2286                 continue;
   2287             }
   2288             moduloStr.printf("[%d.%d] ", gmIndex, moduloDivisor);
   2289         }
   2290 
   2291         const char* shortName = gm->shortName();
   2292 
   2293         if (SkCommandLineFlags::ShouldSkip(FLAGS_match, shortName)) {
   2294             continue;
   2295         }
   2296 
   2297         gmsRun++;
   2298         SkISize size = gm->getISize();
   2299         gm_fprintf(stdout, "%sdrawing... %s [%d %d]\n", moduloStr.c_str(), shortName,
   2300                    size.width(), size.height());
   2301 
   2302         run_multiple_configs(gmmain, gm, configs, pdfRasterizers, grFactory);
   2303 
   2304         SkBitmap comparisonBitmap;
   2305         const ConfigData compareConfig =
   2306             { SkBitmap::kARGB_8888_Config, kRaster_Backend, kDontCare_GLContextType, 0, kRW_ConfigFlag, "comparison", false };
   2307         gmmain.generate_image(gm, compareConfig, NULL, &comparisonBitmap, false);
   2308 
   2309         // TODO(epoger): only run this if gmmain.generate_image() succeeded?
   2310         // Otherwise, what are we comparing against?
   2311         run_multiple_modes(gmmain, gm, compareConfig, comparisonBitmap, tileGridReplayScales);
   2312     }
   2313 
   2314     SkTArray<SkString> modes;
   2315     gmmain.GetRenderModesEncountered(modes);
   2316     bool reportError = false;
   2317     if (gmmain.NumSignificantErrors() > 0) {
   2318         reportError = true;
   2319     }
   2320     int expectedNumberOfTests = gmsRun * (configs.count() + modes.count());
   2321 
   2322     // Output summary to stdout.
   2323     if (FLAGS_verbose) {
   2324         gm_fprintf(stdout, "Ran %d GMs\n", gmsRun);
   2325         gm_fprintf(stdout, "... over %2d configs [%s]\n", configs.count(),
   2326                    list_all_config_names(configs).c_str());
   2327         gm_fprintf(stdout, "...  and %2d modes   [%s]\n", modes.count(), list_all(modes).c_str());
   2328         gm_fprintf(stdout, "... so there should be a total of %d tests.\n", expectedNumberOfTests);
   2329     }
   2330     gmmain.ListErrors(FLAGS_verbose);
   2331 
   2332     // TODO(epoger): Enable this check for Android, too, once we resolve
   2333     // https://code.google.com/p/skia/issues/detail?id=1222
   2334     // ('GM is unexpectedly skipping tests on Android')
   2335 #ifndef SK_BUILD_FOR_ANDROID
   2336     if (expectedNumberOfTests != gmmain.fTestsRun) {
   2337         gm_fprintf(stderr, "expected %d tests, but ran or skipped %d tests\n",
   2338                    expectedNumberOfTests, gmmain.fTestsRun);
   2339         reportError = true;
   2340     }
   2341 #endif
   2342 
   2343     if (FLAGS_writeJsonSummaryPath.count() == 1) {
   2344         Json::Value root = CreateJsonTree(
   2345             gmmain.fJsonExpectedResults,
   2346             gmmain.fJsonActualResults_Failed, gmmain.fJsonActualResults_FailureIgnored,
   2347             gmmain.fJsonActualResults_NoComparison, gmmain.fJsonActualResults_Succeeded);
   2348         std::string jsonStdString = root.toStyledString();
   2349         SkFILEWStream stream(FLAGS_writeJsonSummaryPath[0]);
   2350         stream.write(jsonStdString.c_str(), jsonStdString.length());
   2351     }
   2352 
   2353 #if SK_SUPPORT_GPU
   2354 
   2355 #if GR_CACHE_STATS
   2356     for (int i = 0; i < configs.count(); i++) {
   2357         ConfigData config = gRec[configs[i]];
   2358 
   2359         if (FLAGS_verbose && (kGPU_Backend == config.fBackend)) {
   2360             GrContext* gr = grFactory->get(config.fGLContextType);
   2361 
   2362             gm_fprintf(stdout, "config: %s %x\n", config.fName, gr);
   2363             gr->printCacheStats();
   2364         }
   2365     }
   2366 #endif
   2367 
   2368     delete grFactory;
   2369 #endif
   2370     SkGraphics::Term();
   2371 
   2372     return (reportError) ? -1 : 0;
   2373 }
   2374 
   2375 void GMMain::installFilter(SkCanvas* canvas) {
   2376     if (FLAGS_forceBWtext) {
   2377         canvas->setDrawFilter(SkNEW(BWTextDrawFilter))->unref();
   2378     }
   2379 }
   2380 
   2381 #if !defined(SK_BUILD_FOR_IOS) && !defined(SK_BUILD_FOR_NACL)
   2382 int main(int argc, char * const argv[]) {
   2383     return tool_main(argc, (char**) argv);
   2384 }
   2385 #endif
   2386