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    resetRecording(width, height);
46}
47
48DisplayListCanvas::~DisplayListCanvas() {
49    LOG_ALWAYS_FATAL_IF(mDisplayList,
50            "Destroyed a DisplayListCanvas during a record!");
51}
52
53void DisplayListCanvas::resetRecording(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        GlFunctorLifecycleListener* listener) {
86    addDrawOp(new (alloc()) DrawFunctorOp(functor));
87    mDisplayList->functors.push_back({functor, listener});
88    mDisplayList->ref(listener);
89}
90
91SkCanvas* DisplayListCanvas::asSkCanvas() {
92    LOG_ALWAYS_FATAL_IF(!mDisplayList,
93            "attempting to get an SkCanvas when we are not recording!");
94    if (!mSkiaCanvasProxy) {
95        mSkiaCanvasProxy.reset(new SkiaCanvasProxy(this));
96    }
97
98    // SkCanvas instances default to identity transform, but should inherit
99    // the state of this Canvas; if this code was in the SkiaCanvasProxy
100    // constructor, we couldn't cache mSkiaCanvasProxy.
101    SkMatrix parentTransform;
102    getMatrix(&parentTransform);
103    mSkiaCanvasProxy.get()->setMatrix(parentTransform);
104
105    return mSkiaCanvasProxy.get();
106}
107
108int DisplayListCanvas::save(SaveFlags::Flags flags) {
109    addStateOp(new (alloc()) SaveOp((int) flags));
110    return mState.save((int) flags);
111}
112
113void DisplayListCanvas::restore() {
114    if (mRestoreSaveCount < 0) {
115        restoreToCount(getSaveCount() - 1);
116        return;
117    }
118
119    mRestoreSaveCount--;
120    flushTranslate();
121    mState.restore();
122}
123
124void DisplayListCanvas::restoreToCount(int saveCount) {
125    mRestoreSaveCount = saveCount;
126    flushTranslate();
127    mState.restoreToCount(saveCount);
128}
129
130int DisplayListCanvas::saveLayer(float left, float top, float right, float bottom,
131        const SkPaint* paint, SaveFlags::Flags flags) {
132    // force matrix/clip isolation for layer
133    flags |= SaveFlags::MatrixClip;
134
135    paint = refPaint(paint);
136    addStateOp(new (alloc()) SaveLayerOp(left, top, right, bottom, paint, (int) flags));
137    return mState.save((int) flags);
138}
139
140void DisplayListCanvas::translate(float dx, float dy) {
141    if (dx == 0.0f && dy == 0.0f) return;
142
143    mHasDeferredTranslate = true;
144    mTranslateX += dx;
145    mTranslateY += dy;
146    flushRestoreToCount();
147    mState.translate(dx, dy, 0.0f);
148}
149
150void DisplayListCanvas::rotate(float degrees) {
151    if (degrees == 0.0f) return;
152
153    addStateOp(new (alloc()) RotateOp(degrees));
154    mState.rotate(degrees);
155}
156
157void DisplayListCanvas::scale(float sx, float sy) {
158    if (sx == 1.0f && sy == 1.0f) return;
159
160    addStateOp(new (alloc()) ScaleOp(sx, sy));
161    mState.scale(sx, sy);
162}
163
164void DisplayListCanvas::skew(float sx, float sy) {
165    addStateOp(new (alloc()) SkewOp(sx, sy));
166    mState.skew(sx, sy);
167}
168
169void DisplayListCanvas::setMatrix(const SkMatrix& matrix) {
170    addStateOp(new (alloc()) SetMatrixOp(matrix));
171    mState.setMatrix(matrix);
172}
173
174void DisplayListCanvas::concat(const SkMatrix& matrix) {
175    addStateOp(new (alloc()) ConcatMatrixOp(matrix));
176    mState.concatMatrix(matrix);
177}
178
179bool DisplayListCanvas::getClipBounds(SkRect* outRect) const {
180    Rect bounds = mState.getLocalClipBounds();
181    *outRect = SkRect::MakeLTRB(bounds.left, bounds.top, bounds.right, bounds.bottom);
182    return !(outRect->isEmpty());
183}
184
185bool DisplayListCanvas::quickRejectRect(float left, float top, float right, float bottom) const {
186    return mState.quickRejectConservative(left, top, right, bottom);
187}
188
189bool DisplayListCanvas::quickRejectPath(const SkPath& path) const {
190    SkRect bounds = path.getBounds();
191    return mState.quickRejectConservative(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom);
192}
193
194
195bool DisplayListCanvas::clipRect(float left, float top, float right, float bottom,
196        SkRegion::Op op) {
197    addStateOp(new (alloc()) ClipRectOp(left, top, right, bottom, op));
198    return mState.clipRect(left, top, right, bottom, op);
199}
200
201bool DisplayListCanvas::clipPath(const SkPath* path, SkRegion::Op op) {
202    path = refPath(path);
203    addStateOp(new (alloc()) ClipPathOp(path, op));
204    return mState.clipPath(path, op);
205}
206
207bool DisplayListCanvas::clipRegion(const SkRegion* region, SkRegion::Op op) {
208    region = refRegion(region);
209    addStateOp(new (alloc()) ClipRegionOp(region, op));
210    return mState.clipRegion(region, op);
211}
212
213void DisplayListCanvas::drawRenderNode(RenderNode* renderNode) {
214    LOG_ALWAYS_FATAL_IF(!renderNode, "missing rendernode");
215    DrawRenderNodeOp* op = new (alloc()) DrawRenderNodeOp(
216            renderNode,
217            *mState.currentTransform(),
218            mState.clipIsSimple());
219    addRenderNodeOp(op);
220}
221
222void DisplayListCanvas::drawLayer(DeferredLayerUpdater* layerHandle) {
223    // We ref the DeferredLayerUpdater due to its thread-safe ref-counting
224    // semantics.
225    mDisplayList->ref(layerHandle);
226    addDrawOp(new (alloc()) DrawLayerOp(layerHandle->backingLayer()));
227}
228
229void DisplayListCanvas::drawBitmap(const SkBitmap* bitmap, const SkPaint* paint) {
230    bitmap = refBitmap(*bitmap);
231    paint = refPaint(paint);
232
233    addDrawOp(new (alloc()) DrawBitmapOp(bitmap, paint));
234}
235
236void DisplayListCanvas::drawBitmap(const SkBitmap& bitmap, float left, float top,
237        const SkPaint* paint) {
238    save(SaveFlags::Matrix);
239    translate(left, top);
240    drawBitmap(&bitmap, paint);
241    restore();
242}
243
244void DisplayListCanvas::drawBitmap(const SkBitmap& bitmap, const SkMatrix& matrix,
245        const SkPaint* paint) {
246    if (matrix.isIdentity()) {
247        drawBitmap(&bitmap, paint);
248    } else if (!(matrix.getType() & ~(SkMatrix::kScale_Mask | SkMatrix::kTranslate_Mask))
249            && MathUtils::isPositive(matrix.getScaleX())
250            && MathUtils::isPositive(matrix.getScaleY())) {
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(SaveFlags::Matrix);
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(SaveFlags::Matrix);
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(SaveFlags::Matrix);
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::drawNinePatch(const SkBitmap& bitmap, const Res_png_9patch& patch,
324        float dstLeft, float dstTop, float dstRight, float dstBottom, const SkPaint* paint) {
325    const SkBitmap* bitmapPtr = refBitmap(bitmap);
326    const Res_png_9patch* patchPtr = refPatch(&patch);
327    paint = refPaint(paint);
328
329    addDrawOp(new (alloc()) DrawPatchOp(bitmapPtr, patchPtr,
330            dstLeft, dstTop, dstRight, dstBottom, paint));
331}
332
333void DisplayListCanvas::drawColor(int color, SkXfermode::Mode mode) {
334    addDrawOp(new (alloc()) DrawColorOp(color, mode));
335}
336
337void DisplayListCanvas::drawPaint(const SkPaint& paint) {
338    SkRect bounds;
339    if (getClipBounds(&bounds)) {
340        drawRect(bounds.fLeft, bounds.fTop, bounds.fRight, bounds.fBottom, paint);
341    }
342}
343
344
345void DisplayListCanvas::drawRect(float left, float top, float right, float bottom,
346        const SkPaint& paint) {
347    addDrawOp(new (alloc()) DrawRectOp(left, top, right, bottom, refPaint(&paint)));
348}
349
350void DisplayListCanvas::drawRoundRect(float left, float top, float right, float bottom,
351        float rx, float ry, const SkPaint& paint) {
352    addDrawOp(new (alloc()) DrawRoundRectOp(left, top, right, bottom, rx, ry, refPaint(&paint)));
353}
354
355void DisplayListCanvas::drawRoundRect(
356        CanvasPropertyPrimitive* left, CanvasPropertyPrimitive* top,
357        CanvasPropertyPrimitive* right, CanvasPropertyPrimitive* bottom,
358        CanvasPropertyPrimitive* rx, CanvasPropertyPrimitive* ry,
359        CanvasPropertyPaint* paint) {
360    mDisplayList->ref(left);
361    mDisplayList->ref(top);
362    mDisplayList->ref(right);
363    mDisplayList->ref(bottom);
364    mDisplayList->ref(rx);
365    mDisplayList->ref(ry);
366    mDisplayList->ref(paint);
367    refBitmapsInShader(paint->value.getShader());
368    addDrawOp(new (alloc()) DrawRoundRectPropsOp(&left->value, &top->value,
369            &right->value, &bottom->value, &rx->value, &ry->value, &paint->value));
370}
371
372void DisplayListCanvas::drawCircle(float x, float y, float radius, const SkPaint& paint) {
373    addDrawOp(new (alloc()) DrawCircleOp(x, y, radius, refPaint(&paint)));
374}
375
376void DisplayListCanvas::drawCircle(CanvasPropertyPrimitive* x, CanvasPropertyPrimitive* y,
377        CanvasPropertyPrimitive* radius, CanvasPropertyPaint* paint) {
378    mDisplayList->ref(x);
379    mDisplayList->ref(y);
380    mDisplayList->ref(radius);
381    mDisplayList->ref(paint);
382    refBitmapsInShader(paint->value.getShader());
383    addDrawOp(new (alloc()) DrawCirclePropsOp(&x->value, &y->value,
384            &radius->value, &paint->value));
385}
386
387void DisplayListCanvas::drawOval(float left, float top, float right, float bottom,
388        const SkPaint& paint) {
389    addDrawOp(new (alloc()) DrawOvalOp(left, top, right, bottom, refPaint(&paint)));
390}
391
392void DisplayListCanvas::drawArc(float left, float top, float right, float bottom,
393        float startAngle, float sweepAngle, bool useCenter, const SkPaint& paint) {
394    if (fabs(sweepAngle) >= 360.0f) {
395        drawOval(left, top, right, bottom, paint);
396    } else {
397        addDrawOp(new (alloc()) DrawArcOp(left, top, right, bottom,
398                        startAngle, sweepAngle, useCenter, refPaint(&paint)));
399    }
400}
401
402void DisplayListCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
403    addDrawOp(new (alloc()) DrawPathOp(refPath(&path), refPaint(&paint)));
404}
405
406void DisplayListCanvas::drawLines(const float* points, int count, const SkPaint& paint) {
407    points = refBuffer<float>(points, count);
408
409    addDrawOp(new (alloc()) DrawLinesOp(points, count, refPaint(&paint)));
410}
411
412void DisplayListCanvas::drawPoints(const float* points, int count, const SkPaint& paint) {
413    points = refBuffer<float>(points, count);
414
415    addDrawOp(new (alloc()) DrawPointsOp(points, count, refPaint(&paint)));
416}
417
418void DisplayListCanvas::drawVectorDrawable(VectorDrawableRoot* tree) {
419    mDisplayList->ref(tree);
420    mDisplayList->vectorDrawables.push_back(tree);
421    addDrawOp(new (alloc()) DrawVectorDrawableOp(tree, tree->stagingProperties()->getBounds()));
422}
423
424void DisplayListCanvas::drawGlyphsOnPath(const uint16_t* glyphs, int count,
425        const SkPath& path, float hOffset, float vOffset, const SkPaint& paint) {
426    if (!glyphs || count <= 0) return;
427
428    int bytesCount = 2 * count;
429    DrawOp* op = new (alloc()) DrawTextOnPathOp(refBuffer<glyph_t>(glyphs, count),
430            bytesCount, count, refPath(&path),
431            hOffset, vOffset, refPaint(&paint));
432    addDrawOp(op);
433}
434
435void DisplayListCanvas::drawGlyphs(const uint16_t* glyphs, const float* positions,
436        int count, const SkPaint& paint, float x, float y,
437        float boundsLeft, float boundsTop, float boundsRight, float boundsBottom,
438        float totalAdvance) {
439
440    if (!glyphs || count <= 0 || PaintUtils::paintWillNotDrawText(paint)) return;
441
442    int bytesCount = count * 2;
443    positions = refBuffer<float>(positions, count * 2);
444    Rect bounds(boundsLeft, boundsTop, boundsRight, boundsBottom);
445
446    DrawOp* op = new (alloc()) DrawTextOp(refBuffer<glyph_t>(glyphs, count), bytesCount, count,
447            x, y, positions, refPaint(&paint), totalAdvance, bounds);
448    addDrawOp(op);
449    drawTextDecorations(x, y, totalAdvance, paint);
450}
451
452void DisplayListCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
453    if (paint.getStyle() != SkPaint::kFill_Style ||
454            (paint.isAntiAlias() && !mState.currentTransform()->isSimple())) {
455        SkRegion::Iterator it(region);
456        while (!it.done()) {
457            const SkIRect& r = it.rect();
458            drawRect(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);
459            it.next();
460        }
461    } else {
462        int count = 0;
463        Vector<float> rects;
464        SkRegion::Iterator it(region);
465        while (!it.done()) {
466            const SkIRect& r = it.rect();
467            rects.push(r.fLeft);
468            rects.push(r.fTop);
469            rects.push(r.fRight);
470            rects.push(r.fBottom);
471            count += 4;
472            it.next();
473        }
474        drawRects(rects.array(), count, &paint);
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 = mDisplayList->ops.size();
515#if HWUI_NEW_OPS
516    LOG_ALWAYS_FATAL("unsupported");
517#else
518    mDisplayList->ops.push_back(op);
519#endif
520    if (mDeferredBarrierType != kBarrier_None) {
521        // op is first in new chunk
522        mDisplayList->chunks.emplace_back();
523        DisplayList::Chunk& newChunk = mDisplayList->chunks.back();
524        newChunk.beginOpIndex = insertIndex;
525        newChunk.endOpIndex = insertIndex + 1;
526        newChunk.reorderChildren = (mDeferredBarrierType == kBarrier_OutOfOrder);
527
528        int nextChildIndex = mDisplayList->children.size();
529        newChunk.beginChildIndex = newChunk.endChildIndex = nextChildIndex;
530        mDeferredBarrierType = kBarrier_None;
531    } else {
532        // standard case - append to existing chunk
533        mDisplayList->chunks.back().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    mDisplayList->hasDrawOps = true;
557    return flushAndAddOp(op);
558}
559
560size_t DisplayListCanvas::addRenderNodeOp(DrawRenderNodeOp* op) {
561    int opIndex = addDrawOp(op);
562#if !HWUI_NEW_OPS
563    int childIndex = mDisplayList->addChild(op);
564
565    // update the chunk's child indices
566    DisplayList::Chunk& chunk = mDisplayList->chunks.back();
567    chunk.endChildIndex = childIndex + 1;
568
569    if (op->renderNode->stagingProperties().isProjectionReceiver()) {
570        // use staging property, since recording on UI thread
571        mDisplayList->projectionReceiveIndex = opIndex;
572    }
573#endif
574    return opIndex;
575}
576
577void DisplayListCanvas::refBitmapsInShader(const SkShader* shader) {
578    if (!shader) return;
579
580    // If this paint has an SkShader that has an SkBitmap add
581    // it to the bitmap pile
582    SkBitmap bitmap;
583    SkShader::TileMode xy[2];
584    if (shader->isABitmap(&bitmap, nullptr, xy)) {
585        refBitmap(bitmap);
586        return;
587    }
588    SkShader::ComposeRec rec;
589    if (shader->asACompose(&rec)) {
590        refBitmapsInShader(rec.fShaderA);
591        refBitmapsInShader(rec.fShaderB);
592        return;
593    }
594}
595
596}; // namespace uirenderer
597}; // namespace android
598