TestUtils.h revision aed7f58fb05a25ce2112829e77c0eb5dd268e8a7
1/*
2 * Copyright (C) 2015 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#pragma once
18
19#include <DeviceInfo.h>
20#include <DisplayList.h>
21#include <Matrix.h>
22#include <Rect.h>
23#include <RenderNode.h>
24#include <hwui/Bitmap.h>
25#include <renderstate/RenderState.h>
26#include <renderthread/RenderThread.h>
27#include <Snapshot.h>
28
29#include <RecordedOp.h>
30#include <RecordingCanvas.h>
31
32#include <memory>
33
34namespace android {
35namespace uirenderer {
36
37#define EXPECT_MATRIX_APPROX_EQ(a, b) \
38    EXPECT_TRUE(TestUtils::matricesAreApproxEqual(a, b))
39
40#define EXPECT_RECT_APPROX_EQ(a, b) \
41    EXPECT_TRUE(MathUtils::areEqual((a).left, (b).left) \
42            && MathUtils::areEqual((a).top, (b).top) \
43            && MathUtils::areEqual((a).right, (b).right) \
44            && MathUtils::areEqual((a).bottom, (b).bottom));
45
46#define EXPECT_CLIP_RECT(expRect, clipStatePtr) \
47        EXPECT_NE(nullptr, (clipStatePtr)) << "Op is unclipped"; \
48        if ((clipStatePtr)->mode == ClipMode::Rectangle) { \
49            EXPECT_EQ((expRect), reinterpret_cast<const ClipRect*>(clipStatePtr)->rect); \
50        } else { \
51            ADD_FAILURE() << "ClipState not a rect"; \
52        }
53/**
54 * Like gtest's TEST, but runs on the RenderThread, and 'renderThread' is passed, in top level scope
55 * (for e.g. accessing its RenderState)
56 */
57#define RENDERTHREAD_TEST(test_case_name, test_name) \
58    class test_case_name##_##test_name##_RenderThreadTest { \
59    public: \
60        static void doTheThing(renderthread::RenderThread& renderThread); \
61    }; \
62    TEST(test_case_name, test_name) { \
63        TestUtils::runOnRenderThread(test_case_name##_##test_name##_RenderThreadTest::doTheThing); \
64    }; \
65    void test_case_name##_##test_name##_RenderThreadTest::doTheThing(renderthread::RenderThread& renderThread)
66
67/**
68 * Sets a property value temporarily, generally for the duration of a test, restoring the previous
69 * value when going out of scope.
70 *
71 * Can be used e.g. to test behavior only active while Properties::debugOverdraw is enabled.
72 */
73template <typename T>
74class ScopedProperty {
75public:
76    ScopedProperty(T& property, T newValue)
77        : mPropertyPtr(&property)
78        , mOldValue(property) {
79        property = newValue;
80    }
81    ~ScopedProperty() {
82        *mPropertyPtr = mOldValue;
83    }
84private:
85    T* mPropertyPtr;
86    T mOldValue;
87};
88
89class TestUtils {
90public:
91    class SignalingDtor {
92    public:
93        SignalingDtor()
94                : mSignal(nullptr) {}
95        explicit SignalingDtor(int* signal)
96                : mSignal(signal) {}
97        void setSignal(int* signal) {
98            mSignal = signal;
99        }
100        ~SignalingDtor() {
101            if (mSignal) {
102                (*mSignal)++;
103            }
104        }
105    private:
106        int* mSignal;
107    };
108
109    static bool matricesAreApproxEqual(const Matrix4& a, const Matrix4& b) {
110        for (int i = 0; i < 16; i++) {
111            if (!MathUtils::areEqual(a[i], b[i])) {
112                return false;
113            }
114        }
115        return true;
116    }
117
118    static std::unique_ptr<Snapshot> makeSnapshot(const Matrix4& transform, const Rect& clip) {
119        std::unique_ptr<Snapshot> snapshot(new Snapshot());
120        snapshot->clip(clip, SkRegion::kReplace_Op); // store clip first, so it isn't transformed
121        *(snapshot->transform) = transform;
122        return snapshot;
123    }
124
125    static sk_sp<Bitmap> createBitmap(int width, int height,
126            SkColorType colorType = kN32_SkColorType) {
127        SkImageInfo info = SkImageInfo::Make(width, height, colorType, kPremul_SkAlphaType);
128        size_t size = height * info.minRowBytes();
129        return Bitmap::allocateHeapBitmap(size, info, info.minRowBytes(), nullptr);
130    }
131
132    static sk_sp<Bitmap> createBitmap(int width, int height, SkBitmap* outBitmap) {
133        SkImageInfo info = SkImageInfo::Make(width, height, kN32_SkColorType, kPremul_SkAlphaType);
134        outBitmap->setInfo(info);
135        return Bitmap::allocateHeapBitmap(outBitmap, nullptr);
136    }
137
138    static SkBitmap createSkBitmap(int width, int height,
139            SkColorType colorType = kN32_SkColorType) {
140        SkBitmap bitmap;
141        sk_sp<SkColorSpace> colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
142        SkImageInfo info = SkImageInfo::Make(width, height,
143                colorType, kPremul_SkAlphaType, colorSpace);
144        bitmap.setInfo(info);
145        Bitmap::allocateHeapBitmap(&bitmap, nullptr);
146        return bitmap;
147    }
148
149    static sp<DeferredLayerUpdater> createTextureLayerUpdater(
150            renderthread::RenderThread& renderThread, uint32_t width, uint32_t height,
151            const SkMatrix& transform);
152
153    template<class CanvasType>
154    static std::unique_ptr<DisplayList> createDisplayList(int width, int height,
155            std::function<void(CanvasType& canvas)> canvasCallback) {
156        CanvasType canvas(width, height);
157        canvasCallback(canvas);
158        return std::unique_ptr<DisplayList>(canvas.finishRecording());
159    }
160
161    static sp<RenderNode> createNode(int left, int top, int right, int bottom,
162            std::function<void(RenderProperties& props, Canvas& canvas)> setup) {
163#if HWUI_NULL_GPU
164        // if RenderNodes are being sync'd/used, device info will be needed, since
165        // DeviceInfo::maxTextureSize() affects layer property
166        DeviceInfo::initialize();
167#endif
168
169        sp<RenderNode> node = new RenderNode();
170        RenderProperties& props = node->mutateStagingProperties();
171        props.setLeftTopRightBottom(left, top, right, bottom);
172        if (setup) {
173            std::unique_ptr<Canvas> canvas(Canvas::create_recording_canvas(props.getWidth(),
174                    props.getHeight()));
175            setup(props, *canvas.get());
176            node->setStagingDisplayList(canvas->finishRecording(), nullptr);
177        }
178        node->setPropertyFieldsDirty(0xFFFFFFFF);
179        return node;
180    }
181
182    template<class RecordingCanvasType>
183    static sp<RenderNode> createNode(int left, int top, int right, int bottom,
184            std::function<void(RenderProperties& props, RecordingCanvasType& canvas)> setup) {
185#if HWUI_NULL_GPU
186        // if RenderNodes are being sync'd/used, device info will be needed, since
187        // DeviceInfo::maxTextureSize() affects layer property
188        DeviceInfo::initialize();
189#endif
190
191        sp<RenderNode> node = new RenderNode();
192        RenderProperties& props = node->mutateStagingProperties();
193        props.setLeftTopRightBottom(left, top, right, bottom);
194        if (setup) {
195            RecordingCanvasType canvas(props.getWidth(), props.getHeight());
196            setup(props, canvas);
197            node->setStagingDisplayList(canvas.finishRecording(), nullptr);
198        }
199        node->setPropertyFieldsDirty(0xFFFFFFFF);
200        return node;
201    }
202
203    static void recordNode(RenderNode& node,
204            std::function<void(Canvas&)> contentCallback) {
205       std::unique_ptr<Canvas> canvas(Canvas::create_recording_canvas(
206            node.stagingProperties().getWidth(), node.stagingProperties().getHeight()));
207       contentCallback(*canvas.get());
208       node.setStagingDisplayList(canvas->finishRecording(), nullptr);
209    }
210
211    /**
212     * Forces a sync of a tree of RenderNode, such that every descendant will have its staging
213     * properties and DisplayList moved to the render copies.
214     *
215     * Note: does not check dirtiness bits, so any non-staging DisplayLists will be discarded.
216     * For this reason, this should generally only be called once on a tree.
217     */
218    static void syncHierarchyPropertiesAndDisplayList(sp<RenderNode>& node) {
219        syncHierarchyPropertiesAndDisplayListImpl(node.get());
220    }
221
222    static sp<RenderNode>& getSyncedNode(sp<RenderNode>& node) {
223        syncHierarchyPropertiesAndDisplayList(node);
224        return node;
225    }
226
227    typedef std::function<void(renderthread::RenderThread& thread)> RtCallback;
228
229    class TestTask : public renderthread::RenderTask {
230    public:
231        explicit TestTask(RtCallback rtCallback)
232                : rtCallback(rtCallback) {}
233        virtual ~TestTask() {}
234        virtual void run() override;
235        RtCallback rtCallback;
236    };
237
238    /**
239     * NOTE: requires surfaceflinger to run, otherwise this method will wait indefinitely.
240     */
241    static void runOnRenderThread(RtCallback rtCallback) {
242        TestTask task(rtCallback);
243        renderthread::RenderThread::getInstance().queueAndWait(&task);
244    }
245
246    static bool isRenderThreadRunning() {
247        return renderthread::RenderThread::hasInstance();
248    }
249
250    static SkColor interpolateColor(float fraction, SkColor start, SkColor end);
251
252    static void layoutTextUnscaled(const SkPaint& paint, const char* text,
253            std::vector<glyph_t>* outGlyphs, std::vector<float>* outPositions,
254            float* outTotalAdvance, Rect* outBounds);
255
256    static void drawUtf8ToCanvas(Canvas* canvas, const char* text,
257            const SkPaint& paint, float x, float y);
258
259    static void drawUtf8ToCanvas(Canvas* canvas, const char* text,
260            const SkPaint& paint, const SkPath& path);
261
262    static std::unique_ptr<uint16_t[]> asciiToUtf16(const char* str);
263
264private:
265    static void syncHierarchyPropertiesAndDisplayListImpl(RenderNode* node) {
266        node->syncProperties();
267        node->syncDisplayList(nullptr);
268        auto displayList = node->getDisplayList();
269        if (displayList) {
270            for (auto&& childOp : displayList->getChildren()) {
271                syncHierarchyPropertiesAndDisplayListImpl(childOp->renderNode);
272            }
273        }
274    }
275
276}; // class TestUtils
277
278} /* namespace uirenderer */
279} /* namespace android */
280