TestUtils.h revision 5e00c7ce063116c11315639f0035aca8ad73e8cc
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 <renderstate/RenderState.h>
25#include <renderthread/RenderThread.h>
26#include <Snapshot.h>
27
28#include <RecordedOp.h>
29#include <RecordingCanvas.h>
30
31#include <memory>
32
33namespace android {
34namespace uirenderer {
35
36typedef RecordingCanvas TestCanvas;
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        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        snapshot->clip(clip, SkRegion::kReplace_Op); // store clip first, so it isn't transformed
122        *(snapshot->transform) = transform;
123        return snapshot;
124    }
125
126    static SkBitmap createSkBitmap(int width, int height,
127            SkColorType colorType = kN32_SkColorType) {
128        SkBitmap bitmap;
129        SkImageInfo info = SkImageInfo::Make(width, height,
130                colorType, kPremul_SkAlphaType);
131        bitmap.setInfo(info);
132        bitmap.allocPixels(info);
133        return bitmap;
134    }
135
136    static sp<DeferredLayerUpdater> createTextureLayerUpdater(
137            renderthread::RenderThread& renderThread, uint32_t width, uint32_t height,
138            const SkMatrix& transform);
139
140    template<class CanvasType>
141    static std::unique_ptr<DisplayList> createDisplayList(int width, int height,
142            std::function<void(CanvasType& canvas)> canvasCallback) {
143        CanvasType canvas(width, height);
144        canvasCallback(canvas);
145        return std::unique_ptr<DisplayList>(canvas.finishRecording());
146    }
147
148    static sp<RenderNode> createNode(int left, int top, int right, int bottom,
149            std::function<void(RenderProperties& props, TestCanvas& canvas)> setup) {
150#if HWUI_NULL_GPU
151        // if RenderNodes are being sync'd/used, device info will be needed, since
152        // DeviceInfo::maxTextureSize() affects layer property
153        DeviceInfo::initialize();
154#endif
155
156        sp<RenderNode> node = new RenderNode();
157        RenderProperties& props = node->mutateStagingProperties();
158        props.setLeftTopRightBottom(left, top, right, bottom);
159        if (setup) {
160            TestCanvas canvas(props.getWidth(), props.getHeight());
161            setup(props, canvas);
162            node->setStagingDisplayList(canvas.finishRecording(), nullptr);
163        }
164        node->setPropertyFieldsDirty(0xFFFFFFFF);
165        return node;
166    }
167
168    static void recordNode(RenderNode& node,
169            std::function<void(TestCanvas&)> contentCallback) {
170       TestCanvas canvas(node.stagingProperties().getWidth(),
171               node.stagingProperties().getHeight());
172       contentCallback(canvas);
173       node.setStagingDisplayList(canvas.finishRecording(), nullptr);
174    }
175
176    /**
177     * Forces a sync of a tree of RenderNode, such that every descendant will have its staging
178     * properties and DisplayList moved to the render copies.
179     *
180     * Note: does not check dirtiness bits, so any non-staging DisplayLists will be discarded.
181     * For this reason, this should generally only be called once on a tree.
182     */
183    static void syncHierarchyPropertiesAndDisplayList(sp<RenderNode>& node) {
184        syncHierarchyPropertiesAndDisplayListImpl(node.get());
185    }
186
187    static sp<RenderNode>& getSyncedNode(sp<RenderNode>& node) {
188        syncHierarchyPropertiesAndDisplayList(node);
189        return node;
190    }
191
192    typedef std::function<void(renderthread::RenderThread& thread)> RtCallback;
193
194    class TestTask : public renderthread::RenderTask {
195    public:
196        TestTask(RtCallback rtCallback)
197                : rtCallback(rtCallback) {}
198        virtual ~TestTask() {}
199        virtual void run() override;
200        RtCallback rtCallback;
201    };
202
203    /**
204     * NOTE: requires surfaceflinger to run, otherwise this method will wait indefinitely.
205     */
206    static void runOnRenderThread(RtCallback rtCallback) {
207        TestTask task(rtCallback);
208        renderthread::RenderThread::getInstance().queueAndWait(&task);
209    }
210
211    static bool isRenderThreadRunning() {
212        return renderthread::RenderThread::hasInstance();
213    }
214
215    static SkColor interpolateColor(float fraction, SkColor start, SkColor end);
216
217    static void layoutTextUnscaled(const SkPaint& paint, const char* text,
218            std::vector<glyph_t>* outGlyphs, std::vector<float>* outPositions,
219            float* outTotalAdvance, Rect* outBounds);
220
221    static void drawUtf8ToCanvas(Canvas* canvas, const char* text,
222            const SkPaint& paint, float x, float y);
223
224    static void drawUtf8ToCanvas(Canvas* canvas, const char* text,
225            const SkPaint& paint, const SkPath& path);
226
227    static std::unique_ptr<uint16_t[]> asciiToUtf16(const char* str);
228
229private:
230    static void syncHierarchyPropertiesAndDisplayListImpl(RenderNode* node) {
231        node->syncProperties();
232        node->syncDisplayList(nullptr);
233        auto displayList = node->getDisplayList();
234        if (displayList) {
235            for (auto&& childOp : displayList->getChildren()) {
236                syncHierarchyPropertiesAndDisplayListImpl(childOp->renderNode);
237            }
238        }
239    }
240
241}; // class TestUtils
242
243} /* namespace uirenderer */
244} /* namespace android */
245