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