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