TestUtils.h revision fc9999505a36c66892d7ccce85187936105f4f36
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        return Bitmap::allocateHeapBitmap(info);
129    }
130
131    static sk_sp<Bitmap> createBitmap(int width, int height, SkBitmap* outBitmap) {
132        SkImageInfo info = SkImageInfo::Make(width, height, kN32_SkColorType, kPremul_SkAlphaType);
133        outBitmap->setInfo(info);
134        return Bitmap::allocateHeapBitmap(outBitmap, nullptr);
135    }
136
137    static SkBitmap createSkBitmap(int width, int height,
138            SkColorType colorType = kN32_SkColorType) {
139        SkBitmap bitmap;
140        sk_sp<SkColorSpace> colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
141        SkImageInfo info = SkImageInfo::Make(width, height,
142                colorType, kPremul_SkAlphaType, colorSpace);
143        bitmap.setInfo(info);
144        Bitmap::allocateHeapBitmap(&bitmap, nullptr);
145        return bitmap;
146    }
147
148    static sp<DeferredLayerUpdater> createTextureLayerUpdater(
149            renderthread::RenderThread& renderThread, uint32_t width, uint32_t height,
150            const SkMatrix& transform);
151
152    template<class CanvasType>
153    static std::unique_ptr<DisplayList> createDisplayList(int width, int height,
154            std::function<void(CanvasType& canvas)> canvasCallback) {
155        CanvasType canvas(width, height);
156        canvasCallback(canvas);
157        return std::unique_ptr<DisplayList>(canvas.finishRecording());
158    }
159
160    static sp<RenderNode> createNode(int left, int top, int right, int bottom,
161            std::function<void(RenderProperties& props, Canvas& canvas)> setup) {
162#if HWUI_NULL_GPU
163        // if RenderNodes are being sync'd/used, device info will be needed, since
164        // DeviceInfo::maxTextureSize() affects layer property
165        DeviceInfo::initialize();
166#endif
167
168        sp<RenderNode> node = new RenderNode();
169        RenderProperties& props = node->mutateStagingProperties();
170        props.setLeftTopRightBottom(left, top, right, bottom);
171        if (setup) {
172            std::unique_ptr<Canvas> canvas(Canvas::create_recording_canvas(props.getWidth(),
173                    props.getHeight()));
174            setup(props, *canvas.get());
175            node->setStagingDisplayList(canvas->finishRecording(), nullptr);
176        }
177        node->setPropertyFieldsDirty(0xFFFFFFFF);
178        return node;
179    }
180
181    template<class RecordingCanvasType>
182    static sp<RenderNode> createNode(int left, int top, int right, int bottom,
183            std::function<void(RenderProperties& props, RecordingCanvasType& canvas)> setup) {
184#if HWUI_NULL_GPU
185        // if RenderNodes are being sync'd/used, device info will be needed, since
186        // DeviceInfo::maxTextureSize() affects layer property
187        DeviceInfo::initialize();
188#endif
189
190        sp<RenderNode> node = new RenderNode();
191        RenderProperties& props = node->mutateStagingProperties();
192        props.setLeftTopRightBottom(left, top, right, bottom);
193        if (setup) {
194            RecordingCanvasType canvas(props.getWidth(), props.getHeight());
195            setup(props, canvas);
196            node->setStagingDisplayList(canvas.finishRecording(), nullptr);
197        }
198        node->setPropertyFieldsDirty(0xFFFFFFFF);
199        return node;
200    }
201
202    static void recordNode(RenderNode& node,
203            std::function<void(Canvas&)> contentCallback) {
204       std::unique_ptr<Canvas> canvas(Canvas::create_recording_canvas(
205            node.stagingProperties().getWidth(), node.stagingProperties().getHeight()));
206       contentCallback(*canvas.get());
207       node.setStagingDisplayList(canvas->finishRecording(), nullptr);
208    }
209
210    /**
211     * Forces a sync of a tree of RenderNode, such that every descendant will have its staging
212     * properties and DisplayList moved to the render copies.
213     *
214     * Note: does not check dirtiness bits, so any non-staging DisplayLists will be discarded.
215     * For this reason, this should generally only be called once on a tree.
216     */
217    static void syncHierarchyPropertiesAndDisplayList(sp<RenderNode>& node) {
218        syncHierarchyPropertiesAndDisplayListImpl(node.get());
219    }
220
221    static sp<RenderNode>& getSyncedNode(sp<RenderNode>& node) {
222        syncHierarchyPropertiesAndDisplayList(node);
223        return node;
224    }
225
226    typedef std::function<void(renderthread::RenderThread& thread)> RtCallback;
227
228    class TestTask : public renderthread::RenderTask {
229    public:
230        explicit TestTask(RtCallback rtCallback)
231                : rtCallback(rtCallback) {}
232        virtual ~TestTask() {}
233        virtual void run() override;
234        RtCallback rtCallback;
235    };
236
237    /**
238     * NOTE: requires surfaceflinger to run, otherwise this method will wait indefinitely.
239     */
240    static void runOnRenderThread(RtCallback rtCallback) {
241        TestTask task(rtCallback);
242        renderthread::RenderThread::getInstance().queueAndWait(&task);
243    }
244
245    static bool isRenderThreadRunning() {
246        return renderthread::RenderThread::hasInstance();
247    }
248
249    static SkColor interpolateColor(float fraction, SkColor start, SkColor end);
250
251    static void layoutTextUnscaled(const SkPaint& paint, const char* text,
252            std::vector<glyph_t>* outGlyphs, std::vector<float>* outPositions,
253            float* outTotalAdvance, Rect* outBounds);
254
255    static void drawUtf8ToCanvas(Canvas* canvas, const char* text,
256            const SkPaint& paint, float x, float y);
257
258    static void drawUtf8ToCanvas(Canvas* canvas, const char* text,
259            const SkPaint& paint, const SkPath& path);
260
261    static std::unique_ptr<uint16_t[]> asciiToUtf16(const char* str);
262
263private:
264    static void syncHierarchyPropertiesAndDisplayListImpl(RenderNode* node) {
265        node->syncProperties();
266        node->syncDisplayList(nullptr);
267        auto displayList = node->getDisplayList();
268        if (displayList) {
269            for (auto&& childOp : displayList->getChildren()) {
270                syncHierarchyPropertiesAndDisplayListImpl(childOp->renderNode);
271            }
272        }
273    }
274
275}; // class TestUtils
276
277} /* namespace uirenderer */
278} /* namespace android */
279