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