SkiaCanvasProxy.cpp revision 9969111d9c8017cdd439edbb2c54ef9678b24a59
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 <memory>
20
21#include <log/log.h>
22
23#include "hwui/Bitmap.h"
24#include <SkLatticeIter.h>
25#include <SkPatchUtils.h>
26#include <SkPaint.h>
27#include <SkPath.h>
28#include <SkPixelRef.h>
29#include <SkRect.h>
30#include <SkRRect.h>
31#include <SkRSXform.h>
32#include <SkSurface.h>
33#include <SkTextBlobRunIterator.h>
34
35namespace android {
36namespace uirenderer {
37
38SkiaCanvasProxy::SkiaCanvasProxy(Canvas* canvas, bool filterHwuiCalls)
39        : INHERITED(canvas->width(), canvas->height())
40        , mCanvas(canvas)
41        , mFilterHwuiCalls(filterHwuiCalls) {}
42
43void SkiaCanvasProxy::onDrawPaint(const SkPaint& paint) {
44    mCanvas->drawPaint(paint);
45}
46
47void SkiaCanvasProxy::onDrawPoints(PointMode pointMode, size_t count, const SkPoint pts[],
48        const SkPaint& paint) {
49    if (!pts || count == 0) {
50        return;
51    }
52
53    // convert the SkPoints into floats
54    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
55    const size_t floatCount = count << 1;
56    const float* floatArray = &pts[0].fX;
57
58    switch (pointMode) {
59        case kPoints_PointMode: {
60            mCanvas->drawPoints(floatArray, floatCount, paint);
61            break;
62        }
63        case kLines_PointMode: {
64            mCanvas->drawLines(floatArray, floatCount, paint);
65            break;
66        }
67        case kPolygon_PointMode: {
68            SkPaint strokedPaint(paint);
69            strokedPaint.setStyle(SkPaint::kStroke_Style);
70
71            SkPath path;
72            for (size_t i = 0; i < count - 1; i++) {
73                path.moveTo(pts[i]);
74                path.lineTo(pts[i+1]);
75                this->drawPath(path, strokedPaint);
76                path.rewind();
77            }
78            break;
79        }
80        default:
81            LOG_ALWAYS_FATAL("Unknown point type");
82    }
83}
84
85void SkiaCanvasProxy::onDrawOval(const SkRect& rect, const SkPaint& paint) {
86    mCanvas->drawOval(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, paint);
87}
88
89void SkiaCanvasProxy::onDrawRect(const SkRect& rect, const SkPaint& paint) {
90    mCanvas->drawRect(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, paint);
91}
92
93void SkiaCanvasProxy::onDrawRRect(const SkRRect& roundRect, const SkPaint& paint) {
94    if (!roundRect.isComplex()) {
95        const SkRect& rect = roundRect.rect();
96        SkVector radii = roundRect.getSimpleRadii();
97        mCanvas->drawRoundRect(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom,
98                               radii.fX, radii.fY, paint);
99    } else {
100        SkPath path;
101        path.addRRect(roundRect);
102        mCanvas->drawPath(path, paint);
103    }
104}
105
106void SkiaCanvasProxy::onDrawArc(const SkRect& rect, SkScalar startAngle, SkScalar sweepAngle,
107                                bool useCenter, const SkPaint& paint) {
108    mCanvas->drawArc(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom,
109                     startAngle, sweepAngle, useCenter, paint);
110}
111
112void SkiaCanvasProxy::onDrawPath(const SkPath& path, const SkPaint& paint) {
113    mCanvas->drawPath(path, paint);
114}
115
116void SkiaCanvasProxy::onDrawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
117        const SkPaint* paint) {
118    sk_sp<Bitmap> hwuiBitmap = Bitmap::createFrom(bitmap.info(), *bitmap.pixelRef());
119    // HWUI doesn't support extractSubset(), so convert any subsetted bitmap into
120    // a drawBitmapRect(); pass through an un-subsetted bitmap.
121    if (hwuiBitmap && bitmap.dimensions() != hwuiBitmap->info().dimensions()) {
122        SkIPoint origin = bitmap.pixelRefOrigin();
123        mCanvas->drawBitmap(*hwuiBitmap, origin.fX, origin.fY,
124                            origin.fX + bitmap.dimensions().width(),
125                            origin.fY + bitmap.dimensions().height(),
126                            left, top,
127                            left + bitmap.dimensions().width(),
128                            top + bitmap.dimensions().height(),
129                            paint);
130    } else {
131        mCanvas->drawBitmap(*hwuiBitmap, left, top, paint);
132    }
133}
134
135void SkiaCanvasProxy::onDrawBitmapRect(const SkBitmap& skBitmap, const SkRect* srcPtr,
136        const SkRect& dst, const SkPaint* paint, SrcRectConstraint) {
137    SkRect src = (srcPtr) ? *srcPtr : SkRect::MakeWH(skBitmap.width(), skBitmap.height());
138    // TODO: if bitmap is a subset, do we need to add pixelRefOrigin to src?
139   Bitmap* bitmap = reinterpret_cast<Bitmap*>(skBitmap.pixelRef());
140   mCanvas->drawBitmap(*bitmap, src.fLeft, src.fTop, src.fRight, src.fBottom,
141                        dst.fLeft, dst.fTop, dst.fRight, dst.fBottom, paint);
142}
143
144void SkiaCanvasProxy::onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
145        const SkRect& dst, const SkPaint*) {
146    //TODO make nine-patch drawing a method on Canvas.h
147    SkDEBUGFAIL("SkiaCanvasProxy::onDrawBitmapNine is not yet supported");
148}
149
150void SkiaCanvasProxy::onDrawImage(const SkImage* image, SkScalar left, SkScalar top,
151        const SkPaint* paint) {
152    SkBitmap skiaBitmap;
153    if (image->asLegacyBitmap(&skiaBitmap, SkImage::kRO_LegacyBitmapMode)) {
154        onDrawBitmap(skiaBitmap, left, top, paint);
155    }
156}
157
158void SkiaCanvasProxy::onDrawImageRect(const SkImage* image, const SkRect* srcPtr, const SkRect& dst,
159        const SkPaint* paint, SrcRectConstraint constraint) {
160    SkBitmap skiaBitmap;
161    if (image->asLegacyBitmap(&skiaBitmap, SkImage::kRO_LegacyBitmapMode)) {
162        sk_sp<Bitmap> bitmap = Bitmap::createFrom(skiaBitmap.info(), *skiaBitmap.pixelRef());
163        SkRect src = (srcPtr) ? *srcPtr : SkRect::MakeWH(image->width(), image->height());
164        mCanvas->drawBitmap(*bitmap, src.fLeft, src.fTop, src.fRight, src.fBottom,
165                dst.fLeft, dst.fTop, dst.fRight, dst.fBottom, paint);
166    }
167}
168
169void SkiaCanvasProxy::onDrawImageNine(const SkImage*, const SkIRect& center, const SkRect& dst,
170        const SkPaint*) {
171    SkDEBUGFAIL("SkiaCanvasProxy::onDrawImageNine is not yet supported");
172}
173
174void SkiaCanvasProxy::onDrawImageLattice(const SkImage* image, const Lattice& lattice,
175        const SkRect& dst, const SkPaint* paint) {
176    SkLatticeIter iter(lattice, dst);
177    SkRect srcR, dstR;
178    while (iter.next(&srcR, &dstR)) {
179        onDrawImageRect(image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
180    }
181}
182
183void SkiaCanvasProxy::onDrawVertices(VertexMode mode, int vertexCount, const SkPoint vertices[],
184        const SkPoint texs[], const SkColor colors[], SkBlendMode, const uint16_t indices[],
185        int indexCount, const SkPaint& paint) {
186    // TODO: should we pass through blendmode
187    if (mFilterHwuiCalls) {
188        return;
189    }
190    // convert the SkPoints into floats
191    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
192    const int floatCount = vertexCount << 1;
193    const float* vArray = &vertices[0].fX;
194    const float* tArray = (texs) ? &texs[0].fX : NULL;
195    const int* cArray = (colors) ? (int*)colors : NULL;
196    mCanvas->drawVertices(mode, floatCount, vArray, tArray, cArray, indices, indexCount, paint);
197}
198
199sk_sp<SkSurface> SkiaCanvasProxy::onNewSurface(const SkImageInfo&, const SkSurfaceProps&) {
200    SkDEBUGFAIL("SkiaCanvasProxy::onNewSurface is not supported");
201    return NULL;
202}
203
204void SkiaCanvasProxy::willSave() {
205    mCanvas->save(android::SaveFlags::MatrixClip);
206}
207
208static inline SaveFlags::Flags saveFlags(SkCanvas::SaveLayerFlags layerFlags) {
209    SaveFlags::Flags saveFlags = 0;
210
211    if (!(layerFlags & SkCanvas::kDontClipToLayer_Legacy_SaveLayerFlag)) {
212        saveFlags |= SaveFlags::ClipToLayer;
213    }
214
215    if (!(layerFlags & SkCanvas::kIsOpaque_SaveLayerFlag)) {
216        saveFlags |= SaveFlags::HasAlphaLayer;
217    }
218
219    return saveFlags;
220}
221
222SkCanvas::SaveLayerStrategy SkiaCanvasProxy::getSaveLayerStrategy(const SaveLayerRec& saveLayerRec) {
223    SkRect rect;
224    if (saveLayerRec.fBounds) {
225        rect = *saveLayerRec.fBounds;
226    } else if (!mCanvas->getClipBounds(&rect)) {
227        rect = SkRect::MakeEmpty();
228    }
229    mCanvas->saveLayer(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, saveLayerRec.fPaint,
230                       saveFlags(saveLayerRec.fSaveLayerFlags));
231    return SkCanvas::kNoLayer_SaveLayerStrategy;
232}
233
234void SkiaCanvasProxy::willRestore() {
235    mCanvas->restore();
236}
237
238void SkiaCanvasProxy::didConcat(const SkMatrix& matrix) {
239    mCanvas->concat(matrix);
240}
241
242void SkiaCanvasProxy::didSetMatrix(const SkMatrix& matrix) {
243    mCanvas->setMatrix(matrix);
244}
245
246void SkiaCanvasProxy::onDrawDRRect(const SkRRect& outer, const SkRRect& inner,
247        const SkPaint& paint) {
248    SkPath path;
249    path.addRRect(outer);
250    path.addRRect(inner);
251    path.setFillType(SkPath::kEvenOdd_FillType);
252    this->drawPath(path, paint);
253}
254
255/**
256 * Utility class that converts the incoming text & paint from the given encoding
257 * into glyphIDs.
258 */
259class GlyphIDConverter {
260public:
261    GlyphIDConverter(const void* text, size_t byteLength, const SkPaint& origPaint) {
262        paint = origPaint;
263        if (paint.getTextEncoding() == SkPaint::kGlyphID_TextEncoding) {
264            glyphIDs = (uint16_t*)text;
265            count = byteLength >> 1;
266        } else {
267             // ensure space for one glyph per ID given UTF8 encoding.
268            storage.reset(new uint16_t[byteLength]);
269            glyphIDs = storage.get();
270            count = paint.textToGlyphs(text, byteLength, storage.get());
271            paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
272        }
273    }
274
275    SkPaint paint;
276    uint16_t* glyphIDs;
277    int count;
278private:
279    std::unique_ptr<uint16_t[]> storage;
280};
281
282void SkiaCanvasProxy::onDrawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
283        const SkPaint& origPaint) {
284    // convert to glyphIDs if necessary
285    GlyphIDConverter glyphs(text, byteLength, origPaint);
286
287    // compute the glyph positions
288    std::unique_ptr<SkPoint[]> pointStorage(new SkPoint[glyphs.count]);
289    std::unique_ptr<SkScalar[]> glyphWidths(new SkScalar[glyphs.count]);
290    glyphs.paint.getTextWidths(glyphs.glyphIDs, glyphs.count << 1, glyphWidths.get());
291
292    // compute conservative bounds
293    // NOTE: We could call the faster paint.getFontBounds for a less accurate,
294    //       but even more conservative bounds if this  is too slow.
295    SkRect bounds;
296    glyphs.paint.measureText(glyphs.glyphIDs, glyphs.count << 1, &bounds);
297
298    // adjust for non-left alignment
299    if (glyphs.paint.getTextAlign() != SkPaint::kLeft_Align) {
300        SkScalar stop = 0;
301        for (int i = 0; i < glyphs.count; i++) {
302            stop += glyphWidths[i];
303        }
304        if (glyphs.paint.getTextAlign() == SkPaint::kCenter_Align) {
305            stop = SkScalarHalf(stop);
306        }
307        if (glyphs.paint.isVerticalText()) {
308            y -= stop;
309        } else {
310            x -= stop;
311        }
312    }
313
314    // setup the first glyph position and adjust bounds if needed
315    int xBaseline = 0;
316    int yBaseline = 0;
317    if (mCanvas->drawTextAbsolutePos()) {
318        bounds.offset(x,y);
319        xBaseline = x;
320        yBaseline = y;
321    }
322    pointStorage[0].set(xBaseline, yBaseline);
323
324    // setup the remaining glyph positions
325    if (glyphs.paint.isVerticalText()) {
326        for (int i = 1; i < glyphs.count; i++) {
327            pointStorage[i].set(xBaseline, glyphWidths[i-1] + pointStorage[i-1].fY);
328        }
329    } else {
330        for (int i = 1; i < glyphs.count; i++) {
331            pointStorage[i].set(glyphWidths[i-1] + pointStorage[i-1].fX, yBaseline);
332        }
333    }
334
335    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
336    mCanvas->drawGlyphs(glyphs.glyphIDs, &pointStorage[0].fX, glyphs.count, glyphs.paint,
337                      x, y, bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, 0);
338}
339
340void SkiaCanvasProxy::onDrawPosText(const void* text, size_t byteLength, const SkPoint pos[],
341        const SkPaint& origPaint) {
342    // convert to glyphIDs if necessary
343    GlyphIDConverter glyphs(text, byteLength, origPaint);
344
345    // convert to relative positions if necessary
346    int x, y;
347    const SkPoint* posArray;
348    std::unique_ptr<SkPoint[]> pointStorage;
349    if (mCanvas->drawTextAbsolutePos()) {
350        x = 0;
351        y = 0;
352        posArray = pos;
353    } else {
354        x = pos[0].fX;
355        y = pos[0].fY;
356        pointStorage.reset(new SkPoint[glyphs.count]);
357        for (int i = 0; i < glyphs.count; i++) {
358            pointStorage[i].fX = pos[i].fX - x;
359            pointStorage[i].fY = pos[i].fY - y;
360        }
361        posArray = pointStorage.get();
362    }
363
364    // Compute conservative bounds.  If the content has already been processed
365    // by Minikin then it had already computed these bounds.  Unfortunately,
366    // there is no way to capture those bounds as part of the Skia drawPosText
367    // API so we need to do that computation again here.
368    SkRect bounds = SkRect::MakeEmpty();
369    for (int i = 0; i < glyphs.count; i++) {
370        SkRect glyphBounds = SkRect::MakeEmpty();
371        glyphs.paint.measureText(&glyphs.glyphIDs[i], sizeof(uint16_t), &glyphBounds);
372        glyphBounds.offset(pos[i].fX, pos[i].fY);
373        bounds.join(glyphBounds);
374    }
375
376    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
377    mCanvas->drawGlyphs(glyphs.glyphIDs, &posArray[0].fX, glyphs.count, glyphs.paint, x, y,
378                      bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, 0);
379}
380
381void SkiaCanvasProxy::onDrawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
382        SkScalar constY, const SkPaint& paint) {
383    const size_t pointCount = byteLength >> 1;
384    std::unique_ptr<SkPoint[]> pts(new SkPoint[pointCount]);
385    for (size_t i = 0; i < pointCount; i++) {
386        pts[i].set(xpos[i], constY);
387    }
388    this->onDrawPosText(text, byteLength, pts.get(), paint);
389}
390
391void SkiaCanvasProxy::onDrawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
392        const SkMatrix* matrix, const SkPaint& origPaint) {
393    SkDEBUGFAIL("SkiaCanvasProxy::onDrawTextOnPath is not supported");
394}
395
396void SkiaCanvasProxy::onDrawTextRSXform(const void* text, size_t byteLength,
397        const SkRSXform xform[], const SkRect* cullRect, const SkPaint& paint) {
398    GlyphIDConverter glyphs(text, byteLength, paint); // Just get count
399    SkMatrix localM, currM, origM;
400    mCanvas->getMatrix(&currM);
401    origM = currM;
402    for (int i = 0; i < glyphs.count; i++) {
403        localM.setRSXform(*xform++);
404        currM.setConcat(origM, localM);
405        mCanvas->setMatrix(currM);
406        this->onDrawText((char*)text + (byteLength / glyphs.count * i),
407                         byteLength / glyphs.count, 0, 0, paint);
408    }
409    mCanvas->setMatrix(origM);
410}
411
412
413void SkiaCanvasProxy::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
414        const SkPaint& paint) {
415    SkPaint runPaint = paint;
416
417     SkTextBlobRunIterator it(blob);
418     for (;!it.done(); it.next()) {
419         size_t textLen = it.glyphCount() * sizeof(uint16_t);
420         const SkPoint& offset = it.offset();
421         // applyFontToPaint() always overwrites the exact same attributes,
422         // so it is safe to not re-seed the paint for this reason.
423         it.applyFontToPaint(&runPaint);
424
425         switch (it.positioning()) {
426         case SkTextBlob::kDefault_Positioning:
427             this->drawText(it.glyphs(), textLen, x + offset.x(), y + offset.y(), runPaint);
428             break;
429         case SkTextBlob::kHorizontal_Positioning: {
430             std::unique_ptr<SkPoint[]> pts(new SkPoint[it.glyphCount()]);
431             for (size_t i = 0; i < it.glyphCount(); i++) {
432                 pts[i].set(x + offset.x() + it.pos()[i], y + offset.y());
433             }
434             this->drawPosText(it.glyphs(), textLen, pts.get(), runPaint);
435             break;
436         }
437         case SkTextBlob::kFull_Positioning: {
438             std::unique_ptr<SkPoint[]> pts(new SkPoint[it.glyphCount()]);
439             for (size_t i = 0; i < it.glyphCount(); i++) {
440                 const size_t xIndex = i*2;
441                 const size_t yIndex = xIndex + 1;
442                 pts[i].set(x + offset.x() + it.pos()[xIndex], y + offset.y() + it.pos()[yIndex]);
443             }
444             this->drawPosText(it.glyphs(), textLen, pts.get(), runPaint);
445             break;
446         }
447         default:
448             SkFAIL("unhandled positioning mode");
449         }
450     }
451}
452
453void SkiaCanvasProxy::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
454        const SkPoint texCoords[4], SkBlendMode bmode, const SkPaint& paint) {
455    if (mFilterHwuiCalls) {
456        return;
457    }
458    SkPatchUtils::VertexData data;
459
460    SkMatrix matrix;
461    mCanvas->getMatrix(&matrix);
462    SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, &matrix);
463
464    // It automatically adjusts lodX and lodY in case it exceeds the number of indices.
465    // If it fails to generate the vertices, then we do not draw.
466    if (SkPatchUtils::getVertexData(&data, cubics, colors, texCoords, lod.width(), lod.height())) {
467        this->drawVertices(SkCanvas::kTriangles_VertexMode, data.fVertexCount, data.fPoints,
468                           data.fTexCoords, data.fColors, bmode, data.fIndices, data.fIndexCount,
469                           paint);
470    }
471}
472
473void SkiaCanvasProxy::onClipRect(const SkRect& rect, SkClipOp op, ClipEdgeStyle) {
474    mCanvas->clipRect(rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, op);
475}
476
477void SkiaCanvasProxy::onClipRRect(const SkRRect& roundRect, SkClipOp op, ClipEdgeStyle) {
478    SkPath path;
479    path.addRRect(roundRect);
480    mCanvas->clipPath(&path, op);
481}
482
483void SkiaCanvasProxy::onClipPath(const SkPath& path, SkClipOp op, ClipEdgeStyle) {
484    mCanvas->clipPath(&path, op);
485}
486
487}; // namespace uirenderer
488}; // namespace android
489