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