• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2013 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkCanvas.h"
9 #include "include/core/SkData.h"
10 #include "include/core/SkOverdrawCanvas.h"
11 #include "include/core/SkPath.h"
12 #include "include/core/SkRRect.h"
13 #include "include/core/SkRegion.h"
14 #include "include/core/SkSurface.h"
15 #include "include/gpu/GrBackendSurface.h"
16 #include "include/gpu/GrContext.h"
17 #include "src/core/SkAutoPixmapStorage.h"
18 #include "src/core/SkDevice.h"
19 #include "src/core/SkUtils.h"
20 #include "src/gpu/GrContextPriv.h"
21 #include "src/gpu/GrGpu.h"
22 #include "src/gpu/GrGpuResourcePriv.h"
23 #include "src/gpu/GrRenderTargetContext.h"
24 #include "src/gpu/GrResourceProvider.h"
25 #include "src/gpu/SkGpuDevice.h"
26 #include "src/image/SkImage_Base.h"
27 #include "src/image/SkImage_Gpu.h"
28 #include "src/image/SkSurface_Gpu.h"
29 #include "tests/Test.h"
30 #include "tests/TestUtils.h"
31 
32 #include <functional>
33 #include <initializer_list>
34 #include <vector>
35 
36 #include "tools/ToolUtils.h"
37 
release_direct_surface_storage(void * pixels,void * context)38 static void release_direct_surface_storage(void* pixels, void* context) {
39     SkASSERT(pixels == context);
40     sk_free(pixels);
41 }
create_surface(SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)42 static sk_sp<SkSurface> create_surface(SkAlphaType at = kPremul_SkAlphaType,
43                                        SkImageInfo* requestedInfo = nullptr) {
44     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
45     if (requestedInfo) {
46         *requestedInfo = info;
47     }
48     return SkSurface::MakeRaster(info);
49 }
create_direct_surface(SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)50 static sk_sp<SkSurface> create_direct_surface(SkAlphaType at = kPremul_SkAlphaType,
51                                               SkImageInfo* requestedInfo = nullptr) {
52     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
53     if (requestedInfo) {
54         *requestedInfo = info;
55     }
56     const size_t rowBytes = info.minRowBytes();
57     void* storage = sk_malloc_throw(info.computeByteSize(rowBytes));
58     return SkSurface::MakeRasterDirectReleaseProc(info, storage, rowBytes,
59                                                   release_direct_surface_storage,
60                                                   storage);
61 }
create_gpu_surface(GrContext * context,SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)62 static sk_sp<SkSurface> create_gpu_surface(GrContext* context, SkAlphaType at = kPremul_SkAlphaType,
63                                            SkImageInfo* requestedInfo = nullptr) {
64     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
65     if (requestedInfo) {
66         *requestedInfo = info;
67     }
68     return SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info);
69 }
create_gpu_scratch_surface(GrContext * context,SkAlphaType at=kPremul_SkAlphaType,SkImageInfo * requestedInfo=nullptr)70 static sk_sp<SkSurface> create_gpu_scratch_surface(GrContext* context,
71                                                    SkAlphaType at = kPremul_SkAlphaType,
72                                                    SkImageInfo* requestedInfo = nullptr) {
73     const SkImageInfo info = SkImageInfo::MakeN32(10, 10, at);
74     if (requestedInfo) {
75         *requestedInfo = info;
76     }
77     return SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info);
78 }
79 
DEF_TEST(SurfaceEmpty,reporter)80 DEF_TEST(SurfaceEmpty, reporter) {
81     const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
82     REPORTER_ASSERT(reporter, nullptr == SkSurface::MakeRaster(info));
83     REPORTER_ASSERT(reporter, nullptr == SkSurface::MakeRasterDirect(info, nullptr, 0));
84 
85 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceEmpty_Gpu,reporter,ctxInfo)86 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceEmpty_Gpu, reporter, ctxInfo) {
87     const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
88     REPORTER_ASSERT(reporter, nullptr ==
89                     SkSurface::MakeRenderTarget(ctxInfo.grContext(), SkBudgeted::kNo, info));
90 }
91 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_colorTypeSupportedAsSurface,reporter,ctxInfo)92 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_colorTypeSupportedAsSurface, reporter, ctxInfo) {
93     GrContext* context = ctxInfo.grContext();
94 
95     for (int ct = 0; ct < kLastEnum_SkColorType; ++ct) {
96         static constexpr int kSize = 10;
97 
98         SkColorType colorType = static_cast<SkColorType>(ct);
99         auto info = SkImageInfo::Make(kSize, kSize, colorType, kOpaque_SkAlphaType, nullptr);
100         bool can = context->colorTypeSupportedAsSurface(colorType);
101         auto surf = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info, 1, nullptr);
102         REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d",
103                         colorType, can, SkToBool(surf));
104 
105         GrBackendTexture backendTex = context->createBackendTexture(
106                 kSize, kSize, colorType,
107                 SkColors::kTransparent, GrMipMapped::kNo, GrRenderable::kYes, GrProtected::kNo);
108         surf = SkSurface::MakeFromBackendTexture(context, backendTex,
109                                                  kTopLeft_GrSurfaceOrigin, 0, colorType, nullptr,
110                                                  nullptr);
111         REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d",
112                         colorType, can, SkToBool(surf));
113 
114         surf = SkSurface::MakeFromBackendTextureAsRenderTarget(context, backendTex,
115                                                                kTopLeft_GrSurfaceOrigin, 1,
116                                                                colorType, nullptr, nullptr);
117         REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d",
118                         colorType, can, SkToBool(surf));
119 
120         surf.reset();
121         context->flush();
122         context->deleteBackendTexture(backendTex);
123 
124         static constexpr int kSampleCnt = 2;
125 
126         can = context->maxSurfaceSampleCountForColorType(colorType) >= kSampleCnt;
127         surf = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, info, kSampleCnt, nullptr);
128         REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d",
129                         colorType, can, SkToBool(surf));
130 
131         backendTex = context->createBackendTexture(kSize, kSize, colorType,
132                                                    SkColors::kTransparent,
133                                                    GrMipMapped::kNo, GrRenderable::kYes,
134                                                    GrProtected::kNo);
135         surf = SkSurface::MakeFromBackendTexture(context, backendTex,
136                                                  kTopLeft_GrSurfaceOrigin, kSampleCnt, colorType,
137                                                  nullptr, nullptr);
138         REPORTER_ASSERT(reporter, can == SkToBool(surf),
139                         "colorTypeSupportedAsSurface:%d, surf:%d, ct:%d", can, SkToBool(surf),
140                         colorType);
141         // Ensure that the sample count stored on the resulting SkSurface is a valid value.
142         if (surf) {
143             auto* rtc = ((SkSurface_Gpu*)(surf.get()))->getDevice()->accessRenderTargetContext();
144             int storedCnt = rtc->numSamples();
145             int allowedCnt = context->priv().caps()->getRenderTargetSampleCount(
146                     storedCnt, backendTex.getBackendFormat());
147             REPORTER_ASSERT(reporter, storedCnt == allowedCnt,
148                             "Should store an allowed sample count (%d vs %d)", allowedCnt,
149                             storedCnt);
150         }
151 
152         surf = SkSurface::MakeFromBackendTextureAsRenderTarget(context, backendTex,
153                                                                kTopLeft_GrSurfaceOrigin, kSampleCnt,
154                                                                colorType, nullptr, nullptr);
155         REPORTER_ASSERT(reporter, can == SkToBool(surf),
156                         "colorTypeSupportedAsSurface:%d, surf:%d, ct:%d", can, SkToBool(surf),
157                         colorType);
158         if (surf) {
159             auto* rtc = ((SkSurface_Gpu*)(surf.get()))->getDevice()->accessRenderTargetContext();
160             int storedCnt = rtc->numSamples();
161             int allowedCnt = context->priv().caps()->getRenderTargetSampleCount(
162                     storedCnt, backendTex.getBackendFormat());
163             REPORTER_ASSERT(reporter, storedCnt == allowedCnt,
164                             "Should store an allowed sample count (%d vs %d)", allowedCnt,
165                             storedCnt);
166         }
167 
168         surf.reset();
169         context->flush();
170         context->deleteBackendTexture(backendTex);
171 
172         auto* gpu = context->priv().getGpu();
173 
174         GrBackendRenderTarget backendRenderTarget = gpu->createTestingOnlyBackendRenderTarget(
175                 16, 16, SkColorTypeToGrColorType(colorType));
176         can = context->colorTypeSupportedAsSurface(colorType);
177         surf = SkSurface::MakeFromBackendRenderTarget(context, backendRenderTarget,
178                                                       kTopLeft_GrSurfaceOrigin, colorType, nullptr,
179                                                       nullptr);
180         REPORTER_ASSERT(reporter, can == SkToBool(surf), "ct: %d, can: %d, surf: %d", colorType,
181                         can, SkToBool(surf));
182         surf.reset();
183         context->flush();
184         if (backendRenderTarget.isValid()) {
185             gpu->deleteTestingOnlyBackendRenderTarget(backendRenderTarget);
186         }
187     }
188 }
189 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_maxSurfaceSamplesForColorType,reporter,ctxInfo)190 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_maxSurfaceSamplesForColorType, reporter, ctxInfo) {
191     GrContext* context = ctxInfo.grContext();
192 
193     static constexpr int kSize = 10;
194 
195     for (int ct = 0; ct < kLastEnum_SkColorType; ++ct) {
196 
197         SkColorType colorType = static_cast<SkColorType>(ct);
198         int max = context->maxSurfaceSampleCountForColorType(colorType);
199         if (!max) {
200             continue;
201         }
202         GrBackendTexture backendTex = context->createBackendTexture(
203                 kSize, kSize, colorType, SkColors::kTransparent,
204                 GrMipMapped::kNo, GrRenderable::kYes, GrProtected::kNo);
205         if (!backendTex.isValid()) {
206             continue;
207         }
208         SkScopeExit freeTex([&backendTex, context] {
209             context->deleteBackendTexture(backendTex);
210         });
211         auto info = SkImageInfo::Make(kSize, kSize, colorType, kOpaque_SkAlphaType, nullptr);
212         auto surf = SkSurface::MakeFromBackendTexture(context, backendTex,
213                                                       kTopLeft_GrSurfaceOrigin, max,
214                                                       colorType, nullptr, nullptr);
215         REPORTER_ASSERT(reporter, surf);
216         if (!surf) {
217             continue;
218         }
219         int sampleCnt = ((SkSurface_Gpu*)(surf.get()))
220                                 ->getDevice()
221                                 ->accessRenderTargetContext()
222                                 ->numSamples();
223         REPORTER_ASSERT(reporter, sampleCnt == max, "Exected: %d, actual: %d", max, sampleCnt);
224     }
225 }
226 
test_canvas_peek(skiatest::Reporter * reporter,sk_sp<SkSurface> & surface,const SkImageInfo & requestInfo,bool expectPeekSuccess)227 static void test_canvas_peek(skiatest::Reporter* reporter,
228                              sk_sp<SkSurface>& surface,
229                              const SkImageInfo& requestInfo,
230                              bool expectPeekSuccess) {
231     const SkColor color = SK_ColorRED;
232     const SkPMColor pmcolor = SkPreMultiplyColor(color);
233     surface->getCanvas()->clear(color);
234 
235     SkPixmap pmap;
236     bool success = surface->getCanvas()->peekPixels(&pmap);
237     REPORTER_ASSERT(reporter, expectPeekSuccess == success);
238 
239     SkPixmap pmap2;
240     const void* addr2 = surface->peekPixels(&pmap2) ? pmap2.addr() : nullptr;
241 
242     if (success) {
243         REPORTER_ASSERT(reporter, requestInfo == pmap.info());
244         REPORTER_ASSERT(reporter, requestInfo.minRowBytes() <= pmap.rowBytes());
245         REPORTER_ASSERT(reporter, pmcolor == *pmap.addr32());
246 
247         REPORTER_ASSERT(reporter, pmap.addr() == pmap2.addr());
248         REPORTER_ASSERT(reporter, pmap.info() == pmap2.info());
249         REPORTER_ASSERT(reporter, pmap.rowBytes() == pmap2.rowBytes());
250     } else {
251         REPORTER_ASSERT(reporter, nullptr == addr2);
252     }
253 }
DEF_TEST(SurfaceCanvasPeek,reporter)254 DEF_TEST(SurfaceCanvasPeek, reporter) {
255     for (auto& surface_func : { &create_surface, &create_direct_surface }) {
256         SkImageInfo requestInfo;
257         auto surface(surface_func(kPremul_SkAlphaType, &requestInfo));
258         test_canvas_peek(reporter, surface, requestInfo, true);
259     }
260 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCanvasPeek_Gpu,reporter,ctxInfo)261 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCanvasPeek_Gpu, reporter, ctxInfo) {
262     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
263         SkImageInfo requestInfo;
264         auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, &requestInfo));
265         test_canvas_peek(reporter, surface, requestInfo, false);
266     }
267 }
268 
test_snapshot_alphatype(skiatest::Reporter * reporter,const sk_sp<SkSurface> & surface,SkAlphaType expectedAlphaType)269 static void test_snapshot_alphatype(skiatest::Reporter* reporter, const sk_sp<SkSurface>& surface,
270                                     SkAlphaType expectedAlphaType) {
271     REPORTER_ASSERT(reporter, surface);
272     if (surface) {
273         sk_sp<SkImage> image(surface->makeImageSnapshot());
274         REPORTER_ASSERT(reporter, image);
275         if (image) {
276             REPORTER_ASSERT(reporter, image->alphaType() == expectedAlphaType);
277         }
278     }
279 }
DEF_TEST(SurfaceSnapshotAlphaType,reporter)280 DEF_TEST(SurfaceSnapshotAlphaType, reporter) {
281     for (auto& surface_func : { &create_surface, &create_direct_surface }) {
282         for (auto& at: { kOpaque_SkAlphaType, kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
283             auto surface(surface_func(at, nullptr));
284             test_snapshot_alphatype(reporter, surface, at);
285         }
286     }
287 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceSnapshotAlphaType_Gpu,reporter,ctxInfo)288 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceSnapshotAlphaType_Gpu, reporter, ctxInfo) {
289     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
290         // GPU doesn't support creating unpremul surfaces, so only test opaque + premul
291         for (auto& at : { kOpaque_SkAlphaType, kPremul_SkAlphaType }) {
292             auto surface(surface_func(ctxInfo.grContext(), at, nullptr));
293             test_snapshot_alphatype(reporter, surface, at);
294         }
295     }
296 }
297 
test_backend_texture_access_copy_on_write(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::BackendHandleAccess access)298 static void test_backend_texture_access_copy_on_write(
299     skiatest::Reporter* reporter, SkSurface* surface, SkSurface::BackendHandleAccess access) {
300     GrBackendTexture tex1 = surface->getBackendTexture(access);
301     sk_sp<SkImage> snap1(surface->makeImageSnapshot());
302 
303     GrBackendTexture tex2 = surface->getBackendTexture(access);
304     sk_sp<SkImage> snap2(surface->makeImageSnapshot());
305 
306     // If the access mode triggers CoW, then the backend objects should reflect it.
307     REPORTER_ASSERT(reporter, GrBackendTexture::TestingOnly_Equals(tex1, tex2) == (snap1 == snap2));
308 }
309 
test_backend_rendertarget_access_copy_on_write(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::BackendHandleAccess access)310 static void test_backend_rendertarget_access_copy_on_write(
311     skiatest::Reporter* reporter, SkSurface* surface, SkSurface::BackendHandleAccess access) {
312     GrBackendRenderTarget rt1 = surface->getBackendRenderTarget(access);
313     sk_sp<SkImage> snap1(surface->makeImageSnapshot());
314 
315     GrBackendRenderTarget rt2 = surface->getBackendRenderTarget(access);
316     sk_sp<SkImage> snap2(surface->makeImageSnapshot());
317 
318     // If the access mode triggers CoW, then the backend objects should reflect it.
319     REPORTER_ASSERT(reporter, GrBackendRenderTarget::TestingOnly_Equals(rt1, rt2) ==
320                               (snap1 == snap2));
321 }
322 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendSurfaceAccessCopyOnWrite_Gpu,reporter,ctxInfo)323 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendSurfaceAccessCopyOnWrite_Gpu, reporter, ctxInfo) {
324     const SkSurface::BackendHandleAccess accessModes[] = {
325         SkSurface::kFlushRead_BackendHandleAccess,
326         SkSurface::kFlushWrite_BackendHandleAccess,
327         SkSurface::kDiscardWrite_BackendHandleAccess,
328     };
329 
330     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
331         for (auto& accessMode : accessModes) {
332             {
333                 auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
334                 test_backend_texture_access_copy_on_write(reporter, surface.get(), accessMode);
335             }
336             {
337                 auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
338                 test_backend_rendertarget_access_copy_on_write(reporter, surface.get(), accessMode);
339             }
340         }
341     }
342 }
343 
344 template<typename Type, Type(SkSurface::*func)(SkSurface::BackendHandleAccess)>
test_backend_unique_id(skiatest::Reporter * reporter,SkSurface * surface)345 static void test_backend_unique_id(skiatest::Reporter* reporter, SkSurface* surface) {
346     sk_sp<SkImage> image0(surface->makeImageSnapshot());
347 
348     Type obj = (surface->*func)(SkSurface::kFlushRead_BackendHandleAccess);
349     REPORTER_ASSERT(reporter, obj.isValid());
350     sk_sp<SkImage> image1(surface->makeImageSnapshot());
351     // just read access should not affect the snapshot
352     REPORTER_ASSERT(reporter, image0->uniqueID() == image1->uniqueID());
353 
354     obj = (surface->*func)(SkSurface::kFlushWrite_BackendHandleAccess);
355     REPORTER_ASSERT(reporter, obj.isValid());
356     sk_sp<SkImage> image2(surface->makeImageSnapshot());
357     // expect a new image, since we claimed we would write
358     REPORTER_ASSERT(reporter, image0->uniqueID() != image2->uniqueID());
359 
360     obj = (surface->*func)(SkSurface::kDiscardWrite_BackendHandleAccess);
361     REPORTER_ASSERT(reporter, obj.isValid());
362     sk_sp<SkImage> image3(surface->makeImageSnapshot());
363     // expect a new(er) image, since we claimed we would write
364     REPORTER_ASSERT(reporter, image0->uniqueID() != image3->uniqueID());
365     REPORTER_ASSERT(reporter, image2->uniqueID() != image3->uniqueID());
366 }
367 
368 // No CPU test.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendHandleAccessIDs_Gpu,reporter,ctxInfo)369 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBackendHandleAccessIDs_Gpu, reporter, ctxInfo) {
370     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
371         {
372             auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
373             test_backend_unique_id<GrBackendTexture, &SkSurface::getBackendTexture>(reporter,
374                                                                                     surface.get());
375         }
376         {
377             auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
378             test_backend_unique_id<GrBackendRenderTarget, &SkSurface::getBackendRenderTarget>(
379                                                                 reporter, surface.get());
380         }
381     }
382 }
383 
384 // Verify that the right canvas commands trigger a copy on write.
test_copy_on_write(skiatest::Reporter * reporter,SkSurface * surface)385 static void test_copy_on_write(skiatest::Reporter* reporter, SkSurface* surface) {
386     SkCanvas* canvas = surface->getCanvas();
387 
388     const SkRect testRect =
389         SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
390                          SkIntToScalar(4), SkIntToScalar(5));
391     SkPath testPath;
392     testPath.addRect(SkRect::MakeXYWH(SkIntToScalar(0), SkIntToScalar(0),
393                                       SkIntToScalar(2), SkIntToScalar(1)));
394 
395     const SkIRect testIRect = SkIRect::MakeXYWH(0, 0, 2, 1);
396 
397     SkRegion testRegion;
398     testRegion.setRect(testIRect);
399 
400 
401     const SkColor testColor = 0x01020304;
402     const SkPaint testPaint;
403     const SkPoint testPoints[3] = {
404         {SkIntToScalar(0), SkIntToScalar(0)},
405         {SkIntToScalar(2), SkIntToScalar(1)},
406         {SkIntToScalar(0), SkIntToScalar(2)}
407     };
408     const size_t testPointCount = 3;
409 
410     SkBitmap testBitmap;
411     testBitmap.allocN32Pixels(10, 10);
412     testBitmap.eraseColor(0);
413 
414     SkRRect testRRect;
415     testRRect.setRectXY(testRect, SK_Scalar1, SK_Scalar1);
416 
417     SkString testText("Hello World");
418 
419 #define EXPECT_COPY_ON_WRITE(command)                               \
420     {                                                               \
421         sk_sp<SkImage> imageBefore = surface->makeImageSnapshot();  \
422         sk_sp<SkImage> aur_before(imageBefore);                     \
423         canvas-> command ;                                          \
424         sk_sp<SkImage> imageAfter = surface->makeImageSnapshot();   \
425         sk_sp<SkImage> aur_after(imageAfter);                       \
426         REPORTER_ASSERT(reporter, imageBefore != imageAfter);       \
427     }
428 
429     EXPECT_COPY_ON_WRITE(clear(testColor))
430     EXPECT_COPY_ON_WRITE(drawPaint(testPaint))
431     EXPECT_COPY_ON_WRITE(drawPoints(SkCanvas::kPoints_PointMode, testPointCount, testPoints, \
432         testPaint))
433     EXPECT_COPY_ON_WRITE(drawOval(testRect, testPaint))
434     EXPECT_COPY_ON_WRITE(drawRect(testRect, testPaint))
435     EXPECT_COPY_ON_WRITE(drawRRect(testRRect, testPaint))
436     EXPECT_COPY_ON_WRITE(drawPath(testPath, testPaint))
437     EXPECT_COPY_ON_WRITE(drawBitmap(testBitmap, 0, 0))
438     EXPECT_COPY_ON_WRITE(drawBitmapRect(testBitmap, testRect, nullptr))
439     EXPECT_COPY_ON_WRITE(drawBitmapNine(testBitmap, testIRect, testRect, nullptr))
440     EXPECT_COPY_ON_WRITE(drawString(testText, 0, 1, SkFont(), testPaint))
441 }
DEF_TEST(SurfaceCopyOnWrite,reporter)442 DEF_TEST(SurfaceCopyOnWrite, reporter) {
443     test_copy_on_write(reporter, create_surface().get());
444 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCopyOnWrite_Gpu,reporter,ctxInfo)445 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCopyOnWrite_Gpu, reporter, ctxInfo) {
446     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
447         auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
448         test_copy_on_write(reporter, surface.get());
449     }
450 }
451 
test_writable_after_snapshot_release(skiatest::Reporter * reporter,SkSurface * surface)452 static void test_writable_after_snapshot_release(skiatest::Reporter* reporter,
453                                                  SkSurface* surface) {
454     // This test succeeds by not triggering an assertion.
455     // The test verifies that the surface remains writable (usable) after
456     // acquiring and releasing a snapshot without triggering a copy on write.
457     SkCanvas* canvas = surface->getCanvas();
458     canvas->clear(1);
459     surface->makeImageSnapshot();  // Create and destroy SkImage
460     canvas->clear(2);  // Must not assert internally
461 }
DEF_TEST(SurfaceWriteableAfterSnapshotRelease,reporter)462 DEF_TEST(SurfaceWriteableAfterSnapshotRelease, reporter) {
463     test_writable_after_snapshot_release(reporter, create_surface().get());
464 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWriteableAfterSnapshotRelease_Gpu,reporter,ctxInfo)465 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWriteableAfterSnapshotRelease_Gpu, reporter, ctxInfo) {
466     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
467         auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
468         test_writable_after_snapshot_release(reporter, surface.get());
469     }
470 }
471 
test_crbug263329(skiatest::Reporter * reporter,SkSurface * surface1,SkSurface * surface2)472 static void test_crbug263329(skiatest::Reporter* reporter,
473                              SkSurface* surface1,
474                              SkSurface* surface2) {
475     // This is a regression test for crbug.com/263329
476     // Bug was caused by onCopyOnWrite releasing the old surface texture
477     // back to the scratch texture pool even though the texture is used
478     // by and active SkImage_Gpu.
479     SkCanvas* canvas1 = surface1->getCanvas();
480     SkCanvas* canvas2 = surface2->getCanvas();
481     canvas1->clear(1);
482     sk_sp<SkImage> image1(surface1->makeImageSnapshot());
483     // Trigger copy on write, new backing is a scratch texture
484     canvas1->clear(2);
485     sk_sp<SkImage> image2(surface1->makeImageSnapshot());
486     // Trigger copy on write, old backing should not be returned to scratch
487     // pool because it is held by image2
488     canvas1->clear(3);
489 
490     canvas2->clear(4);
491     sk_sp<SkImage> image3(surface2->makeImageSnapshot());
492     // Trigger copy on write on surface2. The new backing store should not
493     // be recycling a texture that is held by an existing image.
494     canvas2->clear(5);
495     sk_sp<SkImage> image4(surface2->makeImageSnapshot());
496     REPORTER_ASSERT(reporter, as_IB(image4)->getTexture() != as_IB(image3)->getTexture());
497     // The following assertion checks crbug.com/263329
498     REPORTER_ASSERT(reporter, as_IB(image4)->getTexture() != as_IB(image2)->getTexture());
499     REPORTER_ASSERT(reporter, as_IB(image4)->getTexture() != as_IB(image1)->getTexture());
500     REPORTER_ASSERT(reporter, as_IB(image3)->getTexture() != as_IB(image2)->getTexture());
501     REPORTER_ASSERT(reporter, as_IB(image3)->getTexture() != as_IB(image1)->getTexture());
502     REPORTER_ASSERT(reporter, as_IB(image2)->getTexture() != as_IB(image1)->getTexture());
503 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCRBug263329_Gpu,reporter,ctxInfo)504 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceCRBug263329_Gpu, reporter, ctxInfo) {
505     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
506         auto surface1(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
507         auto surface2(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
508         test_crbug263329(reporter, surface1.get(), surface2.get());
509     }
510 }
511 
DEF_TEST(SurfaceGetTexture,reporter)512 DEF_TEST(SurfaceGetTexture, reporter) {
513     auto surface(create_surface());
514     sk_sp<SkImage> image(surface->makeImageSnapshot());
515     REPORTER_ASSERT(reporter, !as_IB(image)->isTextureBacked());
516     surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);
517     REPORTER_ASSERT(reporter, !as_IB(image)->isTextureBacked());
518 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacepeekTexture_Gpu,reporter,ctxInfo)519 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacepeekTexture_Gpu, reporter, ctxInfo) {
520     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
521         auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
522         sk_sp<SkImage> image(surface->makeImageSnapshot());
523 
524         REPORTER_ASSERT(reporter, as_IB(image)->isTextureBacked());
525         GrBackendTexture backendTex = image->getBackendTexture(false);
526         REPORTER_ASSERT(reporter, backendTex.isValid());
527         surface->notifyContentWillChange(SkSurface::kDiscard_ContentChangeMode);
528         REPORTER_ASSERT(reporter, as_IB(image)->isTextureBacked());
529         GrBackendTexture backendTex2 = image->getBackendTexture(false);
530         REPORTER_ASSERT(reporter, GrBackendTexture::TestingOnly_Equals(backendTex, backendTex2));
531     }
532 }
533 
is_budgeted(const sk_sp<SkSurface> & surf)534 static SkBudgeted is_budgeted(const sk_sp<SkSurface>& surf) {
535     SkSurface_Gpu* gsurf = (SkSurface_Gpu*)surf.get();
536 
537     GrRenderTargetProxy* proxy = gsurf->getDevice()->accessRenderTargetContext()
538                                                                         ->asRenderTargetProxy();
539     return proxy->isBudgeted();
540 }
541 
is_budgeted(SkImage * image)542 static SkBudgeted is_budgeted(SkImage* image) {
543     return ((SkImage_Gpu*)image)->peekProxy()->isBudgeted();
544 }
545 
is_budgeted(const sk_sp<SkImage> image)546 static SkBudgeted is_budgeted(const sk_sp<SkImage> image) {
547     return is_budgeted(image.get());
548 }
549 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBudget,reporter,ctxInfo)550 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceBudget, reporter, ctxInfo) {
551     SkImageInfo info = SkImageInfo::MakeN32Premul(8,8);
552     for (auto budgeted : { SkBudgeted::kNo, SkBudgeted::kYes }) {
553         auto surface(SkSurface::MakeRenderTarget(ctxInfo.grContext(), budgeted, info));
554         SkASSERT(surface);
555         REPORTER_ASSERT(reporter, budgeted == is_budgeted(surface));
556 
557         sk_sp<SkImage> image(surface->makeImageSnapshot());
558 
559         // Initially the image shares a texture with the surface, and the
560         // the budgets should always match.
561         REPORTER_ASSERT(reporter, budgeted == is_budgeted(surface));
562         REPORTER_ASSERT(reporter, budgeted == is_budgeted(image));
563 
564         // Now trigger copy-on-write
565         surface->getCanvas()->clear(SK_ColorBLUE);
566 
567         // They don't share a texture anymore but the budgets should still match.
568         REPORTER_ASSERT(reporter, budgeted == is_budgeted(surface));
569         REPORTER_ASSERT(reporter, budgeted == is_budgeted(image));
570     }
571 }
572 
test_no_canvas1(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::ContentChangeMode mode)573 static void test_no_canvas1(skiatest::Reporter* reporter,
574                             SkSurface* surface,
575                             SkSurface::ContentChangeMode mode) {
576     // Test passes by not asserting
577     surface->notifyContentWillChange(mode);
578 }
test_no_canvas2(skiatest::Reporter * reporter,SkSurface * surface,SkSurface::ContentChangeMode mode)579 static void test_no_canvas2(skiatest::Reporter* reporter,
580                             SkSurface* surface,
581                             SkSurface::ContentChangeMode mode) {
582     // Verifies the robustness of SkSurface for handling use cases where calls
583     // are made before a canvas is created.
584     sk_sp<SkImage> image1 = surface->makeImageSnapshot();
585     sk_sp<SkImage> aur_image1(image1);
586     surface->notifyContentWillChange(mode);
587     sk_sp<SkImage> image2 = surface->makeImageSnapshot();
588     sk_sp<SkImage> aur_image2(image2);
589     REPORTER_ASSERT(reporter, image1 != image2);
590 }
DEF_TEST(SurfaceNoCanvas,reporter)591 DEF_TEST(SurfaceNoCanvas, reporter) {
592     SkSurface::ContentChangeMode modes[] =
593             { SkSurface::kDiscard_ContentChangeMode, SkSurface::kRetain_ContentChangeMode};
594     for (auto& test_func : { &test_no_canvas1, &test_no_canvas2 }) {
595         for (auto& mode : modes) {
596             test_func(reporter, create_surface().get(), mode);
597         }
598     }
599 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceNoCanvas_Gpu,reporter,ctxInfo)600 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceNoCanvas_Gpu, reporter, ctxInfo) {
601     SkSurface::ContentChangeMode modes[] =
602             { SkSurface::kDiscard_ContentChangeMode, SkSurface::kRetain_ContentChangeMode};
603     for (auto& surface_func : { &create_gpu_surface, &create_gpu_scratch_surface }) {
604         for (auto& test_func : { &test_no_canvas1, &test_no_canvas2 }) {
605             for (auto& mode : modes) {
606                 auto surface(surface_func(ctxInfo.grContext(), kPremul_SkAlphaType, nullptr));
607                 test_func(reporter, surface.get(), mode);
608             }
609         }
610     }
611 }
612 
check_rowbytes_remain_consistent(SkSurface * surface,skiatest::Reporter * reporter)613 static void check_rowbytes_remain_consistent(SkSurface* surface, skiatest::Reporter* reporter) {
614     SkPixmap surfacePM;
615     REPORTER_ASSERT(reporter, surface->peekPixels(&surfacePM));
616 
617     sk_sp<SkImage> image(surface->makeImageSnapshot());
618     SkPixmap pm;
619     REPORTER_ASSERT(reporter, image->peekPixels(&pm));
620 
621     REPORTER_ASSERT(reporter, surfacePM.rowBytes() == pm.rowBytes());
622 
623     // trigger a copy-on-write
624     surface->getCanvas()->drawPaint(SkPaint());
625     sk_sp<SkImage> image2(surface->makeImageSnapshot());
626     REPORTER_ASSERT(reporter, image->uniqueID() != image2->uniqueID());
627 
628     SkPixmap pm2;
629     REPORTER_ASSERT(reporter, image2->peekPixels(&pm2));
630     REPORTER_ASSERT(reporter, pm2.rowBytes() == pm.rowBytes());
631 }
632 
DEF_TEST(surface_rowbytes,reporter)633 DEF_TEST(surface_rowbytes, reporter) {
634     const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100);
635 
636     auto surf0(SkSurface::MakeRaster(info));
637     check_rowbytes_remain_consistent(surf0.get(), reporter);
638 
639     // specify a larger rowbytes
640     auto surf1(SkSurface::MakeRaster(info, 500, nullptr));
641     check_rowbytes_remain_consistent(surf1.get(), reporter);
642 
643     // Try some illegal rowByte values
644     auto s = SkSurface::MakeRaster(info, 396, nullptr);    // needs to be at least 400
645     REPORTER_ASSERT(reporter, nullptr == s);
646     s = SkSurface::MakeRaster(info, std::numeric_limits<size_t>::max(), nullptr);
647     REPORTER_ASSERT(reporter, nullptr == s);
648 }
649 
DEF_TEST(surface_raster_zeroinitialized,reporter)650 DEF_TEST(surface_raster_zeroinitialized, reporter) {
651     sk_sp<SkSurface> s(SkSurface::MakeRasterN32Premul(100, 100));
652     SkPixmap pixmap;
653     REPORTER_ASSERT(reporter, s->peekPixels(&pixmap));
654 
655     for (int i = 0; i < pixmap.info().width(); ++i) {
656         for (int j = 0; j < pixmap.info().height(); ++j) {
657             REPORTER_ASSERT(reporter, *pixmap.addr32(i, j) == 0);
658         }
659     }
660 }
661 
create_gpu_surface_backend_texture(GrContext * ctx,int sampleCnt,const SkColor4f & color,GrBackendTexture * outTexture)662 static sk_sp<SkSurface> create_gpu_surface_backend_texture(
663     GrContext* ctx, int sampleCnt, const SkColor4f& color, GrBackendTexture* outTexture) {
664 
665     // On Pixel and Pixel2XL's with Adreno 530 and 540s, setting width and height to 10s reliably
666     // triggers what appears to be a driver race condition where the 10x10 surface from the
667     // OverdrawSurface_gpu test is reused(?) for this surface created by the SurfacePartialDraw_gpu
668     // test.
669     //
670     // Immediately after creation of this surface, readback shows the correct initial solid color.
671     // However, sometime before content is rendered into the upper half of the surface, the driver
672     // presumably cleans up the OverdrawSurface_gpu's memory which corrupts this color buffer. The
673     // top half of the surface is fine after the partially-covering rectangle is drawn, but the
674     // untouched bottom half contains random pixel values that trigger asserts in the
675     // SurfacePartialDraw_gpu test for no longer matching the initial color. Running the
676     // SurfacePartialDraw_gpu test without the OverdrawSurface_gpu test completes successfully.
677     //
678     // Requesting a much larger backend texture size seems to prevent it from reusing the same
679     // memory and avoids the issue.
680 #if defined(SK_BUILD_FOR_SKQP)
681     const int kWidth = 10;
682     const int kHeight = 10;
683 #else
684     const int kWidth = 100;
685     const int kHeight = 100;
686 #endif
687 
688     SkImageInfo ii = SkImageInfo::Make(kWidth, kHeight, SkColorType::kRGBA_8888_SkColorType,
689                                        kPremul_SkAlphaType);
690 
691     if (!create_backend_texture(ctx, outTexture, ii, color, GrMipMapped::kNo,
692                                 GrRenderable::kYes)) {
693         return nullptr;
694     }
695 
696     sk_sp<SkSurface> surface = SkSurface::MakeFromBackendTexture(ctx, *outTexture,
697                                                                  kTopLeft_GrSurfaceOrigin, sampleCnt,
698                                                                  kRGBA_8888_SkColorType,
699                                                                  nullptr, nullptr);
700     if (!surface) {
701         delete_backend_texture(ctx, *outTexture);
702         return nullptr;
703     }
704     return surface;
705 }
706 
create_gpu_surface_backend_texture_as_render_target(GrContext * ctx,int sampleCnt,const SkColor4f & color,GrBackendTexture * outTexture)707 static sk_sp<SkSurface> create_gpu_surface_backend_texture_as_render_target(
708     GrContext* ctx, int sampleCnt, const SkColor4f& color, GrBackendTexture* outTexture) {
709 
710     const int kWidth = 10;
711     const int kHeight = 10;
712 
713     SkImageInfo ii = SkImageInfo::Make(kWidth, kHeight, SkColorType::kRGBA_8888_SkColorType,
714                                        kPremul_SkAlphaType);
715 
716     if (!create_backend_texture(ctx, outTexture, ii, color, GrMipMapped::kNo,
717                                 GrRenderable::kYes)) {
718         return nullptr;
719     }
720 
721     sk_sp<SkSurface> surface = SkSurface::MakeFromBackendTextureAsRenderTarget(
722             ctx, *outTexture, kTopLeft_GrSurfaceOrigin, sampleCnt, kRGBA_8888_SkColorType,
723             nullptr, nullptr);
724 
725     if (!surface) {
726         delete_backend_texture(ctx, *outTexture);
727         return nullptr;
728     }
729     return surface;
730 }
731 
test_surface_clear(skiatest::Reporter * reporter,sk_sp<SkSurface> surface,std::function<sk_sp<GrSurfaceContext> (SkSurface *)> grSurfaceGetter,uint32_t expectedValue)732 static void test_surface_clear(skiatest::Reporter* reporter, sk_sp<SkSurface> surface,
733                                std::function<sk_sp<GrSurfaceContext>(SkSurface*)> grSurfaceGetter,
734                                uint32_t expectedValue) {
735     if (!surface) {
736         ERRORF(reporter, "Could not create GPU SkSurface.");
737         return;
738     }
739     int w = surface->width();
740     int h = surface->height();
741 
742     SkImageInfo ii = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
743 
744     SkAutoPixmapStorage readback;
745     readback.alloc(ii);
746 
747     sk_sp<GrSurfaceContext> grSurfaceContext(grSurfaceGetter(surface.get()));
748     if (!grSurfaceContext) {
749         ERRORF(reporter, "Could access render target of GPU SkSurface.");
750         return;
751     }
752     surface.reset();
753 
754     readback.erase(~expectedValue);
755     grSurfaceContext->readPixels(readback.info(), readback.writable_addr(), readback.rowBytes(),
756                                  {0, 0});
757     for (int y = 0; y < h; ++y) {
758         for (int x = 0; x < w; ++x) {
759             uint32_t pixel = readback.addr32()[y * w + x];
760             if (pixel != expectedValue) {
761                 SkString msg;
762                 if (expectedValue) {
763                     msg = "SkSurface should have left render target unmodified";
764                 } else {
765                     msg = "SkSurface should have cleared the render target";
766                 }
767                 ERRORF(reporter,
768                        "%s but read 0x%08x (instead of 0x%08x) at %x,%d", msg.c_str(), pixel,
769                        expectedValue, x, y);
770                 return;
771             }
772         }
773     }
774 }
775 
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceClear_Gpu,reporter,ctxInfo)776 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceClear_Gpu, reporter, ctxInfo) {
777     GrContext* context = ctxInfo.grContext();
778 
779     std::function<sk_sp<GrSurfaceContext>(SkSurface*)> grSurfaceContextGetters[] = {
780         [] (SkSurface* s){
781             return sk_ref_sp(s->getCanvas()->internal_private_accessTopLayerRenderTargetContext());
782         },
783         [context] (SkSurface* s){
784             sk_sp<SkImage> i(s->makeImageSnapshot());
785             SkImage_Gpu* gpuImage = (SkImage_Gpu *) as_IB(i);
786             sk_sp<GrTextureProxy> proxy = gpuImage->asTextureProxyRef(context);
787             return context->priv().makeWrappedSurfaceContext(
788                     std::move(proxy), SkColorTypeToGrColorType(i->colorType()), kPremul_SkAlphaType,
789                     gpuImage->refColorSpace());
790         }
791     };
792 
793     for (auto grSurfaceGetter : grSurfaceContextGetters) {
794         // Test that non-wrapped RTs are created clear.
795         for (auto& surface_func : {&create_gpu_surface, &create_gpu_scratch_surface}) {
796             auto surface = surface_func(context, kPremul_SkAlphaType, nullptr);
797             test_surface_clear(reporter, surface, grSurfaceGetter, 0x0);
798         }
799         // Wrapped RTs are *not* supposed to clear (to allow client to partially update a surface).
800         const SkColor4f kOrigColor { .67f, .67f, .67f, 1 };
801         for (auto& surfaceFunc : {&create_gpu_surface_backend_texture,
802                                   &create_gpu_surface_backend_texture_as_render_target}) {
803             GrBackendTexture backendTex;
804             auto surface = surfaceFunc(context, 1, kOrigColor, &backendTex);
805             test_surface_clear(reporter, surface, grSurfaceGetter, kOrigColor.toSkColor());
806             surface.reset();
807             context->deleteBackendTexture(backendTex);
808         }
809     }
810 }
811 
test_surface_draw_partially(skiatest::Reporter * reporter,sk_sp<SkSurface> surface,uint32_t origColor)812 static void test_surface_draw_partially(
813     skiatest::Reporter* reporter, sk_sp<SkSurface> surface, uint32_t origColor) {
814     const int kW = surface->width();
815     const int kH = surface->height();
816     SkPaint paint;
817     const SkColor kRectColor = ~origColor | 0xFF000000;
818     paint.setColor(kRectColor);
819     surface->getCanvas()->drawRect(SkRect::MakeIWH(kW, kH/2), paint);
820 
821     // Read back RGBA to avoid format conversions that may not be supported on all platforms.
822     SkImageInfo readInfo = SkImageInfo::Make(kW, kH, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
823 
824     SkAutoPixmapStorage readback;
825     readback.alloc(readInfo);
826 
827     readback.erase(~origColor);
828     SkAssertResult(surface->readPixels(readback.info(), readback.writable_addr(),
829                                        readback.rowBytes(), 0, 0));
830     bool stop = false;
831 
832     SkPMColor origColorPM = SkPackARGB_as_RGBA((origColor >> 24 & 0xFF),
833                                                (origColor >> 0 & 0xFF),
834                                                (origColor >> 8 & 0xFF),
835                                                (origColor >> 16 & 0xFF));
836     SkPMColor rectColorPM = SkPackARGB_as_RGBA((kRectColor >> 24 & 0xFF),
837                                                (kRectColor >> 16 & 0xFF),
838                                                (kRectColor >> 8 & 0xFF),
839                                                (kRectColor >> 0 & 0xFF));
840 
841     for (int y = 0; y < kH/2 && !stop; ++y) {
842        for (int x = 0; x < kW && !stop; ++x) {
843             REPORTER_ASSERT(reporter, rectColorPM == readback.addr32()[x + y * kW]);
844             if (rectColorPM != readback.addr32()[x + y * kW]) {
845                 SkDebugf("--- got [%x] expected [%x], x = %d, y = %d\n",
846                          readback.addr32()[x + y * kW], rectColorPM, x, y);
847                 stop = true;
848             }
849         }
850     }
851     stop = false;
852     for (int y = kH/2; y < kH && !stop; ++y) {
853         for (int x = 0; x < kW && !stop; ++x) {
854             REPORTER_ASSERT(reporter, origColorPM == readback.addr32()[x + y * kW]);
855             if (origColorPM != readback.addr32()[x + y * kW]) {
856                 SkDebugf("--- got [%x] expected [%x], x = %d, y = %d\n",
857                          readback.addr32()[x + y * kW], origColorPM, x, y);
858                 stop = true;
859             }
860         }
861     }
862 }
863 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacePartialDraw_Gpu,reporter,ctxInfo)864 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfacePartialDraw_Gpu, reporter, ctxInfo) {
865     GrContext* context = ctxInfo.grContext();
866 
867     static const SkColor4f kOrigColor { 0.667f, 0.733f, 0.8f, 1 };
868 
869     for (auto& surfaceFunc : {&create_gpu_surface_backend_texture,
870                               &create_gpu_surface_backend_texture_as_render_target}) {
871         // Validate that we can draw to the canvas and that the original texture color is
872         // preserved in pixels that aren't rendered to via the surface.
873         // This works only for non-multisampled case.
874         GrBackendTexture backendTex;
875         auto surface = surfaceFunc(context, 1, kOrigColor, &backendTex);
876         if (surface) {
877             test_surface_draw_partially(reporter, surface, kOrigColor.toSkColor());
878             surface.reset();
879             context->deleteBackendTexture(backendTex);
880         }
881     }
882 }
883 
884 struct ReleaseChecker {
ReleaseCheckerReleaseChecker885     ReleaseChecker() : fReleaseCount(0) {}
886     int fReleaseCount;
ReleaseReleaseChecker887     static void Release(void* self) {
888         static_cast<ReleaseChecker*>(self)->fReleaseCount++;
889     }
890 };
891 
892 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWrappedWithRelease_Gpu,reporter,ctxInfo)893 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceWrappedWithRelease_Gpu, reporter, ctxInfo) {
894     const int kWidth = 10;
895     const int kHeight = 10;
896 
897     GrContext* ctx = ctxInfo.grContext();
898     GrGpu* gpu = ctx->priv().getGpu();
899 
900     for (bool useTexture : {false, true}) {
901         GrBackendTexture backendTex;
902         GrBackendRenderTarget backendRT;
903         sk_sp<SkSurface> surface;
904 
905         ReleaseChecker releaseChecker;
906         GrSurfaceOrigin texOrigin = kBottomLeft_GrSurfaceOrigin;
907 
908         if (useTexture) {
909             SkImageInfo ii = SkImageInfo::Make(kWidth, kHeight, SkColorType::kRGBA_8888_SkColorType,
910                                                kPremul_SkAlphaType);
911             if (!create_backend_texture(ctx, &backendTex, ii, SkColors::kRed, GrMipMapped::kNo,
912                                         GrRenderable::kYes)) {
913                 continue;
914             }
915 
916             surface = SkSurface::MakeFromBackendTexture(ctx, backendTex, texOrigin, 1,
917                                                         kRGBA_8888_SkColorType,
918                                                         nullptr, nullptr,
919                                                         ReleaseChecker::Release,
920                                                         &releaseChecker);
921         } else {
922             backendRT = gpu->createTestingOnlyBackendRenderTarget(kWidth, kHeight,
923                                                                   GrColorType::kRGBA_8888);
924             if (!backendRT.isValid()) {
925                 continue;
926             }
927             surface = SkSurface::MakeFromBackendRenderTarget(ctx, backendRT, texOrigin,
928                                                              kRGBA_8888_SkColorType,
929                                                              nullptr, nullptr,
930                                                              ReleaseChecker::Release,
931                                                              &releaseChecker);
932         }
933         if (!surface) {
934             ERRORF(reporter, "Failed to create surface");
935             continue;
936         }
937 
938         surface->getCanvas()->clear(SK_ColorRED);
939         surface->flush();
940         gpu->testingOnly_flushGpuAndSync();
941 
942         // Now exercise the release proc
943         REPORTER_ASSERT(reporter, 0 == releaseChecker.fReleaseCount);
944         surface.reset(nullptr); // force a release of the surface
945         REPORTER_ASSERT(reporter, 1 == releaseChecker.fReleaseCount);
946 
947         if (useTexture) {
948             delete_backend_texture(ctx, backendTex);
949         } else {
950             gpu->deleteTestingOnlyBackendRenderTarget(backendRT);
951         }
952     }
953 }
954 
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceAttachStencil_Gpu,reporter,ctxInfo)955 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SurfaceAttachStencil_Gpu, reporter, ctxInfo) {
956     GrContext* context = ctxInfo.grContext();
957     const GrCaps* caps = context->priv().caps();
958 
959     if (caps->avoidStencilBuffers()) {
960         return;
961     }
962 
963     static const SkColor4f kOrigColor { 0.667f, 0.733f, 0.8f, 1 };
964 
965     auto resourceProvider = context->priv().resourceProvider();
966 
967     for (auto& surfaceFunc : {&create_gpu_surface_backend_texture,
968                               &create_gpu_surface_backend_texture_as_render_target}) {
969         for (int sampleCnt : {1, 4, 8}) {
970             GrBackendTexture backendTex;
971             auto surface = surfaceFunc(context, sampleCnt, kOrigColor, &backendTex);
972 
973             if (!surface && sampleCnt > 1) {
974                 // Certain platforms don't support MSAA, skip these.
975                 continue;
976             }
977 
978             // Validate that we can attach a stencil buffer to an SkSurface created by either of
979             // our surface functions.
980             GrRenderTarget* rt = surface->getCanvas()
981                 ->internal_private_accessTopLayerRenderTargetContext()->accessRenderTarget();
982             REPORTER_ASSERT(reporter, resourceProvider->attachStencilAttachment(rt, sampleCnt));
983             context->deleteBackendTexture(backendTex);
984         }
985     }
986 }
987 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReplaceSurfaceBackendTexture,reporter,ctxInfo)988 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReplaceSurfaceBackendTexture, reporter, ctxInfo) {
989     GrContext* context = ctxInfo.grContext();
990 
991     for (int sampleCnt : {1, 2}) {
992         GrBackendTexture backendTexture1;
993         auto ii = SkImageInfo::Make(10, 10, kRGBA_8888_SkColorType, kPremul_SkAlphaType, nullptr);
994         if (!create_backend_texture(context, &backendTexture1, ii, SkColors::kTransparent,
995                                     GrMipMapped::kNo, GrRenderable::kYes)) {
996             continue;
997         }
998         SkScopeExit delete1(
999                 [context, &backendTexture1] { delete_backend_texture(context, backendTexture1); });
1000         GrBackendTexture backendTexture2;
1001         if (!create_backend_texture(context, &backendTexture2, ii, SkColors::kTransparent,
1002                                     GrMipMapped::kNo, GrRenderable::kYes)) {
1003             ERRORF(reporter, "Expected to be able to make second texture");
1004             continue;
1005         }
1006         SkScopeExit delete2(
1007                 [context, &backendTexture2] { delete_backend_texture(context, backendTexture2); });
1008         auto ii2 = ii.makeWH(8, 8);
1009         GrBackendTexture backendTexture3;
1010         if (!create_backend_texture(context, &backendTexture3, ii2, SkColors::kTransparent,
1011                                     GrMipMapped::kNo, GrRenderable::kYes)) {
1012             ERRORF(reporter, "Couldn't create different sized texture.");
1013             continue;
1014         }
1015         SkScopeExit delete3(
1016                 [context, &backendTexture3] { delete_backend_texture(context, backendTexture3); });
1017 
1018         auto surf = SkSurface::MakeFromBackendTexture(
1019                 context, backendTexture1, kTopLeft_GrSurfaceOrigin, sampleCnt,
1020                 kRGBA_8888_SkColorType, ii.refColorSpace(), nullptr);
1021         if (!surf) {
1022             continue;
1023         }
1024         surf->getCanvas()->clear(SK_ColorBLUE);
1025         // Change matrix, layer, and clip state before swapping out the backing texture.
1026         surf->getCanvas()->translate(5, 5);
1027         surf->getCanvas()->saveLayer(nullptr, nullptr);
1028         surf->getCanvas()->clipRect(SkRect::MakeXYWH(0, 0, 1, 1));
1029         // switch origin while we're at it.
1030         bool replaced = surf->replaceBackendTexture(backendTexture2, kBottomLeft_GrSurfaceOrigin);
1031         REPORTER_ASSERT(reporter, replaced);
1032         SkPaint paint;
1033         paint.setColor(SK_ColorRED);
1034         surf->getCanvas()->drawRect(SkRect::MakeWH(5, 5), paint);
1035         surf->getCanvas()->restore();
1036 
1037         // Check that the replacement texture got the right color values.
1038         SkAutoPixmapStorage pm;
1039         pm.alloc(ii);
1040         bool bad = !surf->readPixels(pm, 0, 0);
1041         REPORTER_ASSERT(reporter, !bad, "Could not read surface.");
1042         for (int y = 0; y < ii.height() && !bad; ++y) {
1043             for (int x = 0; x < ii.width() && !bad; ++x) {
1044                 auto expected = (x == 5 && y == 5) ? 0xFF0000FF : 0xFFFF0000;
1045                 auto found = *pm.addr32(x, y);
1046                 if (found != expected) {
1047                     bad = true;
1048                     ERRORF(reporter, "Expected color 0x%08x, found color 0x%08x at %d, %d.",
1049                            expected, found, x, y);
1050                 }
1051             }
1052         }
1053         // The original texture should still be all blue.
1054         surf = SkSurface::MakeFromBackendTexture(
1055                 context, backendTexture1, kBottomLeft_GrSurfaceOrigin, sampleCnt,
1056                 kRGBA_8888_SkColorType, ii.refColorSpace(), nullptr);
1057         if (!surf) {
1058             ERRORF(reporter, "Could not create second surface.");
1059             continue;
1060         }
1061         bad = !surf->readPixels(pm, 0, 0);
1062         REPORTER_ASSERT(reporter, !bad, "Could not read second surface.");
1063         for (int y = 0; y < ii.height() && !bad; ++y) {
1064             for (int x = 0; x < ii.width() && !bad; ++x) {
1065                 auto expected = 0xFFFF0000;
1066                 auto found = *pm.addr32(x, y);
1067                 if (found != expected) {
1068                     bad = true;
1069                     ERRORF(reporter, "Expected color 0x%08x, found color 0x%08x at %d, %d.",
1070                            expected, found, x, y);
1071                 }
1072             }
1073         }
1074 
1075         // Can't replace with the same texture
1076         REPORTER_ASSERT(reporter,
1077                         !surf->replaceBackendTexture(backendTexture1, kTopLeft_GrSurfaceOrigin));
1078         // Can't replace with invalid texture
1079         REPORTER_ASSERT(reporter, !surf->replaceBackendTexture({}, kTopLeft_GrSurfaceOrigin));
1080         // Can't replace with different size texture.
1081         REPORTER_ASSERT(reporter,
1082                         !surf->replaceBackendTexture(backendTexture3, kTopLeft_GrSurfaceOrigin));
1083         // Can't replace texture of non-wrapped SkSurface.
1084         surf = SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, ii, sampleCnt, nullptr);
1085         REPORTER_ASSERT(reporter, surf);
1086         if (surf) {
1087             REPORTER_ASSERT(reporter, !surf->replaceBackendTexture(backendTexture1,
1088                                                                    kTopLeft_GrSurfaceOrigin));
1089         }
1090     }
1091 }
1092 
test_overdraw_surface(skiatest::Reporter * r,SkSurface * surface)1093 static void test_overdraw_surface(skiatest::Reporter* r, SkSurface* surface) {
1094     SkOverdrawCanvas canvas(surface->getCanvas());
1095     canvas.drawPaint(SkPaint());
1096     sk_sp<SkImage> image = surface->makeImageSnapshot();
1097 
1098     SkBitmap bitmap;
1099     image->asLegacyBitmap(&bitmap);
1100     for (int y = 0; y < 10; y++) {
1101         for (int x = 0; x < 10; x++) {
1102             REPORTER_ASSERT(r, 1 == SkGetPackedA32(*bitmap.getAddr32(x, y)));
1103         }
1104     }
1105 }
1106 
DEF_TEST(OverdrawSurface_Raster,r)1107 DEF_TEST(OverdrawSurface_Raster, r) {
1108     sk_sp<SkSurface> surface = create_surface();
1109     test_overdraw_surface(r, surface.get());
1110 }
1111 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(OverdrawSurface_Gpu,r,ctxInfo)1112 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(OverdrawSurface_Gpu, r, ctxInfo) {
1113     GrContext* context = ctxInfo.grContext();
1114     sk_sp<SkSurface> surface = create_gpu_surface(context);
1115     test_overdraw_surface(r, surface.get());
1116 }
1117 
DEF_TEST(Surface_null,r)1118 DEF_TEST(Surface_null, r) {
1119     REPORTER_ASSERT(r, SkSurface::MakeNull(0, 0) == nullptr);
1120 
1121     const int w = 37;
1122     const int h = 1000;
1123     auto surf = SkSurface::MakeNull(w, h);
1124     auto canvas = surf->getCanvas();
1125 
1126     canvas->drawPaint(SkPaint());   // should not crash, but don't expect anything to draw
1127     REPORTER_ASSERT(r, surf->makeImageSnapshot() == nullptr);
1128 }
1129 
1130 // assert: if a given imageinfo is valid for a surface, then it must be valid for an image
1131 //         (so the snapshot can succeed)
DEF_TEST(surface_image_unity,reporter)1132 DEF_TEST(surface_image_unity, reporter) {
1133     auto do_test = [reporter](const SkImageInfo& info) {
1134         size_t rowBytes = info.minRowBytes();
1135         auto surf = SkSurface::MakeRaster(info, rowBytes, nullptr);
1136         if (surf) {
1137             auto img = surf->makeImageSnapshot();
1138             if (!img && false) {    // change to true to document the differences
1139                 SkDebugf("image failed: [%08X %08X] %14s %s\n",
1140                          info.width(),
1141                          info.height(),
1142                          ToolUtils::colortype_name(info.colorType()),
1143                          ToolUtils::alphatype_name(info.alphaType()));
1144                 return;
1145             }
1146             REPORTER_ASSERT(reporter, img != nullptr);
1147 
1148             char dummyPixel = 0;    // just need a valid address (not a valid size)
1149             SkPixmap pmap = { info, &dummyPixel, rowBytes };
1150             img = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
1151             REPORTER_ASSERT(reporter, img != nullptr);
1152         }
1153     };
1154 
1155     const int32_t sizes[] = { -1, 0, 1, 1 << 18 };
1156     for (int cti = 0; cti <= kLastEnum_SkColorType; ++cti) {
1157         SkColorType ct = static_cast<SkColorType>(cti);
1158         for (int ati = 0; ati <= kLastEnum_SkAlphaType; ++ati) {
1159             SkAlphaType at = static_cast<SkAlphaType>(ati);
1160             for (int32_t size : sizes) {
1161                 do_test(SkImageInfo::Make(1, size, ct, at));
1162                 do_test(SkImageInfo::Make(size, 1, ct, at));
1163             }
1164         }
1165     }
1166 }
1167