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