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