DisplayListCanvas.cpp revision f276acd98457bcaabc9e79a17a736b3b484f005e
1/*
2 * Copyright (C) 2010 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 "DisplayListCanvas.h"
18
19#include "DeferredDisplayList.h"
20#include "DeferredLayerUpdater.h"
21#include "DisplayListOp.h"
22#include "ResourceCache.h"
23#include "RenderNode.h"
24#include "VectorDrawable.h"
25#include "utils/PaintUtils.h"
26
27#include <SkCamera.h>
28#include <SkCanvas.h>
29
30#include <private/hwui/DrawGlInfo.h>
31
32namespace android {
33namespace uirenderer {
34
35DisplayListCanvas::DisplayListCanvas(int width, int height)
36    : mState(*this)
37    , mResourceCache(ResourceCache::getInstance())
38    , mDisplayList(nullptr)
39    , mTranslateX(0.0f)
40    , mTranslateY(0.0f)
41    , mHasDeferredTranslate(false)
42    , mDeferredBarrierType(kBarrier_None)
43    , mHighContrastText(false)
44    , mRestoreSaveCount(-1) {
45    reset(width, height);
46}
47
48DisplayListCanvas::~DisplayListCanvas() {
49    LOG_ALWAYS_FATAL_IF(mDisplayList,
50            "Destroyed a DisplayListCanvas during a record!");
51}
52
53void DisplayListCanvas::reset(int width, int height) {
54    LOG_ALWAYS_FATAL_IF(mDisplayList,
55            "prepareDirty called a second time during a recording!");
56    mDisplayList = new DisplayList();
57
58    mState.initializeSaveStack(width, height,
59            0, 0, width, height, Vector3());
60
61    mDeferredBarrierType = kBarrier_InOrder;
62    mState.setDirtyClip(false);
63    mRestoreSaveCount = -1;
64}
65
66
67///////////////////////////////////////////////////////////////////////////////
68// Operations
69///////////////////////////////////////////////////////////////////////////////
70
71DisplayList* DisplayListCanvas::finishRecording() {
72    flushRestoreToCount();
73    flushTranslate();
74
75    mPaintMap.clear();
76    mRegionMap.clear();
77    mPathMap.clear();
78    DisplayList* displayList = mDisplayList;
79    mDisplayList = nullptr;
80    mSkiaCanvasProxy.reset(nullptr);
81    return displayList;
82}
83
84void DisplayListCanvas::callDrawGLFunction(Functor *functor) {
85    addDrawOp(new (alloc()) DrawFunctorOp(functor));
86    mDisplayList->functors.push_back(functor);
87}
88
89SkCanvas* DisplayListCanvas::asSkCanvas() {
90    LOG_ALWAYS_FATAL_IF(!mDisplayList,
91            "attempting to get an SkCanvas when we are not recording!");
92    if (!mSkiaCanvasProxy) {
93        mSkiaCanvasProxy.reset(new SkiaCanvasProxy(this));
94    }
95
96    // SkCanvas instances default to identity transform, but should inherit
97    // the state of this Canvas; if this code was in the SkiaCanvasProxy
98    // constructor, we couldn't cache mSkiaCanvasProxy.
99    SkMatrix parentTransform;
100    getMatrix(&parentTransform);
101    mSkiaCanvasProxy.get()->setMatrix(parentTransform);
102
103    return mSkiaCanvasProxy.get();
104}
105
106int DisplayListCanvas::save(SaveFlags::Flags flags) {
107    addStateOp(new (alloc()) SaveOp((int) flags));
108    return mState.save((int) flags);
109}
110
111void DisplayListCanvas::restore() {
112    if (mRestoreSaveCount < 0) {
113        restoreToCount(getSaveCount() - 1);
114        return;
115    }
116
117    mRestoreSaveCount--;
118    flushTranslate();
119    mState.restore();
120}
121
122void DisplayListCanvas::restoreToCount(int saveCount) {
123    mRestoreSaveCount = saveCount;
124    flushTranslate();
125    mState.restoreToCount(saveCount);
126}
127
128int DisplayListCanvas::saveLayer(float left, float top, float right, float bottom,
129        const SkPaint* paint, SaveFlags::Flags flags) {
130    // force matrix/clip isolation for layer
131    flags |= SaveFlags::MatrixClip;
132
133    paint = refPaint(paint);
134    addStateOp(new (alloc()) SaveLayerOp(left, top, right, bottom, paint, (int) flags));
135    return mState.save((int) flags);
136}
137
138void DisplayListCanvas::translate(float dx, float dy) {
139    if (dx == 0.0f && dy == 0.0f) return;
140
141    mHasDeferredTranslate = true;
142    mTranslateX += dx;
143    mTranslateY += dy;
144    flushRestoreToCount();
145    mState.translate(dx, dy, 0.0f);
146}
147
148void DisplayListCanvas::rotate(float degrees) {
149    if (degrees == 0.0f) return;
150
151    addStateOp(new (alloc()) RotateOp(degrees));
152    mState.rotate(degrees);
153}
154
155void DisplayListCanvas::scale(float sx, float sy) {
156    if (sx == 1.0f && sy == 1.0f) return;
157
158    addStateOp(new (alloc()) ScaleOp(sx, sy));
159    mState.scale(sx, sy);
160}
161
162void DisplayListCanvas::skew(float sx, float sy) {
163    addStateOp(new (alloc()) SkewOp(sx, sy));
164    mState.skew(sx, sy);
165}
166
167void DisplayListCanvas::setMatrix(const SkMatrix& matrix) {
168    addStateOp(new (alloc()) SetMatrixOp(matrix));
169    mState.setMatrix(matrix);
170}
171
172void DisplayListCanvas::concat(const SkMatrix& matrix) {
173    addStateOp(new (alloc()) ConcatMatrixOp(matrix));
174    mState.concatMatrix(matrix);
175}
176
177bool DisplayListCanvas::getClipBounds(SkRect* outRect) const {
178    Rect bounds = mState.getLocalClipBounds();
179    *outRect = SkRect::MakeLTRB(bounds.left, bounds.top, bounds.right, bounds.bottom);
180    return !(outRect->isEmpty());
181}
182
183bool DisplayListCanvas::quickRejectRect(float left, float top, float right, float bottom) const {
184    return mState.quickRejectConservative(left, top, right, bottom);
185}
186
187bool DisplayListCanvas::quickRejectPath(const SkPath& path) const {
188    SkRect bounds = path.getBounds();
189    return mState.quickRejectConservative(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom);
190}
191
192
193bool DisplayListCanvas::clipRect(float left, float top, float right, float bottom,
194        SkRegion::Op op) {
195    addStateOp(new (alloc()) ClipRectOp(left, top, right, bottom, op));
196    return mState.clipRect(left, top, right, bottom, op);
197}
198
199bool DisplayListCanvas::clipPath(const SkPath* path, SkRegion::Op op) {
200    path = refPath(path);
201    addStateOp(new (alloc()) ClipPathOp(path, op));
202    return mState.clipPath(path, op);
203}
204
205bool DisplayListCanvas::clipRegion(const SkRegion* region, SkRegion::Op op) {
206    region = refRegion(region);
207    addStateOp(new (alloc()) ClipRegionOp(region, op));
208    return mState.clipRegion(region, op);
209}
210
211void DisplayListCanvas::drawRenderNode(RenderNode* renderNode) {
212    LOG_ALWAYS_FATAL_IF(!renderNode, "missing rendernode");
213    DrawRenderNodeOp* op = new (alloc()) DrawRenderNodeOp(
214            renderNode,
215            *mState.currentTransform(),
216            mState.clipIsSimple());
217    addRenderNodeOp(op);
218}
219
220void DisplayListCanvas::drawLayer(DeferredLayerUpdater* layerHandle) {
221    // We ref the DeferredLayerUpdater due to its thread-safe ref-counting
222    // semantics.
223    mDisplayList->ref(layerHandle);
224    addDrawOp(new (alloc()) DrawLayerOp(layerHandle->backingLayer()));
225}
226
227void DisplayListCanvas::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
228    bitmap = refBitmap(*bitmap);
229    paint = refPaint(paint);
230
231    addDrawOp(new (alloc()) DrawBitmapOp(bitmap, paint));
232}
233
234void DisplayListCanvas::drawBitmap(const SkBitmap& bitmap, float left, float top,
235        const SkPaint* paint) {
236    save(SaveFlags::Matrix);
237    translate(left, top);
238    drawBitmap(&bitmap, paint);
239    restore();
240}
241
242void DisplayListCanvas::drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
243        const SkPaint* paint) {
244    if (matrix.isIdentity()) {
245        drawBitmap(&bitmap, paint);
246    } else if (!(matrix.getType() & ~(SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask))
247            && MathUtils::isPositive(matrix.getScaleX())
248            && MathUtils::isPositive(matrix.getScaleY())) {
249        // SkMatrix::isScaleTranslate() not available in L
250        SkRect src;
251        SkRect dst;
252        bitmap.getBounds(&src);
253        matrix.mapRect(&dst, src);
254        drawBitmap(bitmap, src.fLeft, src.fTop, src.fRight, src.fBottom,
255                   dst.fLeft, dst.fTop, dst.fRight, dst.fBottom, paint);
256    } else {
257        save(SaveFlags::Matrix);
258        concat(matrix);
259        drawBitmap(&bitmap, paint);
260        restore();
261    }
262}
263
264void DisplayListCanvas::drawBitmap(const SkBitmap& bitmap, float srcLeft, float srcTop,
265        float srcRight, float srcBottom, float dstLeft, float dstTop,
266        float dstRight, float dstBottom, const SkPaint* paint) {
267    if (srcLeft == 0 && srcTop == 0
268            && srcRight == bitmap.width()
269            && srcBottom == bitmap.height()
270            && (srcBottom - srcTop == dstBottom - dstTop)
271            && (srcRight - srcLeft == dstRight - dstLeft)) {
272        // transform simple rect to rect drawing case into position bitmap ops, since they merge
273        save(SaveFlags::Matrix);
274        translate(dstLeft, dstTop);
275        drawBitmap(&bitmap, paint);
276        restore();
277    } else {
278        paint = refPaint(paint);
279
280        if (paint && paint->getShader()) {
281            float scaleX = (dstRight - dstLeft) / (srcRight - srcLeft);
282            float scaleY = (dstBottom - dstTop) / (srcBottom - srcTop);
283            if (!MathUtils::areEqual(scaleX, 1.0f) || !MathUtils::areEqual(scaleY, 1.0f)) {
284                // Apply the scale transform on the canvas, so that the shader
285                // effectively calculates positions relative to src rect space
286
287                save(SaveFlags::Matrix);
288                translate(dstLeft, dstTop);
289                scale(scaleX, scaleY);
290
291                dstLeft = 0.0f;
292                dstTop = 0.0f;
293                dstRight = srcRight - srcLeft;
294                dstBottom = srcBottom - srcTop;
295
296                addDrawOp(new (alloc()) DrawBitmapRectOp(refBitmap(bitmap),
297                        srcLeft, srcTop, srcRight, srcBottom,
298                        dstLeft, dstTop, dstRight, dstBottom, paint));
299                restore();
300                return;
301            }
302        }
303
304        addDrawOp(new (alloc()) DrawBitmapRectOp(refBitmap(bitmap),
305                srcLeft, srcTop, srcRight, srcBottom,
306                dstLeft, dstTop, dstRight, dstBottom, paint));
307    }
308}
309
310void DisplayListCanvas::drawBitmapMesh(const SkBitmap& bitmap, int meshWidth, int meshHeight,
311        const float* vertices, const int* colors, const SkPaint* paint) {
312    int vertexCount = (meshWidth + 1) * (meshHeight + 1);
313    vertices = refBuffer<float>(vertices, vertexCount * 2); // 2 floats per vertex
314    paint = refPaint(paint);
315    colors = refBuffer<int>(colors, vertexCount); // 1 color per vertex
316
317    addDrawOp(new (alloc()) DrawBitmapMeshOp(refBitmap(bitmap), meshWidth, meshHeight,
318           vertices, colors, paint));
319}
320
321void DisplayListCanvas::drawNinePatch(const SkBitmap& bitmap, const Res_png_9patch& patch,
322        float dstLeft, float dstTop, float dstRight, float dstBottom, const SkPaint* paint) {
323    const SkBitmap* bitmapPtr = refBitmap(bitmap);
324    const Res_png_9patch* patchPtr = refPatch(&patch);
325    paint = refPaint(paint);
326
327    addDrawOp(new (alloc()) DrawPatchOp(bitmapPtr, patchPtr,
328            dstLeft, dstTop, dstRight, dstBottom, paint));
329}
330
331void DisplayListCanvas::drawColor(int color, SkXfermode::Mode mode) {
332    addDrawOp(new (alloc()) DrawColorOp(color, mode));
333}
334
335void DisplayListCanvas::drawPaint(const SkPaint& paint) {
336    SkRect bounds;
337    if (getClipBounds(&bounds)) {
338        drawRect(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, paint);
339    }
340}
341
342
343void DisplayListCanvas::drawRect(float left, float top, float right, float bottom,
344        const SkPaint& paint) {
345    addDrawOp(new (alloc()) DrawRectOp(left, top, right, bottom, refPaint(&paint)));
346}
347
348void DisplayListCanvas::drawRoundRect(float left, float top, float right, float bottom,
349        float rx, float ry, const SkPaint& paint) {
350    addDrawOp(new (alloc()) DrawRoundRectOp(left, top, right, bottom, rx, ry, refPaint(&paint)));
351}
352
353void DisplayListCanvas::drawRoundRect(
354        CanvasPropertyPrimitive* left, CanvasPropertyPrimitive* top,
355        CanvasPropertyPrimitive* right, CanvasPropertyPrimitive* bottom,
356        CanvasPropertyPrimitive* rx, CanvasPropertyPrimitive* ry,
357        CanvasPropertyPaint* paint) {
358    mDisplayList->ref(left);
359    mDisplayList->ref(top);
360    mDisplayList->ref(right);
361    mDisplayList->ref(bottom);
362    mDisplayList->ref(rx);
363    mDisplayList->ref(ry);
364    mDisplayList->ref(paint);
365    refBitmapsInShader(paint->value.getShader());
366    addDrawOp(new (alloc()) DrawRoundRectPropsOp(&left->value, &top->value,
367            &right->value, &bottom->value, &rx->value, &ry->value, &paint->value));
368}
369
370void DisplayListCanvas::drawCircle(float x, float y, float radius, const SkPaint& paint) {
371    addDrawOp(new (alloc()) DrawCircleOp(x, y, radius, refPaint(&paint)));
372}
373
374void DisplayListCanvas::drawCircle(CanvasPropertyPrimitive* x, CanvasPropertyPrimitive* y,
375        CanvasPropertyPrimitive* radius, CanvasPropertyPaint* paint) {
376    mDisplayList->ref(x);
377    mDisplayList->ref(y);
378    mDisplayList->ref(radius);
379    mDisplayList->ref(paint);
380    refBitmapsInShader(paint->value.getShader());
381    addDrawOp(new (alloc()) DrawCirclePropsOp(&x->value, &y->value,
382            &radius->value, &paint->value));
383}
384
385void DisplayListCanvas::drawOval(float left, float top, float right, float bottom,
386        const SkPaint& paint) {
387    addDrawOp(new (alloc()) DrawOvalOp(left, top, right, bottom, refPaint(&paint)));
388}
389
390void DisplayListCanvas::drawArc(float left, float top, float right, float bottom,
391        float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) {
392    if (fabs(sweepAngle) >= 360.0f) {
393        drawOval(left, top, right, bottom, paint);
394    } else {
395        addDrawOp(new (alloc()) DrawArcOp(left, top, right, bottom,
396                        startAngle, sweepAngle, useCenter, refPaint(&paint)));
397    }
398}
399
400void DisplayListCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
401    addDrawOp(new (alloc()) DrawPathOp(refPath(&path), refPaint(&paint)));
402}
403
404void DisplayListCanvas::drawLines(const float* points, int count, const SkPaint& paint) {
405    points = refBuffer<float>(points, count);
406
407    addDrawOp(new (alloc()) DrawLinesOp(points, count, refPaint(&paint)));
408}
409
410void DisplayListCanvas::drawPoints(const float* points, int count, const SkPaint& paint) {
411    points = refBuffer<float>(points, count);
412
413    addDrawOp(new (alloc()) DrawPointsOp(points, count, refPaint(&paint)));
414}
415
416void DisplayListCanvas::drawVectorDrawable(VectorDrawableRoot* tree) {
417    mDisplayList->ref(tree);
418    const SkBitmap& bitmap = tree->getBitmapUpdateIfDirty();
419    SkPaint* paint = tree->getPaint();
420    const SkRect bounds = tree->getBounds();
421    addDrawOp(new (alloc()) DrawBitmapRectOp(refBitmap(bitmap),
422            0, 0, bitmap.width(), bitmap.height(),
423            bounds.left(), bounds.top(), bounds.right(), bounds.bottom(), refPaint(paint)));
424}
425
426void DisplayListCanvas::drawTextOnPath(const uint16_t* glyphs, int count,
427        const SkPath& path, float hOffset, float vOffset, const SkPaint& paint) {
428    if (!glyphs || count <= 0) return;
429
430    int bytesCount = 2 * count;
431    DrawOp* op = new (alloc()) DrawTextOnPathOp(refText((const char*) glyphs, bytesCount),
432            bytesCount, count, refPath(&path),
433            hOffset, vOffset, refPaint(&paint));
434    addDrawOp(op);
435}
436
437void DisplayListCanvas::drawText(const uint16_t* glyphs, const float* positions,
438        int count, const SkPaint& paint, float x, float y,
439        float boundsLeft, float boundsTop, float boundsRight, float boundsBottom,
440        float totalAdvance) {
441
442    if (!glyphs || count <= 0 || PaintUtils::paintWillNotDrawText(paint)) return;
443
444    int bytesCount = count * 2;
445    const char* text = refText((const char*) glyphs, bytesCount);
446    positions = refBuffer<float>(positions, count * 2);
447    Rect bounds(boundsLeft, boundsTop, boundsRight, boundsBottom);
448
449    DrawOp* op = new (alloc()) DrawTextOp(text, bytesCount, count,
450            x, y, positions, refPaint(&paint), totalAdvance, bounds);
451    addDrawOp(op);
452    drawTextDecorations(x, y, totalAdvance, paint);
453}
454
455void DisplayListCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
456    if (paint.getStyle() != SkPaint::kFill_Style ||
457            (paint.isAntiAlias() && !mState.currentTransform()->isSimple())) {
458        SkRegion::Iterator it(region);
459        while (!it.done()) {
460            const SkIRect& r = it.rect();
461            drawRect(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
462            it.next();
463        }
464    } else {
465        int count = 0;
466        Vector<float> rects;
467        SkRegion::Iterator it(region);
468        while (!it.done()) {
469            const SkIRect& r = it.rect();
470            rects.push(r.fLeft);
471            rects.push(r.fTop);
472            rects.push(r.fRight);
473            rects.push(r.fBottom);
474            count += 4;
475            it.next();
476        }
477        drawRects(rects.array(), count, &paint);
478    }
479}
480
481void DisplayListCanvas::drawRects(const float* rects, int count, const SkPaint* paint) {
482    if (count <= 0) return;
483
484    rects = refBuffer<float>(rects, count);
485    paint = refPaint(paint);
486    addDrawOp(new (alloc()) DrawRectsOp(rects, count, paint));
487}
488
489void DisplayListCanvas::setDrawFilter(SkDrawFilter* filter) {
490    mDrawFilter.reset(SkSafeRef(filter));
491}
492
493void DisplayListCanvas::insertReorderBarrier(bool enableReorder) {
494    flushRestoreToCount();
495    flushTranslate();
496    mDeferredBarrierType = enableReorder ? kBarrier_OutOfOrder : kBarrier_InOrder;
497}
498
499void DisplayListCanvas::flushRestoreToCount() {
500    if (mRestoreSaveCount >= 0) {
501        addOpAndUpdateChunk(new (alloc()) RestoreToCountOp(mRestoreSaveCount));
502        mRestoreSaveCount = -1;
503    }
504}
505
506void DisplayListCanvas::flushTranslate() {
507    if (mHasDeferredTranslate) {
508        if (mTranslateX != 0.0f || mTranslateY != 0.0f) {
509            addOpAndUpdateChunk(new (alloc()) TranslateOp(mTranslateX, mTranslateY));
510            mTranslateX = mTranslateY = 0.0f;
511        }
512        mHasDeferredTranslate = false;
513    }
514}
515
516size_t DisplayListCanvas::addOpAndUpdateChunk(DisplayListOp* op) {
517    int insertIndex = mDisplayList->ops.size();
518#if HWUI_NEW_OPS
519    LOG_ALWAYS_FATAL("unsupported");
520#else
521    mDisplayList->ops.push_back(op);
522#endif
523    if (mDeferredBarrierType != kBarrier_None) {
524        // op is first in new chunk
525        mDisplayList->chunks.emplace_back();
526        DisplayList::Chunk& newChunk = mDisplayList->chunks.back();
527        newChunk.beginOpIndex = insertIndex;
528        newChunk.endOpIndex = insertIndex + 1;
529        newChunk.reorderChildren = (mDeferredBarrierType == kBarrier_OutOfOrder);
530
531        int nextChildIndex = mDisplayList->children.size();
532        newChunk.beginChildIndex = newChunk.endChildIndex = nextChildIndex;
533        mDeferredBarrierType = kBarrier_None;
534    } else {
535        // standard case - append to existing chunk
536        mDisplayList->chunks.back().endOpIndex = insertIndex + 1;
537    }
538    return insertIndex;
539}
540
541size_t DisplayListCanvas::flushAndAddOp(DisplayListOp* op) {
542    flushRestoreToCount();
543    flushTranslate();
544    return addOpAndUpdateChunk(op);
545}
546
547size_t DisplayListCanvas::addStateOp(StateOp* op) {
548    return flushAndAddOp(op);
549}
550
551size_t DisplayListCanvas::addDrawOp(DrawOp* op) {
552    Rect localBounds;
553    if (op->getLocalBounds(localBounds)) {
554        bool rejected = quickRejectRect(localBounds.left, localBounds.top,
555                localBounds.right, localBounds.bottom);
556        op->setQuickRejected(rejected);
557    }
558
559    mDisplayList->hasDrawOps = true;
560    return flushAndAddOp(op);
561}
562
563size_t DisplayListCanvas::addRenderNodeOp(DrawRenderNodeOp* op) {
564    int opIndex = addDrawOp(op);
565#if !HWUI_NEW_OPS
566    int childIndex = mDisplayList->addChild(op);
567
568    // update the chunk's child indices
569    DisplayList::Chunk& chunk = mDisplayList->chunks.back();
570    chunk.endChildIndex = childIndex + 1;
571
572    if (op->renderNode->stagingProperties().isProjectionReceiver()) {
573        // use staging property, since recording on UI thread
574        mDisplayList->projectionReceiveIndex = opIndex;
575    }
576#endif
577    return opIndex;
578}
579
580void DisplayListCanvas::refBitmapsInShader(const SkShader* shader) {
581    if (!shader) return;
582
583    // If this paint has an SkShader that has an SkBitmap add
584    // it to the bitmap pile
585    SkBitmap bitmap;
586    SkShader::TileMode xy[2];
587    if (shader->isABitmap(&bitmap, nullptr, xy)) {
588        refBitmap(bitmap);
589        return;
590    }
591    SkShader::ComposeRec rec;
592    if (shader->asACompose(&rec)) {
593        refBitmapsInShader(rec.fShaderA);
594        refBitmapsInShader(rec.fShaderB);
595        return;
596    }
597}
598
599}; // namespace uirenderer
600}; // namespace android
601