SkDebugCanvas.cpp revision 6e998e6137e6b25f047b5c5943f2b02485165e3e
1/*
2 * Copyright 2012 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkCanvasPriv.h"
9#include "SkClipStack.h"
10#include "SkDebugCanvas.h"
11#include "SkDrawCommand.h"
12#include "SkPaintFilterCanvas.h"
13#include "SkOverdrawMode.h"
14
15#if SK_SUPPORT_GPU
16#include "GrAuditTrail.h"
17#include "GrContext.h"
18#include "GrRenderTarget.h"
19#include "SkGpuDevice.h"
20#endif
21
22#define SKDEBUGCANVAS_VERSION                     1
23#define SKDEBUGCANVAS_ATTRIBUTE_VERSION           "version"
24#define SKDEBUGCANVAS_ATTRIBUTE_COMMANDS          "commands"
25#define SKDEBUGCANVAS_ATTRIBUTE_AUDITTRAIL        "auditTrail"
26
27class DebugPaintFilterCanvas : public SkPaintFilterCanvas {
28public:
29    DebugPaintFilterCanvas(int width,
30                           int height,
31                           bool overdrawViz,
32                           bool overrideFilterQuality,
33                           SkFilterQuality quality)
34        : INHERITED(width, height)
35        , fOverdrawXfermode(overdrawViz ? SkOverdrawMode::Make() : nullptr)
36        , fOverrideFilterQuality(overrideFilterQuality)
37        , fFilterQuality(quality) {}
38
39protected:
40    bool onFilter(SkTCopyOnFirstWrite<SkPaint>* paint, Type) const override {
41        if (*paint) {
42            if (nullptr != fOverdrawXfermode.get()) {
43                paint->writable()->setAntiAlias(false);
44                paint->writable()->setXfermode(fOverdrawXfermode);
45            }
46
47            if (fOverrideFilterQuality) {
48                paint->writable()->setFilterQuality(fFilterQuality);
49            }
50        }
51        return true;
52    }
53
54    void onDrawPicture(const SkPicture* picture,
55                       const SkMatrix* matrix,
56                       const SkPaint* paint) override {
57        // We need to replay the picture onto this canvas in order to filter its internal paints.
58        this->SkCanvas::onDrawPicture(picture, matrix, paint);
59    }
60
61private:
62    sk_sp<SkXfermode> fOverdrawXfermode;
63
64    bool fOverrideFilterQuality;
65    SkFilterQuality fFilterQuality;
66
67    typedef SkPaintFilterCanvas INHERITED;
68};
69
70SkDebugCanvas::SkDebugCanvas(int width, int height)
71        : INHERITED(width, height)
72        , fPicture(nullptr)
73        , fFilter(false)
74        , fMegaVizMode(false)
75        , fOverdrawViz(false)
76        , fOverrideFilterQuality(false)
77        , fFilterQuality(kNone_SkFilterQuality)
78        , fClipVizColor(SK_ColorTRANSPARENT)
79        , fDrawGpuBatchBounds(false) {
80    fUserMatrix.reset();
81
82    // SkPicturePlayback uses the base-class' quickReject calls to cull clipped
83    // operations. This can lead to problems in the debugger which expects all
84    // the operations in the captured skp to appear in the debug canvas. To
85    // circumvent this we create a wide open clip here (an empty clip rect
86    // is not sufficient).
87    // Internally, the SkRect passed to clipRect is converted to an SkIRect and
88    // rounded out. The following code creates a nearly maximal rect that will
89    // not get collapsed by the coming conversions (Due to precision loss the
90    // inset has to be surprisingly large).
91    SkIRect largeIRect = SkIRect::MakeLargest();
92    largeIRect.inset(1024, 1024);
93    SkRect large = SkRect::Make(largeIRect);
94#ifdef SK_DEBUG
95    SkASSERT(!large.roundOut().isEmpty());
96#endif
97    // call the base class' version to avoid adding a draw command
98    this->INHERITED::onClipRect(large, SkRegion::kReplace_Op, kHard_ClipEdgeStyle);
99}
100
101SkDebugCanvas::~SkDebugCanvas() {
102    fCommandVector.deleteAll();
103}
104
105void SkDebugCanvas::addDrawCommand(SkDrawCommand* command) {
106    fCommandVector.push(command);
107}
108
109void SkDebugCanvas::draw(SkCanvas* canvas) {
110    if (!fCommandVector.isEmpty()) {
111        this->drawTo(canvas, fCommandVector.count() - 1);
112    }
113}
114
115void SkDebugCanvas::applyUserTransform(SkCanvas* canvas) {
116    canvas->concat(fUserMatrix);
117}
118
119int SkDebugCanvas::getCommandAtPoint(int x, int y, int index) {
120    SkBitmap bitmap;
121    bitmap.allocPixels(SkImageInfo::MakeN32Premul(1, 1));
122
123    SkCanvas canvas(bitmap);
124    canvas.translate(SkIntToScalar(-x), SkIntToScalar(-y));
125    this->applyUserTransform(&canvas);
126
127    int layer = 0;
128    SkColor prev = bitmap.getColor(0,0);
129    for (int i = 0; i < index; i++) {
130        if (fCommandVector[i]->isVisible()) {
131            fCommandVector[i]->setUserMatrix(fUserMatrix);
132            fCommandVector[i]->execute(&canvas);
133        }
134        if (prev != bitmap.getColor(0,0)) {
135            layer = i;
136        }
137        prev = bitmap.getColor(0,0);
138    }
139    return layer;
140}
141
142class SkDebugClipVisitor : public SkCanvas::ClipVisitor {
143public:
144    SkDebugClipVisitor(SkCanvas* canvas) : fCanvas(canvas) {}
145
146    void clipRect(const SkRect& r, SkRegion::Op, bool doAA) override {
147        SkPaint p;
148        p.setColor(SK_ColorRED);
149        p.setStyle(SkPaint::kStroke_Style);
150        p.setAntiAlias(doAA);
151        fCanvas->drawRect(r, p);
152    }
153    void clipRRect(const SkRRect& rr, SkRegion::Op, bool doAA) override {
154        SkPaint p;
155        p.setColor(SK_ColorGREEN);
156        p.setStyle(SkPaint::kStroke_Style);
157        p.setAntiAlias(doAA);
158        fCanvas->drawRRect(rr, p);
159    }
160    void clipPath(const SkPath& path, SkRegion::Op, bool doAA) override {
161        SkPaint p;
162        p.setColor(SK_ColorBLUE);
163        p.setStyle(SkPaint::kStroke_Style);
164        p.setAntiAlias(doAA);
165        fCanvas->drawPath(path, p);
166    }
167
168protected:
169    SkCanvas* fCanvas;
170
171private:
172    typedef SkCanvas::ClipVisitor INHERITED;
173};
174
175// set up the saveLayer commands so that the active ones
176// return true in their 'active' method
177void SkDebugCanvas::markActiveCommands(int index) {
178    fActiveLayers.rewind();
179
180    for (int i = 0; i < fCommandVector.count(); ++i) {
181        fCommandVector[i]->setActive(false);
182    }
183
184    for (int i = 0; i < index; ++i) {
185        SkDrawCommand::Action result = fCommandVector[i]->action();
186        if (SkDrawCommand::kPushLayer_Action == result) {
187            fActiveLayers.push(fCommandVector[i]);
188        } else if (SkDrawCommand::kPopLayer_Action == result) {
189            fActiveLayers.pop();
190        }
191    }
192
193    for (int i = 0; i < fActiveLayers.count(); ++i) {
194        fActiveLayers[i]->setActive(true);
195    }
196
197}
198
199void SkDebugCanvas::drawTo(SkCanvas* canvas, int index, int m) {
200    SkASSERT(!fCommandVector.isEmpty());
201    SkASSERT(index < fCommandVector.count());
202
203    int saveCount = canvas->save();
204
205    SkRect windowRect = SkRect::MakeWH(SkIntToScalar(canvas->getBaseLayerSize().width()),
206                                       SkIntToScalar(canvas->getBaseLayerSize().height()));
207
208    bool pathOpsMode = getAllowSimplifyClip();
209    canvas->setAllowSimplifyClip(pathOpsMode);
210    canvas->clear(SK_ColorWHITE);
211    canvas->resetMatrix();
212    if (!windowRect.isEmpty()) {
213        canvas->clipRect(windowRect, SkRegion::kReplace_Op);
214    }
215    this->applyUserTransform(canvas);
216
217    if (fPaintFilterCanvas) {
218        fPaintFilterCanvas->addCanvas(canvas);
219        canvas = fPaintFilterCanvas.get();
220
221    }
222
223    if (fMegaVizMode) {
224        this->markActiveCommands(index);
225    }
226
227#if SK_SUPPORT_GPU
228    // If we have a GPU backend we can also visualize the batching information
229    GrAuditTrail* at = nullptr;
230    if (fDrawGpuBatchBounds || m != -1) {
231        at = this->getAuditTrail(canvas);
232    }
233#endif
234
235    for (int i = 0; i <= index; i++) {
236        if (i == index && fFilter) {
237            canvas->clear(0xAAFFFFFF);
238        }
239
240#if SK_SUPPORT_GPU
241        // We need to flush any pending operations, or they might batch with commands below.
242        // Previous operations were not registered with the audit trail when they were
243        // created, so if we allow them to combine, the audit trail will fail to find them.
244        canvas->flush();
245
246        GrAuditTrail::AutoCollectBatches* acb = nullptr;
247        if (at) {
248            acb = new GrAuditTrail::AutoCollectBatches(at, i);
249        }
250#endif
251
252        if (fCommandVector[i]->isVisible()) {
253            if (fMegaVizMode && fCommandVector[i]->active()) {
254                // "active" commands execute their visualization behaviors:
255                //     All active saveLayers get replaced with saves so all draws go to the
256                //     visible canvas.
257                //     All active culls draw their cull box
258                fCommandVector[i]->vizExecute(canvas);
259            } else {
260                fCommandVector[i]->setUserMatrix(fUserMatrix);
261                fCommandVector[i]->execute(canvas);
262            }
263        }
264#if SK_SUPPORT_GPU
265        if (at && acb) {
266            delete acb;
267        }
268#endif
269    }
270
271    if (SkColorGetA(fClipVizColor) != 0) {
272        canvas->save();
273        #define LARGE_COORD 1000000000
274        canvas->clipRect(SkRect::MakeLTRB(-LARGE_COORD, -LARGE_COORD, LARGE_COORD, LARGE_COORD),
275                       SkRegion::kReverseDifference_Op);
276        SkPaint clipPaint;
277        clipPaint.setColor(fClipVizColor);
278        canvas->drawPaint(clipPaint);
279        canvas->restore();
280    }
281
282    if (fMegaVizMode) {
283        canvas->save();
284        // nuke the CTM
285        canvas->resetMatrix();
286        // turn off clipping
287        if (!windowRect.isEmpty()) {
288            SkRect r = windowRect;
289            r.outset(SK_Scalar1, SK_Scalar1);
290            canvas->clipRect(r, SkRegion::kReplace_Op);
291        }
292        // visualize existing clips
293        SkDebugClipVisitor visitor(canvas);
294
295        canvas->replayClips(&visitor);
296
297        canvas->restore();
298    }
299    if (pathOpsMode) {
300        this->resetClipStackData();
301        const SkClipStack* clipStack = canvas->getClipStack();
302        SkClipStack::Iter iter(*clipStack, SkClipStack::Iter::kBottom_IterStart);
303        const SkClipStack::Element* element;
304        SkPath devPath;
305        while ((element = iter.next())) {
306            SkClipStack::Element::Type type = element->getType();
307            SkPath operand;
308            if (type != SkClipStack::Element::kEmpty_Type) {
309               element->asPath(&operand);
310            }
311            SkRegion::Op elementOp = element->getOp();
312            this->addClipStackData(devPath, operand, elementOp);
313            if (elementOp == SkRegion::kReplace_Op) {
314                devPath = operand;
315            } else {
316                Op(devPath, operand, (SkPathOp) elementOp, &devPath);
317            }
318        }
319        this->lastClipStackData(devPath);
320    }
321    fMatrix = canvas->getTotalMatrix();
322    if (!canvas->getClipDeviceBounds(&fClip)) {
323        fClip.setEmpty();
324    }
325
326    canvas->restoreToCount(saveCount);
327
328    if (fPaintFilterCanvas) {
329        fPaintFilterCanvas->removeAll();
330    }
331
332#if SK_SUPPORT_GPU
333    // draw any batches if required and issue a full reset onto GrAuditTrail
334    if (at) {
335        // just in case there is global reordering, we flush the canvas before querying
336        // GrAuditTrail
337        GrAuditTrail::AutoEnable ae(at);
338        canvas->flush();
339
340        // we pick three colorblind-safe colors, 75% alpha
341        static const SkColor kTotalBounds = SkColorSetARGB(0xC0, 0x6A, 0x3D, 0x9A);
342        static const SkColor kOpBatchBounds = SkColorSetARGB(0xC0, 0xE3, 0x1A, 0x1C);
343        static const SkColor kOtherBatchBounds = SkColorSetARGB(0xC0, 0xFF, 0x7F, 0x00);
344
345        // get the render target of the top device so we can ignore batches drawn offscreen
346        SkBaseDevice* bd = canvas->getDevice_just_for_deprecated_compatibility_testing();
347        SkGpuDevice* gbd = reinterpret_cast<SkGpuDevice*>(bd);
348        uint32_t rtID = gbd->accessRenderTarget()->getUniqueID();
349
350        // get the bounding boxes to draw
351        SkTArray<GrAuditTrail::BatchInfo> childrenBounds;
352        if (m == -1) {
353            at->getBoundsByClientID(&childrenBounds, index);
354        } else {
355            // the client wants us to draw the mth batch
356            at->getBoundsByBatchListID(&childrenBounds.push_back(), m);
357        }
358        SkPaint paint;
359        paint.setStyle(SkPaint::kStroke_Style);
360        paint.setStrokeWidth(1);
361        for (int i = 0; i < childrenBounds.count(); i++) {
362            if (childrenBounds[i].fRenderTargetUniqueID != rtID) {
363                // offscreen draw, ignore for now
364                continue;
365            }
366            paint.setColor(kTotalBounds);
367            canvas->drawRect(childrenBounds[i].fBounds, paint);
368            for (int j = 0; j < childrenBounds[i].fBatches.count(); j++) {
369                const GrAuditTrail::BatchInfo::Batch& batch = childrenBounds[i].fBatches[j];
370                if (batch.fClientID != index) {
371                    paint.setColor(kOtherBatchBounds);
372                } else {
373                    paint.setColor(kOpBatchBounds);
374                }
375                canvas->drawRect(batch.fBounds, paint);
376            }
377        }
378    }
379#endif
380    this->cleanupAuditTrail(canvas);
381}
382
383void SkDebugCanvas::deleteDrawCommandAt(int index) {
384    SkASSERT(index < fCommandVector.count());
385    delete fCommandVector[index];
386    fCommandVector.remove(index);
387}
388
389SkDrawCommand* SkDebugCanvas::getDrawCommandAt(int index) {
390    SkASSERT(index < fCommandVector.count());
391    return fCommandVector[index];
392}
393
394void SkDebugCanvas::setDrawCommandAt(int index, SkDrawCommand* command) {
395    SkASSERT(index < fCommandVector.count());
396    delete fCommandVector[index];
397    fCommandVector[index] = command;
398}
399
400const SkTDArray<SkString*>* SkDebugCanvas::getCommandInfo(int index) const {
401    SkASSERT(index < fCommandVector.count());
402    return fCommandVector[index]->Info();
403}
404
405bool SkDebugCanvas::getDrawCommandVisibilityAt(int index) {
406    SkASSERT(index < fCommandVector.count());
407    return fCommandVector[index]->isVisible();
408}
409
410const SkTDArray <SkDrawCommand*>& SkDebugCanvas::getDrawCommands() const {
411    return fCommandVector;
412}
413
414SkTDArray <SkDrawCommand*>& SkDebugCanvas::getDrawCommands() {
415    return fCommandVector;
416}
417
418GrAuditTrail* SkDebugCanvas::getAuditTrail(SkCanvas* canvas) {
419    GrAuditTrail* at = nullptr;
420#if SK_SUPPORT_GPU
421    GrContext* ctx = canvas->getGrContext();
422    if (ctx) {
423        at = ctx->getAuditTrail();
424    }
425#endif
426    return at;
427}
428
429void SkDebugCanvas::drawAndCollectBatches(int n, SkCanvas* canvas) {
430#if SK_SUPPORT_GPU
431    GrAuditTrail* at = this->getAuditTrail(canvas);
432    if (at) {
433        // loop over all of the commands and draw them, this is to collect reordering
434        // information
435        for (int i = 0; i < this->getSize() && i <= n; i++) {
436            GrAuditTrail::AutoCollectBatches enable(at, i);
437            fCommandVector[i]->execute(canvas);
438        }
439
440        // in case there is some kind of global reordering
441        {
442            GrAuditTrail::AutoEnable ae(at);
443            canvas->flush();
444        }
445    }
446#endif
447}
448
449void SkDebugCanvas::cleanupAuditTrail(SkCanvas* canvas) {
450    GrAuditTrail* at = this->getAuditTrail(canvas);
451    if (at) {
452#if SK_SUPPORT_GPU
453        GrAuditTrail::AutoEnable ae(at);
454        at->fullReset();
455#endif
456    }
457}
458
459Json::Value SkDebugCanvas::toJSON(UrlDataManager& urlDataManager, int n, SkCanvas* canvas) {
460    this->drawAndCollectBatches(n, canvas);
461
462    // now collect json
463#if SK_SUPPORT_GPU
464    GrAuditTrail* at = this->getAuditTrail(canvas);
465#endif
466    Json::Value result = Json::Value(Json::objectValue);
467    result[SKDEBUGCANVAS_ATTRIBUTE_VERSION] = Json::Value(SKDEBUGCANVAS_VERSION);
468    Json::Value commands = Json::Value(Json::arrayValue);
469    for (int i = 0; i < this->getSize() && i <= n; i++) {
470        commands[i] = this->getDrawCommandAt(i)->toJSON(urlDataManager);
471#if SK_SUPPORT_GPU
472        if (at) {
473            // TODO if this is inefficient we could add a method to GrAuditTrail which takes
474            // a Json::Value and is only compiled in this file
475            Json::Value parsedFromString;
476            Json::Reader reader;
477            SkAssertResult(reader.parse(at->toJson(i).c_str(), parsedFromString));
478
479            commands[i][SKDEBUGCANVAS_ATTRIBUTE_AUDITTRAIL] = parsedFromString;
480        }
481#endif
482    }
483    this->cleanupAuditTrail(canvas);
484    result[SKDEBUGCANVAS_ATTRIBUTE_COMMANDS] = commands;
485    return result;
486}
487
488Json::Value SkDebugCanvas::toJSONBatchList(int n, SkCanvas* canvas) {
489    this->drawAndCollectBatches(n, canvas);
490
491    Json::Value parsedFromString;
492#if SK_SUPPORT_GPU
493    GrAuditTrail* at = this->getAuditTrail(canvas);
494    if (at) {
495        GrAuditTrail::AutoManageBatchList enable(at);
496        Json::Reader reader;
497        SkAssertResult(reader.parse(at->toJson().c_str(), parsedFromString));
498    }
499#endif
500    this->cleanupAuditTrail(canvas);
501    return parsedFromString;
502}
503
504void SkDebugCanvas::updatePaintFilterCanvas() {
505    if (!fOverdrawViz && !fOverrideFilterQuality) {
506        fPaintFilterCanvas.reset(nullptr);
507        return;
508    }
509
510    const SkImageInfo info = this->imageInfo();
511    fPaintFilterCanvas.reset(new DebugPaintFilterCanvas(info.width(), info.height(), fOverdrawViz,
512                                                        fOverrideFilterQuality, fFilterQuality));
513}
514
515void SkDebugCanvas::setOverdrawViz(bool overdrawViz) {
516    if (fOverdrawViz == overdrawViz) {
517        return;
518    }
519
520    fOverdrawViz = overdrawViz;
521    this->updatePaintFilterCanvas();
522}
523
524void SkDebugCanvas::overrideTexFiltering(bool overrideTexFiltering, SkFilterQuality quality) {
525    if (fOverrideFilterQuality == overrideTexFiltering && fFilterQuality == quality) {
526        return;
527    }
528
529    fOverrideFilterQuality = overrideTexFiltering;
530    fFilterQuality = quality;
531    this->updatePaintFilterCanvas();
532}
533
534void SkDebugCanvas::onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle edgeStyle) {
535    this->addDrawCommand(new SkClipPathCommand(path, op, kSoft_ClipEdgeStyle == edgeStyle));
536}
537
538void SkDebugCanvas::onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle edgeStyle) {
539    this->addDrawCommand(new SkClipRectCommand(rect, op, kSoft_ClipEdgeStyle == edgeStyle));
540}
541
542void SkDebugCanvas::onClipRRect(const SkRRect& rrect, SkRegion::Op op, ClipEdgeStyle edgeStyle) {
543    this->addDrawCommand(new SkClipRRectCommand(rrect, op, kSoft_ClipEdgeStyle == edgeStyle));
544}
545
546void SkDebugCanvas::onClipRegion(const SkRegion& region, SkRegion::Op op) {
547    this->addDrawCommand(new SkClipRegionCommand(region, op));
548}
549
550void SkDebugCanvas::didConcat(const SkMatrix& matrix) {
551    this->addDrawCommand(new SkConcatCommand(matrix));
552    this->INHERITED::didConcat(matrix);
553}
554
555void SkDebugCanvas::onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) {
556    this->addDrawCommand(new SkDrawAnnotationCommand(rect, key, sk_ref_sp(value)));
557}
558
559void SkDebugCanvas::onDrawBitmap(const SkBitmap& bitmap, SkScalar left,
560                                 SkScalar top, const SkPaint* paint) {
561    this->addDrawCommand(new SkDrawBitmapCommand(bitmap, left, top, paint));
562}
563
564void SkDebugCanvas::onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
565                                     const SkPaint* paint, SrcRectConstraint constraint) {
566    this->addDrawCommand(new SkDrawBitmapRectCommand(bitmap, src, dst, paint,
567                                                     (SrcRectConstraint)constraint));
568}
569
570void SkDebugCanvas::onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
571                                     const SkRect& dst, const SkPaint* paint) {
572    this->addDrawCommand(new SkDrawBitmapNineCommand(bitmap, center, dst, paint));
573}
574
575void SkDebugCanvas::onDrawImage(const SkImage* image, SkScalar left, SkScalar top,
576                                const SkPaint* paint) {
577    this->addDrawCommand(new SkDrawImageCommand(image, left, top, paint));
578}
579
580void SkDebugCanvas::onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
581                                    const SkPaint* paint, SrcRectConstraint constraint) {
582    this->addDrawCommand(new SkDrawImageRectCommand(image, src, dst, paint, constraint));
583}
584
585void SkDebugCanvas::onDrawOval(const SkRect& oval, const SkPaint& paint) {
586    this->addDrawCommand(new SkDrawOvalCommand(oval, paint));
587}
588
589void SkDebugCanvas::onDrawPaint(const SkPaint& paint) {
590    this->addDrawCommand(new SkDrawPaintCommand(paint));
591}
592
593void SkDebugCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {
594    this->addDrawCommand(new SkDrawPathCommand(path, paint));
595}
596
597void SkDebugCanvas::onDrawPicture(const SkPicture* picture,
598                                  const SkMatrix* matrix,
599                                  const SkPaint* paint) {
600    this->addDrawCommand(new SkBeginDrawPictureCommand(picture, matrix, paint));
601    SkAutoCanvasMatrixPaint acmp(this, matrix, paint, picture->cullRect());
602    picture->playback(this);
603    this->addDrawCommand(new SkEndDrawPictureCommand(SkToBool(matrix) || SkToBool(paint)));
604}
605
606void SkDebugCanvas::onDrawPoints(PointMode mode, size_t count,
607                                 const SkPoint pts[], const SkPaint& paint) {
608    this->addDrawCommand(new SkDrawPointsCommand(mode, count, pts, paint));
609}
610
611void SkDebugCanvas::onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[],
612                                  const SkPaint& paint) {
613    this->addDrawCommand(new SkDrawPosTextCommand(text, byteLength, pos, paint));
614}
615
616void SkDebugCanvas::onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
617                                   SkScalar constY, const SkPaint& paint) {
618    this->addDrawCommand(
619        new SkDrawPosTextHCommand(text, byteLength, xpos, constY, paint));
620}
621
622void SkDebugCanvas::onDrawRect(const SkRect& rect, const SkPaint& paint) {
623    // NOTE(chudy): Messing up when renamed to DrawRect... Why?
624    addDrawCommand(new SkDrawRectCommand(rect, paint));
625}
626
627void SkDebugCanvas::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) {
628    this->addDrawCommand(new SkDrawRRectCommand(rrect, paint));
629}
630
631void SkDebugCanvas::onDrawDRRect(const SkRRect& outer, const SkRRect& inner,
632                                 const SkPaint& paint) {
633    this->addDrawCommand(new SkDrawDRRectCommand(outer, inner, paint));
634}
635
636void SkDebugCanvas::onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
637                               const SkPaint& paint) {
638    this->addDrawCommand(new SkDrawTextCommand(text, byteLength, x, y, paint));
639}
640
641void SkDebugCanvas::onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
642                                     const SkMatrix* matrix, const SkPaint& paint) {
643    this->addDrawCommand(
644        new SkDrawTextOnPathCommand(text, byteLength, path, matrix, paint));
645}
646
647void SkDebugCanvas::onDrawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
648                                      const SkRect* cull, const SkPaint& paint) {
649    this->addDrawCommand(new SkDrawTextRSXformCommand(text, byteLength, xform, cull, paint));
650}
651
652void SkDebugCanvas::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
653                                   const SkPaint& paint) {
654    this->addDrawCommand(new SkDrawTextBlobCommand(blob, x, y, paint));
655}
656
657void SkDebugCanvas::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
658                                const SkPoint texCoords[4], SkXfermode* xmode,
659                                const SkPaint& paint) {
660    this->addDrawCommand(new SkDrawPatchCommand(cubics, colors, texCoords, xmode, paint));
661}
662
663void SkDebugCanvas::onDrawVertices(VertexMode vmode, int vertexCount, const SkPoint vertices[],
664                                   const SkPoint texs[], const SkColor colors[],
665                                   SkXfermode*, const uint16_t indices[], int indexCount,
666                                   const SkPaint& paint) {
667    this->addDrawCommand(new SkDrawVerticesCommand(vmode, vertexCount, vertices,
668                         texs, colors, nullptr, indices, indexCount, paint));
669}
670
671void SkDebugCanvas::willRestore() {
672    this->addDrawCommand(new SkRestoreCommand());
673    this->INHERITED::willRestore();
674}
675
676void SkDebugCanvas::willSave() {
677    this->addDrawCommand(new SkSaveCommand());
678    this->INHERITED::willSave();
679}
680
681SkCanvas::SaveLayerStrategy SkDebugCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {
682    this->addDrawCommand(new SkSaveLayerCommand(rec));
683    (void)this->INHERITED::getSaveLayerStrategy(rec);
684    // No need for a full layer.
685    return kNoLayer_SaveLayerStrategy;
686}
687
688void SkDebugCanvas::didSetMatrix(const SkMatrix& matrix) {
689    this->addDrawCommand(new SkSetMatrixCommand(matrix));
690    this->INHERITED::didSetMatrix(matrix);
691}
692
693void SkDebugCanvas::toggleCommand(int index, bool toggle) {
694    SkASSERT(index < fCommandVector.count());
695    fCommandVector[index]->setVisible(toggle);
696}
697
698static const char* gFillTypeStrs[] = {
699    "kWinding_FillType",
700    "kEvenOdd_FillType",
701    "kInverseWinding_FillType",
702    "kInverseEvenOdd_FillType"
703};
704
705static const char* gOpStrs[] = {
706    "kDifference_PathOp",
707    "kIntersect_PathOp",
708    "kUnion_PathOp",
709    "kXor_PathOp",
710    "kReverseDifference_PathOp",
711};
712
713static const char kHTML4SpaceIndent[] = "&nbsp;&nbsp;&nbsp;&nbsp;";
714
715void SkDebugCanvas::outputScalar(SkScalar num) {
716    if (num == (int) num) {
717        fClipStackData.appendf("%d", (int) num);
718    } else {
719        SkString str;
720        str.printf("%1.9g", num);
721        int width = (int) str.size();
722        const char* cStr = str.c_str();
723        while (cStr[width - 1] == '0') {
724            --width;
725        }
726        str.resize(width);
727        fClipStackData.appendf("%sf", str.c_str());
728    }
729}
730
731void SkDebugCanvas::outputPointsCommon(const SkPoint* pts, int count) {
732    for (int index = 0; index < count; ++index) {
733        this->outputScalar(pts[index].fX);
734        fClipStackData.appendf(", ");
735        this->outputScalar(pts[index].fY);
736        if (index + 1 < count) {
737            fClipStackData.appendf(", ");
738        }
739    }
740}
741
742void SkDebugCanvas::outputPoints(const SkPoint* pts, int count) {
743    this->outputPointsCommon(pts, count);
744    fClipStackData.appendf(");<br>");
745}
746
747void SkDebugCanvas::outputConicPoints(const SkPoint* pts, SkScalar weight) {
748    this->outputPointsCommon(pts, 2);
749    fClipStackData.appendf(", ");
750    this->outputScalar(weight);
751    fClipStackData.appendf(");<br>");
752}
753
754void SkDebugCanvas::addPathData(const SkPath& path, const char* pathName) {
755    SkPath::RawIter iter(path);
756    SkPath::FillType fillType = path.getFillType();
757    fClipStackData.appendf("%sSkPath %s;<br>", kHTML4SpaceIndent, pathName);
758    fClipStackData.appendf("%s%s.setFillType(SkPath::%s);<br>", kHTML4SpaceIndent, pathName,
759            gFillTypeStrs[fillType]);
760    iter.setPath(path);
761    uint8_t verb;
762    SkPoint pts[4];
763    while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {
764        switch (verb) {
765            case SkPath::kMove_Verb:
766                fClipStackData.appendf("%s%s.moveTo(", kHTML4SpaceIndent, pathName);
767                this->outputPoints(&pts[0], 1);
768                continue;
769            case SkPath::kLine_Verb:
770                fClipStackData.appendf("%s%s.lineTo(", kHTML4SpaceIndent, pathName);
771                this->outputPoints(&pts[1], 1);
772                break;
773            case SkPath::kQuad_Verb:
774                fClipStackData.appendf("%s%s.quadTo(", kHTML4SpaceIndent, pathName);
775                this->outputPoints(&pts[1], 2);
776                break;
777            case SkPath::kConic_Verb:
778                fClipStackData.appendf("%s%s.conicTo(", kHTML4SpaceIndent, pathName);
779                this->outputConicPoints(&pts[1], iter.conicWeight());
780                break;
781            case SkPath::kCubic_Verb:
782                fClipStackData.appendf("%s%s.cubicTo(", kHTML4SpaceIndent, pathName);
783                this->outputPoints(&pts[1], 3);
784                break;
785            case SkPath::kClose_Verb:
786                fClipStackData.appendf("%s%s.close();<br>", kHTML4SpaceIndent, pathName);
787                break;
788            default:
789                SkDEBUGFAIL("bad verb");
790                return;
791        }
792    }
793}
794
795void SkDebugCanvas::addClipStackData(const SkPath& devPath, const SkPath& operand,
796                                     SkRegion::Op elementOp) {
797    if (elementOp == SkRegion::kReplace_Op) {
798        if (!lastClipStackData(devPath)) {
799            fSaveDevPath = operand;
800        }
801        fCalledAddStackData = false;
802    } else {
803        fClipStackData.appendf("<br>static void test(skiatest::Reporter* reporter,"
804            " const char* filename) {<br>");
805        addPathData(fCalledAddStackData ? devPath : fSaveDevPath, "path");
806        addPathData(operand, "pathB");
807        fClipStackData.appendf("%stestPathOp(reporter, path, pathB, %s, filename);<br>",
808            kHTML4SpaceIndent, gOpStrs[elementOp]);
809        fClipStackData.appendf("}<br>");
810        fCalledAddStackData = true;
811    }
812}
813
814bool SkDebugCanvas::lastClipStackData(const SkPath& devPath) {
815    if (fCalledAddStackData) {
816        fClipStackData.appendf("<br>");
817        addPathData(devPath, "pathOut");
818        return true;
819    }
820    return false;
821}
822