SkiaCanvasProxy.cpp revision f35b989d26bb98900f6c5fa2e586326b30b6e161
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "SkiaCanvasProxy.h"
18
19#include <cutils/log.h>
20#include <SkPatchUtils.h>
21#include <SkPaint.h>
22#include <SkPath.h>
23#include <SkPixelRef.h>
24#include <SkRect.h>
25#include <SkRRect.h>
26
27#include <memory>
28
29namespace android {
30namespace uirenderer {
31
32SkiaCanvasProxy::SkiaCanvasProxy(Canvas* canvas, bool filterHwuiCalls)
33        : INHERITED(canvas->width(), canvas->height())
34        , mCanvas(canvas)
35        , mFilterHwuiCalls(filterHwuiCalls) {}
36
37void SkiaCanvasProxy::onDrawPaint(const SkPaint& paint) {
38    mCanvas->drawPaint(paint);
39}
40
41void SkiaCanvasProxy::onDrawPoints(PointMode pointMode, size_t count, const SkPoint pts[],
42        const SkPaint& paint) {
43    if (!pts || count == 0) {
44        return;
45    }
46
47    // convert the SkPoints into floats
48    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
49    const size_t floatCount = count << 1;
50    const float* floatArray = &pts[0].fX;
51
52    switch (pointMode) {
53        case kPoints_PointMode: {
54            mCanvas->drawPoints(floatArray, floatCount, paint);
55            break;
56        }
57        case kLines_PointMode: {
58            mCanvas->drawLines(floatArray, floatCount, paint);
59            break;
60        }
61        case kPolygon_PointMode: {
62            SkPaint strokedPaint(paint);
63            strokedPaint.setStyle(SkPaint::kStroke_Style);
64
65            SkPath path;
66            for (size_t i = 0; i < count - 1; i++) {
67                path.moveTo(pts[i]);
68                path.lineTo(pts[i+1]);
69                this->drawPath(path, strokedPaint);
70                path.rewind();
71            }
72            break;
73        }
74        default:
75            LOG_ALWAYS_FATAL("Unknown point type");
76    }
77}
78
79void SkiaCanvasProxy::onDrawOval(const SkRect& rect, const SkPaint& paint) {
80    mCanvas->drawOval(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, paint);
81}
82
83void SkiaCanvasProxy::onDrawRect(const SkRect& rect, const SkPaint& paint) {
84    mCanvas->drawRect(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, paint);
85}
86
87void SkiaCanvasProxy::onDrawRRect(const SkRRect& roundRect, const SkPaint& paint) {
88    if (!roundRect.isComplex()) {
89        const SkRect& rect = roundRect.rect();
90        SkVector radii = roundRect.getSimpleRadii();
91        mCanvas->drawRoundRect(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom,
92                               radii.fX, radii.fY, paint);
93    } else {
94        SkPath path;
95        path.addRRect(roundRect);
96        mCanvas->drawPath(path, paint);
97    }
98}
99
100void SkiaCanvasProxy::onDrawPath(const SkPath& path, const SkPaint& paint) {
101    mCanvas->drawPath(path, paint);
102}
103
104void SkiaCanvasProxy::onDrawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
105        const SkPaint* paint) {
106    SkPixelRef* pxRef = bitmap.pixelRef();
107
108    // HWUI doesn't support extractSubset(), so convert any subsetted bitmap into
109    // a drawBitmapRect(); pass through an un-subsetted bitmap.
110    if (pxRef && bitmap.dimensions() != pxRef->info().dimensions()) {
111        SkBitmap fullBitmap;
112        fullBitmap.setInfo(pxRef->info());
113        fullBitmap.setPixelRef(pxRef, 0, 0);
114        SkIPoint origin = bitmap.pixelRefOrigin();
115        mCanvas->drawBitmap(fullBitmap, origin.fX, origin.fY,
116                            origin.fX + bitmap.dimensions().width(),
117                            origin.fY + bitmap.dimensions().height(),
118                            left, top,
119                            left + bitmap.dimensions().width(),
120                            top + bitmap.dimensions().height(),
121                            paint);
122    } else {
123        mCanvas->drawBitmap(bitmap, left, top, paint);
124    }
125}
126
127void SkiaCanvasProxy::onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* srcPtr,
128        const SkRect& dst, const SkPaint* paint, SrcRectConstraint) {
129    SkRect src = (srcPtr) ? *srcPtr : SkRect::MakeWH(bitmap.width(), bitmap.height());
130    // TODO: if bitmap is a subset, do we need to add pixelRefOrigin to src?
131    mCanvas->drawBitmap(bitmap, src.fLeft, src.fTop, src.fRight, src.fBottom,
132                        dst.fLeft, dst.fTop, dst.fRight, dst.fBottom, paint);
133}
134
135void SkiaCanvasProxy::onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
136        const SkRect& dst, const SkPaint*) {
137    //TODO make nine-patch drawing a method on Canvas.h
138    SkDEBUGFAIL("SkiaCanvasProxy::onDrawBitmapNine is not yet supported");
139}
140
141void SkiaCanvasProxy::onDrawSprite(const SkBitmap& bitmap, int left, int top,
142        const SkPaint* paint) {
143    // TODO: if bitmap is a subset, do we need to add pixelRefOrigin to src?
144    mCanvas->save(SkCanvas::kMatrixClip_SaveFlag);
145    mCanvas->setMatrix(SkMatrix::I());
146    mCanvas->drawBitmap(bitmap, left, top, paint);
147    mCanvas->restore();
148}
149
150void SkiaCanvasProxy::onDrawVertices(VertexMode mode, int vertexCount, const SkPoint vertices[],
151        const SkPoint texs[], const SkColor colors[], SkXfermode*, const uint16_t indices[],
152        int indexCount, const SkPaint& paint) {
153    if (mFilterHwuiCalls) {
154        return;
155    }
156    // convert the SkPoints into floats
157    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
158    const int floatCount = vertexCount << 1;
159    const float* vArray = &vertices[0].fX;
160    const float* tArray = (texs) ? &texs[0].fX : NULL;
161    const int* cArray = (colors) ? (int*)colors : NULL;
162    mCanvas->drawVertices(mode, floatCount, vArray, tArray, cArray, indices, indexCount, paint);
163}
164
165SkSurface* SkiaCanvasProxy::onNewSurface(const SkImageInfo&, const SkSurfaceProps&) {
166    SkDEBUGFAIL("SkiaCanvasProxy::onNewSurface is not supported");
167    return NULL;
168}
169
170void SkiaCanvasProxy::willSave() {
171    mCanvas->save(SkCanvas::kMatrixClip_SaveFlag);
172}
173
174SkCanvas::SaveLayerStrategy SkiaCanvasProxy::willSaveLayer(const SkRect* rectPtr,
175        const SkPaint* paint, SaveFlags flags) {
176    SkRect rect;
177    if (rectPtr) {
178        rect = *rectPtr;
179    } else if(!mCanvas->getClipBounds(&rect)) {
180        rect = SkRect::MakeEmpty();
181    }
182    mCanvas->saveLayer(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, paint, flags);
183    return SkCanvas::kNoLayer_SaveLayerStrategy;
184}
185
186void SkiaCanvasProxy::willRestore() {
187    mCanvas->restore();
188}
189
190void SkiaCanvasProxy::didConcat(const SkMatrix& matrix) {
191    mCanvas->concat(matrix);
192}
193
194void SkiaCanvasProxy::didSetMatrix(const SkMatrix& matrix) {
195    mCanvas->setMatrix(matrix);
196}
197
198void SkiaCanvasProxy::onDrawDRRect(const SkRRect& outer, const SkRRect& inner,
199        const SkPaint& paint) {
200    SkPath path;
201    path.addRRect(outer);
202    path.addRRect(inner);
203    path.setFillType(SkPath::kEvenOdd_FillType);
204    this->drawPath(path, paint);
205}
206
207/**
208 * Utility class that converts the incoming text & paint from the given encoding
209 * into glyphIDs.
210 */
211class GlyphIDConverter {
212public:
213    GlyphIDConverter(const void* text, size_t byteLength, const SkPaint& origPaint) {
214        paint = origPaint;
215        if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
216            glyphIDs = (uint16_t*)text;
217            count = byteLength >> 1;
218        } else {
219             // ensure space for one glyph per ID given UTF8 encoding.
220            storage.reset(new uint16_t[byteLength]);
221            glyphIDs = storage.get();
222            count = paint.textToGlyphs(text, byteLength, storage.get());
223            paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
224        }
225    }
226
227    SkPaint paint;
228    uint16_t* glyphIDs;
229    int count;
230private:
231    std::unique_ptr<uint16_t[]> storage;
232};
233
234void SkiaCanvasProxy::onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
235        const SkPaint& origPaint) {
236    // convert to glyphIDs if necessary
237    GlyphIDConverter glyphs(text, byteLength, origPaint);
238
239    // compute the glyph positions
240    std::unique_ptr<SkPoint[]> pointStorage(new SkPoint[glyphs.count]);
241    std::unique_ptr<SkScalar[]> glyphWidths(new SkScalar[glyphs.count]);
242    glyphs.paint.getTextWidths(glyphs.glyphIDs, glyphs.count << 1, glyphWidths.get());
243
244    // compute conservative bounds
245    // NOTE: We could call the faster paint.getFontBounds for a less accurate,
246    //       but even more conservative bounds if this  is too slow.
247    SkRect bounds;
248    glyphs.paint.measureText(glyphs.glyphIDs, glyphs.count << 1, &bounds);
249
250    // adjust for non-left alignment
251    if (glyphs.paint.getTextAlign() != SkPaint::kLeft_Align) {
252        SkScalar stop = 0;
253        for (int i = 0; i < glyphs.count; i++) {
254            stop += glyphWidths[i];
255        }
256        if (glyphs.paint.getTextAlign() == SkPaint::kCenter_Align) {
257            stop = SkScalarHalf(stop);
258        }
259        if (glyphs.paint.isVerticalText()) {
260            y -= stop;
261        } else {
262            x -= stop;
263        }
264    }
265
266    // setup the first glyph position and adjust bounds if needed
267    int xBaseline = 0;
268    int yBaseline = 0;
269    if (mCanvas->drawTextAbsolutePos()) {
270        bounds.offset(x,y);
271        xBaseline = x;
272        yBaseline = y;
273    }
274    pointStorage[0].set(xBaseline, yBaseline);
275
276    // setup the remaining glyph positions
277    if (glyphs.paint.isVerticalText()) {
278        for (int i = 1; i < glyphs.count; i++) {
279            pointStorage[i].set(xBaseline, glyphWidths[i-1] + pointStorage[i-1].fY);
280        }
281    } else {
282        for (int i = 1; i < glyphs.count; i++) {
283            pointStorage[i].set(glyphWidths[i-1] + pointStorage[i-1].fX, yBaseline);
284        }
285    }
286
287    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
288    mCanvas->drawText(glyphs.glyphIDs, &pointStorage[0].fX, glyphs.count, glyphs.paint,
289                      x, y, bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, 0);
290}
291
292void SkiaCanvasProxy::onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[],
293        const SkPaint& origPaint) {
294    // convert to glyphIDs if necessary
295    GlyphIDConverter glyphs(text, byteLength, origPaint);
296
297    // convert to relative positions if necessary
298    int x, y;
299    const SkPoint* posArray;
300    std::unique_ptr<SkPoint[]> pointStorage;
301    if (mCanvas->drawTextAbsolutePos()) {
302        x = 0;
303        y = 0;
304        posArray = pos;
305    } else {
306        x = pos[0].fX;
307        y = pos[0].fY;
308        pointStorage.reset(new SkPoint[glyphs.count]);
309        for (int i = 0; i < glyphs.count; i++) {
310            pointStorage[i].fX = pos[i].fX - x;
311            pointStorage[i].fY = pos[i].fY - y;
312        }
313        posArray = pointStorage.get();
314    }
315
316    // compute conservative bounds
317    // NOTE: We could call the faster paint.getFontBounds for a less accurate,
318    //       but even more conservative bounds if this  is too slow.
319    SkRect bounds;
320    glyphs.paint.measureText(glyphs.glyphIDs, glyphs.count << 1, &bounds);
321    bounds.offset(x, y);
322
323    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
324    mCanvas->drawText(glyphs.glyphIDs, &posArray[0].fX, glyphs.count, glyphs.paint, x, y,
325                      bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, 0);
326}
327
328void SkiaCanvasProxy::onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
329        SkScalar constY, const SkPaint& paint) {
330    const size_t pointCount = byteLength >> 1;
331    std::unique_ptr<SkPoint[]> pts(new SkPoint[pointCount]);
332    for (size_t i = 0; i < pointCount; i++) {
333        pts[i].set(xpos[i], constY);
334    }
335    this->onDrawPosText(text, byteLength, pts.get(), paint);
336}
337
338void SkiaCanvasProxy::onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
339        const SkMatrix* matrix, const SkPaint& origPaint) {
340    // convert to glyphIDs if necessary
341    GlyphIDConverter glyphs(text, byteLength, origPaint);
342    mCanvas->drawTextOnPath(glyphs.glyphIDs, glyphs.count, path, 0, 0, glyphs.paint);
343}
344
345void SkiaCanvasProxy::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
346        const SkPaint& paint) {
347    SkDEBUGFAIL("SkiaCanvasProxy::onDrawTextBlob is not supported");
348}
349
350void SkiaCanvasProxy::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
351        const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint) {
352    if (mFilterHwuiCalls) {
353        return;
354    }
355    SkPatchUtils::VertexData data;
356
357    SkMatrix matrix;
358    mCanvas->getMatrix(&matrix);
359    SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, &matrix);
360
361    // It automatically adjusts lodX and lodY in case it exceeds the number of indices.
362    // If it fails to generate the vertices, then we do not draw.
363    if (SkPatchUtils::getVertexData(&data, cubics, colors, texCoords, lod.width(), lod.height())) {
364        this->drawVertices(SkCanvas::kTriangles_VertexMode, data.fVertexCount, data.fPoints,
365                           data.fTexCoords, data.fColors, xmode, data.fIndices, data.fIndexCount,
366                           paint);
367    }
368}
369
370void SkiaCanvasProxy::onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle) {
371    mCanvas->clipRect(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, op);
372}
373
374void SkiaCanvasProxy::onClipRRect(const SkRRect& roundRect, SkRegion::Op op, ClipEdgeStyle) {
375    SkPath path;
376    path.addRRect(roundRect);
377    mCanvas->clipPath(&path, op);
378}
379
380void SkiaCanvasProxy::onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle) {
381    mCanvas->clipPath(&path, op);
382}
383
384void SkiaCanvasProxy::onClipRegion(const SkRegion& region, SkRegion::Op op) {
385    mCanvas->clipRegion(&region, op);
386}
387
388}; // namespace uirenderer
389}; // namespace android
390