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