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