SkiaCanvas.cpp revision afc221499d943386256feb9db46c119ff834bf79
1/*
2 * Copyright (C) 2014 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 "SkiaCanvas.h"
18
19#include "CanvasProperty.h"
20#include "VectorDrawable.h"
21#include "hwui/MinikinUtils.h"
22
23#include <SkDrawable.h>
24#include <SkDevice.h>
25#include <SkDeque.h>
26#include <SkDrawFilter.h>
27#include <SkGraphics.h>
28#include <SkImage.h>
29#include <SkRSXform.h>
30#include <SkShader.h>
31#include <SkTemplates.h>
32
33#include <memory>
34
35namespace android {
36
37Canvas* Canvas::create_canvas(const SkBitmap& bitmap) {
38    return new SkiaCanvas(bitmap);
39}
40
41Canvas* Canvas::create_canvas(SkCanvas* skiaCanvas) {
42    return new SkiaCanvas(skiaCanvas);
43}
44
45SkiaCanvas::SkiaCanvas(const SkBitmap& bitmap) {
46    mCanvas.reset(new SkCanvas(bitmap));
47}
48
49void SkiaCanvas::reset(SkCanvas* skiaCanvas) {
50    mCanvas.reset(SkRef(skiaCanvas));
51    mSaveStack.reset(nullptr);
52    mHighContrastText = false;
53}
54
55// ----------------------------------------------------------------------------
56// Canvas state operations: Replace Bitmap
57// ----------------------------------------------------------------------------
58
59class ClipCopier : public SkCanvas::ClipVisitor {
60public:
61    explicit ClipCopier(SkCanvas* dstCanvas) : m_dstCanvas(dstCanvas) {}
62
63    virtual void clipRect(const SkRect& rect, SkRegion::Op op, bool antialias) {
64        m_dstCanvas->clipRect(rect, op, antialias);
65    }
66    virtual void clipRRect(const SkRRect& rrect, SkRegion::Op op, bool antialias) {
67        m_dstCanvas->clipRRect(rrect, op, antialias);
68    }
69    virtual void clipPath(const SkPath& path, SkRegion::Op op, bool antialias) {
70        m_dstCanvas->clipPath(path, op, antialias);
71    }
72
73private:
74    SkCanvas* m_dstCanvas;
75};
76
77void SkiaCanvas::setBitmap(const SkBitmap& bitmap) {
78    sk_sp<SkCanvas> newCanvas(new SkCanvas(bitmap));
79
80    if (!bitmap.isNull()) {
81        // Copy the canvas matrix & clip state.
82        newCanvas->setMatrix(mCanvas->getTotalMatrix());
83
84        ClipCopier copier(newCanvas.get());
85        mCanvas->replayClips(&copier);
86    }
87
88    // unrefs the existing canvas
89    mCanvas = std::move(newCanvas);
90
91    // clean up the old save stack
92    mSaveStack.reset(NULL);
93}
94
95// ----------------------------------------------------------------------------
96// Canvas state operations
97// ----------------------------------------------------------------------------
98
99bool SkiaCanvas::isOpaque() {
100    return mCanvas->imageInfo().isOpaque();
101}
102
103int SkiaCanvas::width() {
104    return mCanvas->imageInfo().width();
105}
106
107int SkiaCanvas::height() {
108    return mCanvas->imageInfo().height();
109}
110
111// ----------------------------------------------------------------------------
112// Canvas state operations: Save (layer)
113// ----------------------------------------------------------------------------
114
115int SkiaCanvas::getSaveCount() const {
116    return mCanvas->getSaveCount();
117}
118
119int SkiaCanvas::save(SaveFlags::Flags flags) {
120    int count = mCanvas->save();
121    recordPartialSave(flags);
122    return count;
123}
124
125// The SkiaCanvas::restore operation layers on the capability to preserve
126// either (or both) the matrix and/or clip state after a SkCanvas::restore
127// operation. It does this by explicitly saving off the clip & matrix state
128// when requested and playing it back after the SkCanvas::restore.
129void SkiaCanvas::restore() {
130    const SaveRec* rec = (NULL == mSaveStack.get())
131            ? NULL
132            : static_cast<SaveRec*>(mSaveStack->back());
133    int currentSaveCount = mCanvas->getSaveCount();
134    SkASSERT(NULL == rec || currentSaveCount >= rec->saveCount);
135
136    if (NULL == rec || rec->saveCount != currentSaveCount) {
137        // Fast path - no record for this frame.
138        mCanvas->restore();
139        return;
140    }
141
142    bool preserveMatrix = !(rec->saveFlags & SaveFlags::Matrix);
143    bool preserveClip   = !(rec->saveFlags & SaveFlags::Clip);
144
145    SkMatrix savedMatrix;
146    if (preserveMatrix) {
147        savedMatrix = mCanvas->getTotalMatrix();
148    }
149
150    SkTArray<SkClipStack::Element> savedClips;
151    int topClipStackFrame = mCanvas->getClipStack()->getSaveCount();
152    if (preserveClip) {
153        saveClipsForFrame(savedClips, topClipStackFrame);
154    }
155
156    mCanvas->restore();
157
158    if (preserveMatrix) {
159        mCanvas->setMatrix(savedMatrix);
160    }
161
162    if (preserveClip && !savedClips.empty() &&
163        topClipStackFrame != mCanvas->getClipStack()->getSaveCount()) {
164        // Only reapply the saved clips if the top clip stack frame was actually
165        // popped by restore().  If it wasn't, it means it doesn't belong to the
166        // restored canvas frame (SkCanvas lazy save/restore kicked in).
167        applyClips(savedClips);
168    }
169
170    mSaveStack->pop_back();
171}
172
173void SkiaCanvas::restoreToCount(int restoreCount) {
174    while (mCanvas->getSaveCount() > restoreCount) {
175        this->restore();
176    }
177}
178
179static inline SkCanvas::SaveLayerFlags layerFlags(SaveFlags::Flags flags) {
180    SkCanvas::SaveLayerFlags layerFlags = 0;
181
182    if (!(flags & SaveFlags::HasAlphaLayer)) {
183        layerFlags |= SkCanvas::kIsOpaque_SaveLayerFlag;
184    }
185
186    if (!(flags & SaveFlags::ClipToLayer)) {
187        layerFlags |= SkCanvas::kDontClipToLayer_Legacy_SaveLayerFlag;
188    }
189
190    return layerFlags;
191}
192
193int SkiaCanvas::saveLayer(float left, float top, float right, float bottom,
194            const SkPaint* paint, SaveFlags::Flags flags) {
195    const SkRect bounds = SkRect::MakeLTRB(left, top, right, bottom);
196    const SkCanvas::SaveLayerRec rec(&bounds, paint, layerFlags(flags));
197
198    int count = mCanvas->saveLayer(rec);
199    recordPartialSave(flags);
200    return count;
201}
202
203int SkiaCanvas::saveLayerAlpha(float left, float top, float right, float bottom,
204        int alpha, SaveFlags::Flags flags) {
205    if (static_cast<unsigned>(alpha) < 0xFF) {
206        SkPaint alphaPaint;
207        alphaPaint.setAlpha(alpha);
208        return this->saveLayer(left, top, right, bottom, &alphaPaint, flags);
209    }
210    return this->saveLayer(left, top, right, bottom, nullptr, flags);
211}
212
213// ----------------------------------------------------------------------------
214// functions to emulate legacy SaveFlags (i.e. independent matrix/clip flags)
215// ----------------------------------------------------------------------------
216
217void SkiaCanvas::recordPartialSave(SaveFlags::Flags flags) {
218    // A partial save is a save operation which doesn't capture the full canvas state.
219    // (either SaveFlags::Matrix or SaveFlags::Clip is missing).
220
221    // Mask-out non canvas state bits.
222    flags &= SaveFlags::MatrixClip;
223
224    if (flags == SaveFlags::MatrixClip) {
225        // not a partial save.
226        return;
227    }
228
229    if (NULL == mSaveStack.get()) {
230        mSaveStack.reset(new SkDeque(sizeof(struct SaveRec), 8));
231    }
232
233    SaveRec* rec = static_cast<SaveRec*>(mSaveStack->push_back());
234    rec->saveCount = mCanvas->getSaveCount();
235    rec->saveFlags = flags;
236}
237
238void SkiaCanvas::saveClipsForFrame(SkTArray<SkClipStack::Element>& clips,
239                                   int saveCountToBackup) {
240    // Each SkClipStack::Element stores the index of the canvas save
241    // with which it is associated. Backup only those Elements that
242    // are associated with 'saveCountToBackup'
243    SkClipStack::Iter clipIterator(*mCanvas->getClipStack(),
244                                   SkClipStack::Iter::kTop_IterStart);
245    while (const SkClipStack::Element* elem = clipIterator.prev()) {
246        if (elem->getSaveCount() < saveCountToBackup) {
247            // done with the target save count.
248            break;
249        }
250        SkASSERT(elem->getSaveCount() == saveCountToBackup);
251        clips.push_back(*elem);
252    }
253}
254
255void SkiaCanvas::applyClips(const SkTArray<SkClipStack::Element>& clips) {
256    ClipCopier clipCopier(mCanvas.get());
257
258    // The clip stack stores clips in device space.
259    SkMatrix origMatrix = mCanvas->getTotalMatrix();
260    mCanvas->resetMatrix();
261
262    // We pushed the clips in reverse order.
263    for (int i = clips.count() - 1; i >= 0; --i) {
264        clips[i].replay(&clipCopier);
265    }
266
267    mCanvas->setMatrix(origMatrix);
268}
269
270// ----------------------------------------------------------------------------
271// Canvas state operations: Matrix
272// ----------------------------------------------------------------------------
273
274void SkiaCanvas::getMatrix(SkMatrix* outMatrix) const {
275    *outMatrix = mCanvas->getTotalMatrix();
276}
277
278void SkiaCanvas::setMatrix(const SkMatrix& matrix) {
279    mCanvas->setMatrix(matrix);
280}
281
282void SkiaCanvas::concat(const SkMatrix& matrix) {
283    mCanvas->concat(matrix);
284}
285
286void SkiaCanvas::rotate(float degrees) {
287    mCanvas->rotate(degrees);
288}
289
290void SkiaCanvas::scale(float sx, float sy) {
291    mCanvas->scale(sx, sy);
292}
293
294void SkiaCanvas::skew(float sx, float sy) {
295    mCanvas->skew(sx, sy);
296}
297
298void SkiaCanvas::translate(float dx, float dy) {
299    mCanvas->translate(dx, dy);
300}
301
302// ----------------------------------------------------------------------------
303// Canvas state operations: Clips
304// ----------------------------------------------------------------------------
305
306// This function is a mirror of SkCanvas::getClipBounds except that it does
307// not outset the edge of the clip to account for anti-aliasing. There is
308// a skia bug to investigate pushing this logic into back into skia.
309// (see https://code.google.com/p/skia/issues/detail?id=1303)
310bool SkiaCanvas::getClipBounds(SkRect* outRect) const {
311    SkIRect ibounds;
312    if (!mCanvas->getClipDeviceBounds(&ibounds)) {
313        return false;
314    }
315
316    SkMatrix inverse;
317    // if we can't invert the CTM, we can't return local clip bounds
318    if (!mCanvas->getTotalMatrix().invert(&inverse)) {
319        if (outRect) {
320            outRect->setEmpty();
321        }
322        return false;
323    }
324
325    if (NULL != outRect) {
326        SkRect r = SkRect::Make(ibounds);
327        inverse.mapRect(outRect, r);
328    }
329    return true;
330}
331
332bool SkiaCanvas::quickRejectRect(float left, float top, float right, float bottom) const {
333    SkRect bounds = SkRect::MakeLTRB(left, top, right, bottom);
334    return mCanvas->quickReject(bounds);
335}
336
337bool SkiaCanvas::quickRejectPath(const SkPath& path) const {
338    return mCanvas->quickReject(path);
339}
340
341bool SkiaCanvas::clipRect(float left, float top, float right, float bottom, SkRegion::Op op) {
342    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
343    mCanvas->clipRect(rect, op);
344    return !mCanvas->isClipEmpty();
345}
346
347bool SkiaCanvas::clipPath(const SkPath* path, SkRegion::Op op) {
348    SkRRect roundRect;
349    if (path->isRRect(&roundRect)) {
350        mCanvas->clipRRect(roundRect, op);
351    } else {
352        mCanvas->clipPath(*path, op);
353    }
354    return !mCanvas->isClipEmpty();
355}
356
357bool SkiaCanvas::clipRegion(const SkRegion* region, SkRegion::Op op) {
358    SkPath rgnPath;
359    if (region->getBoundaryPath(&rgnPath)) {
360        // The region is specified in device space.
361        SkMatrix savedMatrix = mCanvas->getTotalMatrix();
362        mCanvas->resetMatrix();
363        mCanvas->clipPath(rgnPath, op);
364        mCanvas->setMatrix(savedMatrix);
365    } else {
366        mCanvas->clipRect(SkRect::MakeEmpty(), op);
367    }
368    return !mCanvas->isClipEmpty();
369}
370
371// ----------------------------------------------------------------------------
372// Canvas state operations: Filters
373// ----------------------------------------------------------------------------
374
375SkDrawFilter* SkiaCanvas::getDrawFilter() {
376    return mCanvas->getDrawFilter();
377}
378
379void SkiaCanvas::setDrawFilter(SkDrawFilter* drawFilter) {
380    mCanvas->setDrawFilter(drawFilter);
381}
382
383// ----------------------------------------------------------------------------
384// Canvas draw operations
385// ----------------------------------------------------------------------------
386
387void SkiaCanvas::drawColor(int color, SkXfermode::Mode mode) {
388    mCanvas->drawColor(color, mode);
389}
390
391void SkiaCanvas::drawPaint(const SkPaint& paint) {
392    mCanvas->drawPaint(paint);
393}
394
395// ----------------------------------------------------------------------------
396// Canvas draw operations: Geometry
397// ----------------------------------------------------------------------------
398
399void SkiaCanvas::drawPoints(const float* points, int count, const SkPaint& paint,
400                            SkCanvas::PointMode mode) {
401    // convert the floats into SkPoints
402    count >>= 1;    // now it is the number of points
403    std::unique_ptr<SkPoint[]> pts(new SkPoint[count]);
404    for (int i = 0; i < count; i++) {
405        pts[i].set(points[0], points[1]);
406        points += 2;
407    }
408    mCanvas->drawPoints(mode, count, pts.get(), paint);
409}
410
411
412void SkiaCanvas::drawPoint(float x, float y, const SkPaint& paint) {
413    mCanvas->drawPoint(x, y, paint);
414}
415
416void SkiaCanvas::drawPoints(const float* points, int count, const SkPaint& paint) {
417    this->drawPoints(points, count, paint, SkCanvas::kPoints_PointMode);
418}
419
420void SkiaCanvas::drawLine(float startX, float startY, float stopX, float stopY,
421                          const SkPaint& paint) {
422    mCanvas->drawLine(startX, startY, stopX, stopY, paint);
423}
424
425void SkiaCanvas::drawLines(const float* points, int count, const SkPaint& paint) {
426    this->drawPoints(points, count, paint, SkCanvas::kLines_PointMode);
427}
428
429void SkiaCanvas::drawRect(float left, float top, float right, float bottom,
430        const SkPaint& paint) {
431    mCanvas->drawRectCoords(left, top, right, bottom, paint);
432
433}
434
435void SkiaCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
436    SkRegion::Iterator it(region);
437    while (!it.done()) {
438        mCanvas->drawRect(SkRect::Make(it.rect()), paint);
439        it.next();
440    }
441}
442
443void SkiaCanvas::drawRoundRect(float left, float top, float right, float bottom,
444        float rx, float ry, const SkPaint& paint) {
445    SkRect rect = SkRect::MakeLTRB(left, top, right, bottom);
446    mCanvas->drawRoundRect(rect, rx, ry, paint);
447}
448
449void SkiaCanvas::drawCircle(float x, float y, float radius, const SkPaint& paint) {
450    mCanvas->drawCircle(x, y, radius, paint);
451}
452
453void SkiaCanvas::drawOval(float left, float top, float right, float bottom, const SkPaint& paint) {
454    SkRect oval = SkRect::MakeLTRB(left, top, right, bottom);
455    mCanvas->drawOval(oval, paint);
456}
457
458void SkiaCanvas::drawArc(float left, float top, float right, float bottom,
459        float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) {
460    SkRect arc = SkRect::MakeLTRB(left, top, right, bottom);
461    mCanvas->drawArc(arc, startAngle, sweepAngle, useCenter, paint);
462}
463
464void SkiaCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
465    SkRect rect;
466    SkRRect roundRect;
467    if (path.isOval(&rect)) {
468        mCanvas->drawOval(rect, paint);
469    } else if (path.isRRect(&roundRect)) {
470        mCanvas->drawRRect(roundRect, paint);
471    } else {
472        mCanvas->drawPath(path, paint);
473    }
474}
475
476void SkiaCanvas::drawVertices(SkCanvas::VertexMode vertexMode, int vertexCount,
477                              const float* verts, const float* texs, const int* colors,
478                              const uint16_t* indices, int indexCount, const SkPaint& paint) {
479#ifndef SK_SCALAR_IS_FLOAT
480    SkDEBUGFAIL("SkScalar must be a float for these conversions to be valid");
481#endif
482    const int ptCount = vertexCount >> 1;
483    mCanvas->drawVertices(vertexMode, ptCount, (SkPoint*)verts, (SkPoint*)texs,
484                          (SkColor*)colors, NULL, indices, indexCount, paint);
485}
486
487// ----------------------------------------------------------------------------
488// Canvas draw operations: Bitmaps
489// ----------------------------------------------------------------------------
490
491void SkiaCanvas::drawBitmap(const SkBitmap& bitmap, float left, float top, const SkPaint* paint) {
492    mCanvas->drawBitmap(bitmap, left, top, paint);
493}
494
495void SkiaCanvas::drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix, const SkPaint* paint) {
496    SkAutoCanvasRestore acr(mCanvas.get(), true);
497    mCanvas->concat(matrix);
498    mCanvas->drawBitmap(bitmap, 0, 0, paint);
499}
500
501void SkiaCanvas::drawBitmap(const SkBitmap& bitmap, float srcLeft, float srcTop,
502                            float srcRight, float srcBottom, float dstLeft, float dstTop,
503                            float dstRight, float dstBottom, const SkPaint* paint) {
504    SkRect srcRect = SkRect::MakeLTRB(srcLeft, srcTop, srcRight, srcBottom);
505    SkRect dstRect = SkRect::MakeLTRB(dstLeft, dstTop, dstRight, dstBottom);
506    mCanvas->drawBitmapRect(bitmap, srcRect, dstRect, paint);
507}
508
509void SkiaCanvas::drawBitmapMesh(const SkBitmap& bitmap, int meshWidth, int meshHeight,
510        const float* vertices, const int* colors, const SkPaint* paint) {
511
512    const int ptCount = (meshWidth + 1) * (meshHeight + 1);
513    const int indexCount = meshWidth * meshHeight * 6;
514
515    /*  Our temp storage holds 2 or 3 arrays.
516        texture points [ptCount * sizeof(SkPoint)]
517        optionally vertex points [ptCount * sizeof(SkPoint)] if we need a
518            copy to convert from float to fixed
519        indices [ptCount * sizeof(uint16_t)]
520    */
521    ssize_t storageSize = ptCount * sizeof(SkPoint); // texs[]
522    storageSize += indexCount * sizeof(uint16_t);  // indices[]
523
524
525#ifndef SK_SCALAR_IS_FLOAT
526    SkDEBUGFAIL("SkScalar must be a float for these conversions to be valid");
527#endif
528    std::unique_ptr<char[]> storage(new char[storageSize]);
529    SkPoint* texs = (SkPoint*)storage.get();
530    uint16_t* indices = (uint16_t*)(texs + ptCount);
531
532    // cons up texture coordinates and indices
533    {
534        const SkScalar w = SkIntToScalar(bitmap.width());
535        const SkScalar h = SkIntToScalar(bitmap.height());
536        const SkScalar dx = w / meshWidth;
537        const SkScalar dy = h / meshHeight;
538
539        SkPoint* texsPtr = texs;
540        SkScalar y = 0;
541        for (int i = 0; i <= meshHeight; i++) {
542            if (i == meshHeight) {
543                y = h;  // to ensure numerically we hit h exactly
544            }
545            SkScalar x = 0;
546            for (int j = 0; j < meshWidth; j++) {
547                texsPtr->set(x, y);
548                texsPtr += 1;
549                x += dx;
550            }
551            texsPtr->set(w, y);
552            texsPtr += 1;
553            y += dy;
554        }
555        SkASSERT(texsPtr - texs == ptCount);
556    }
557
558    // cons up indices
559    {
560        uint16_t* indexPtr = indices;
561        int index = 0;
562        for (int i = 0; i < meshHeight; i++) {
563            for (int j = 0; j < meshWidth; j++) {
564                // lower-left triangle
565                *indexPtr++ = index;
566                *indexPtr++ = index + meshWidth + 1;
567                *indexPtr++ = index + meshWidth + 2;
568                // upper-right triangle
569                *indexPtr++ = index;
570                *indexPtr++ = index + meshWidth + 2;
571                *indexPtr++ = index + 1;
572                // bump to the next cell
573                index += 1;
574            }
575            // bump to the next row
576            index += 1;
577        }
578        SkASSERT(indexPtr - indices == indexCount);
579        SkASSERT((char*)indexPtr - (char*)storage.get() == storageSize);
580    }
581
582    // double-check that we have legal indices
583#ifdef SK_DEBUG
584    {
585        for (int i = 0; i < indexCount; i++) {
586            SkASSERT((unsigned)indices[i] < (unsigned)ptCount);
587        }
588    }
589#endif
590
591    // cons-up a shader for the bitmap
592    SkPaint tmpPaint;
593    if (paint) {
594        tmpPaint = *paint;
595    }
596    SkShader* shader = SkShader::CreateBitmapShader(bitmap,
597                                                    SkShader::kClamp_TileMode,
598                                                    SkShader::kClamp_TileMode);
599    SkSafeUnref(tmpPaint.setShader(shader));
600
601    mCanvas->drawVertices(SkCanvas::kTriangles_VertexMode, ptCount, (SkPoint*)vertices,
602                         texs, (const SkColor*)colors, NULL, indices,
603                         indexCount, tmpPaint);
604}
605
606void SkiaCanvas::drawNinePatch(const SkBitmap& bitmap, const Res_png_9patch& chunk,
607        float dstLeft, float dstTop, float dstRight, float dstBottom, const SkPaint* paint) {
608    SkRect bounds = SkRect::MakeLTRB(dstLeft, dstTop, dstRight, dstBottom);
609    NinePatch::Draw(mCanvas.get(), bounds, bitmap, chunk, paint, nullptr);
610}
611
612void SkiaCanvas::drawVectorDrawable(VectorDrawableRoot* vectorDrawable) {
613    vectorDrawable->drawStaging(this);
614}
615
616// ----------------------------------------------------------------------------
617// Canvas draw operations: Text
618// ----------------------------------------------------------------------------
619
620void SkiaCanvas::drawGlyphs(const uint16_t* text, const float* positions, int count,
621        const SkPaint& paint, float x, float y,
622        float boundsLeft, float boundsTop, float boundsRight, float boundsBottom,
623        float totalAdvance) {
624    static_assert(sizeof(SkPoint) == sizeof(float)*2, "SkPoint is no longer two floats");
625    mCanvas->drawPosText(text, count << 1, reinterpret_cast<const SkPoint*>(positions), paint);
626    drawTextDecorations(x, y, totalAdvance, paint);
627}
628
629void SkiaCanvas::drawLayoutOnPath(const minikin::Layout& layout, float hOffset, float vOffset,
630        const SkPaint& paint, const SkPath& path, size_t start, size_t end) {
631    const int N = end - start;
632    SkAutoSMalloc<1024> storage(N * (sizeof(uint16_t) + sizeof(SkRSXform)));
633    SkRSXform* xform = (SkRSXform*)storage.get();
634    uint16_t* glyphs = (uint16_t*)(xform + N);
635    SkPathMeasure meas(path, false);
636
637    for (size_t i = start; i < end; i++) {
638        glyphs[i - start] = layout.getGlyphId(i);
639        float x = hOffset + layout.getX(i);
640        float y = vOffset + layout.getY(i);
641
642        SkPoint pos;
643        SkVector tan;
644        if (!meas.getPosTan(x, &pos, &tan)) {
645            pos.set(x, y);
646            tan.set(1, 0);
647        }
648        xform[i - start].fSCos = tan.x();
649        xform[i - start].fSSin = tan.y();
650        xform[i - start].fTx   = pos.x() - tan.y() * y;
651        xform[i - start].fTy   = pos.y() + tan.x() * y;
652    }
653
654    this->asSkCanvas()->drawTextRSXform(glyphs, sizeof(uint16_t) * N, xform, nullptr, paint);
655}
656
657// ----------------------------------------------------------------------------
658// Canvas draw operations: Animations
659// ----------------------------------------------------------------------------
660
661class AnimatedRoundRect : public SkDrawable {
662 public:
663    AnimatedRoundRect(uirenderer::CanvasPropertyPrimitive* left,
664            uirenderer::CanvasPropertyPrimitive* top, uirenderer::CanvasPropertyPrimitive* right,
665            uirenderer::CanvasPropertyPrimitive* bottom, uirenderer::CanvasPropertyPrimitive* rx,
666            uirenderer::CanvasPropertyPrimitive* ry, uirenderer::CanvasPropertyPaint* p) :
667            mLeft(left), mTop(top), mRight(right), mBottom(bottom), mRx(rx), mRy(ry), mPaint(p) {}
668
669 protected:
670     virtual SkRect onGetBounds() override {
671         return SkRect::MakeLTRB(mLeft->value, mTop->value, mRight->value, mBottom->value);
672     }
673     virtual void onDraw(SkCanvas* canvas) override {
674         SkRect rect = SkRect::MakeLTRB(mLeft->value, mTop->value, mRight->value, mBottom->value);
675         canvas->drawRoundRect(rect, mRx->value, mRy->value, mPaint->value);
676     }
677
678 private:
679    sp<uirenderer::CanvasPropertyPrimitive> mLeft;
680    sp<uirenderer::CanvasPropertyPrimitive> mTop;
681    sp<uirenderer::CanvasPropertyPrimitive> mRight;
682    sp<uirenderer::CanvasPropertyPrimitive> mBottom;
683    sp<uirenderer::CanvasPropertyPrimitive> mRx;
684    sp<uirenderer::CanvasPropertyPrimitive> mRy;
685    sp<uirenderer::CanvasPropertyPaint> mPaint;
686};
687
688class AnimatedCircle : public SkDrawable {
689 public:
690    AnimatedCircle(uirenderer::CanvasPropertyPrimitive* x, uirenderer::CanvasPropertyPrimitive* y,
691            uirenderer::CanvasPropertyPrimitive* radius, uirenderer::CanvasPropertyPaint* paint) :
692            mX(x), mY(y), mRadius(radius), mPaint(paint) {}
693
694 protected:
695     virtual SkRect onGetBounds() override {
696         const float x = mX->value;
697         const float y = mY->value;
698         const float radius = mRadius->value;
699         return SkRect::MakeLTRB(x - radius, y - radius, x + radius, y + radius);
700     }
701     virtual void onDraw(SkCanvas* canvas) override {
702         canvas->drawCircle(mX->value, mY->value, mRadius->value, mPaint->value);
703     }
704
705 private:
706    sp<uirenderer::CanvasPropertyPrimitive> mX;
707    sp<uirenderer::CanvasPropertyPrimitive> mY;
708    sp<uirenderer::CanvasPropertyPrimitive> mRadius;
709    sp<uirenderer::CanvasPropertyPaint> mPaint;
710};
711
712void SkiaCanvas::drawRoundRect(uirenderer::CanvasPropertyPrimitive* left,
713        uirenderer::CanvasPropertyPrimitive* top, uirenderer::CanvasPropertyPrimitive* right,
714        uirenderer::CanvasPropertyPrimitive* bottom, uirenderer::CanvasPropertyPrimitive* rx,
715        uirenderer::CanvasPropertyPrimitive* ry, uirenderer::CanvasPropertyPaint* paint) {
716    sk_sp<AnimatedRoundRect> drawable(
717            new AnimatedRoundRect(left, top, right, bottom, rx, ry, paint));
718    mCanvas->drawDrawable(drawable.get());
719}
720
721void SkiaCanvas::drawCircle(uirenderer::CanvasPropertyPrimitive* x, uirenderer::CanvasPropertyPrimitive* y,
722        uirenderer::CanvasPropertyPrimitive* radius, uirenderer::CanvasPropertyPaint* paint) {
723    sk_sp<AnimatedCircle> drawable(new AnimatedCircle(x, y, radius, paint));
724    mCanvas->drawDrawable(drawable.get());
725}
726
727// ----------------------------------------------------------------------------
728// Canvas draw operations: View System
729// ----------------------------------------------------------------------------
730
731void SkiaCanvas::drawLayer(uirenderer::DeferredLayerUpdater* layer) {
732    LOG_ALWAYS_FATAL("SkiaCanvas can't directly draw Layers");
733}
734
735void SkiaCanvas::drawRenderNode(uirenderer::RenderNode* renderNode) {
736    LOG_ALWAYS_FATAL("SkiaCanvas can't directly draw RenderNodes");
737}
738
739void SkiaCanvas::callDrawGLFunction(Functor* functor,
740        uirenderer::GlFunctorLifecycleListener* listener) {
741    LOG_ALWAYS_FATAL("SkiaCanvas can't directly draw GL Content");
742}
743
744} // namespace android
745