Improve use of NeverDestroyed
[WebKit-https.git] / Source / WebCore / platform / graphics / cairo / ImageBufferCairo.cpp
1 /*
2  * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
3  * Copyright (C) 2007 Holger Hans Peter Freyther <zecke@selfish.org>
4  * Copyright (C) 2008, 2009 Dirk Schulze <krit@webkit.org>
5  * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
20  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
24  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "config.h"
30 #include "ImageBuffer.h"
31
32 #if USE(CAIRO)
33
34 #include "BitmapImage.h"
35 #include "CairoUtilities.h"
36 #include "Color.h"
37 #include "GraphicsContext.h"
38 #include "MIMETypeRegistry.h"
39 #include "NotImplemented.h"
40 #include "Pattern.h"
41 #include "PlatformContextCairo.h"
42 #include "RefPtrCairo.h"
43 #include <cairo.h>
44 #include <runtime/JSCInlines.h>
45 #include <runtime/TypedArrayInlines.h>
46 #include <wtf/Vector.h>
47 #include <wtf/text/Base64.h>
48 #include <wtf/text/WTFString.h>
49
50 #if ENABLE(ACCELERATED_2D_CANVAS)
51 #include "GLContext.h"
52 #include "TextureMapperGL.h"
53
54 #if USE(EGL) && USE(LIBEPOXY)
55 #include <epoxy/egl.h>
56 #endif
57 #include <cairo-gl.h>
58
59 #if USE(OPENGL_ES_2)
60 #include <GLES2/gl2.h>
61 #else
62 #include "OpenGLShims.h"
63 #endif
64
65 #if USE(COORDINATED_GRAPHICS_THREADED)
66 #include "TextureMapperPlatformLayerBuffer.h"
67 #include "TextureMapperPlatformLayerProxy.h"
68 #endif
69 #endif
70
71 using namespace std;
72
73 namespace WebCore {
74
75 ImageBufferData::ImageBufferData(const IntSize& size, RenderingMode renderingMode)
76     : m_platformContext(0)
77     , m_size(size)
78     , m_renderingMode(renderingMode)
79 #if ENABLE(ACCELERATED_2D_CANVAS)
80 #if USE(COORDINATED_GRAPHICS_THREADED)
81     , m_compositorTexture(0)
82 #endif
83     , m_texture(0)
84 #endif
85 {
86 #if ENABLE(ACCELERATED_2D_CANVAS) && USE(COORDINATED_GRAPHICS_THREADED)
87     if (m_renderingMode == RenderingMode::Accelerated)
88         m_platformLayerProxy = adoptRef(new TextureMapperPlatformLayerProxy);
89 #endif
90 }
91
92 ImageBufferData::~ImageBufferData()
93 {
94     if (m_renderingMode != Accelerated)
95         return;
96
97 #if ENABLE(ACCELERATED_2D_CANVAS)
98     GLContext* previousActiveContext = GLContext::current();
99     PlatformDisplay::sharedDisplayForCompositing().sharingGLContext()->makeContextCurrent();
100
101     if (m_texture)
102         glDeleteTextures(1, &m_texture);
103
104 #if USE(COORDINATED_GRAPHICS_THREADED)
105     if (m_compositorTexture)
106         glDeleteTextures(1, &m_compositorTexture);
107 #endif
108
109     if (previousActiveContext)
110         previousActiveContext->makeContextCurrent();
111 #endif
112 }
113
114 #if ENABLE(ACCELERATED_2D_CANVAS)
115 #if USE(COORDINATED_GRAPHICS_THREADED)
116 void ImageBufferData::createCompositorBuffer()
117 {
118     auto* context = PlatformDisplay::sharedDisplayForCompositing().sharingGLContext();
119     context->makeContextCurrent();
120
121     glGenTextures(1, &m_compositorTexture);
122     glBindTexture(GL_TEXTURE_2D, m_compositorTexture);
123     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
124     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
125     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
126     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
127     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
128     glTexImage2D(GL_TEXTURE_2D, 0 , GL_RGBA, m_size.width(), m_size.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
129
130     m_compositorSurface = adoptRef(cairo_gl_surface_create_for_texture(context->cairoDevice(), CAIRO_CONTENT_COLOR_ALPHA, m_compositorTexture, m_size.width(), m_size.height()));
131     m_compositorCr = adoptRef(cairo_create(m_compositorSurface.get()));
132     cairo_set_antialias(m_compositorCr.get(), CAIRO_ANTIALIAS_NONE);
133 }
134
135 void ImageBufferData::swapBuffersIfNeeded()
136 {
137     GLContext* previousActiveContext = GLContext::current();
138
139     if (!m_compositorTexture) {
140         createCompositorBuffer();
141         LockHolder holder(m_platformLayerProxy->lock());
142         m_platformLayerProxy->pushNextBuffer(std::make_unique<TextureMapperPlatformLayerBuffer>(m_compositorTexture, m_size, TextureMapperGL::ShouldBlend, GL_RGBA));
143     }
144
145     // It would be great if we could just swap the buffers here as we do with webgl, but that breaks the cases
146     // where one frame uses the content already rendered in the previous frame. So we just copy the content
147     // into the compositor buffer.
148     cairo_set_source_surface(m_compositorCr.get(), m_surface.get(), 0, 0);
149     cairo_set_operator(m_compositorCr.get(), CAIRO_OPERATOR_SOURCE);
150     cairo_paint(m_compositorCr.get());
151
152     if (previousActiveContext)
153         previousActiveContext->makeContextCurrent();
154 }
155 #endif
156
157 void clearSurface(cairo_surface_t* surface)
158 {
159     if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS)
160         return;
161
162     RefPtr<cairo_t> cr = adoptRef(cairo_create(surface));
163     cairo_set_operator(cr.get(), CAIRO_OPERATOR_CLEAR);
164     cairo_paint(cr.get());
165 }
166
167 void ImageBufferData::createCairoGLSurface()
168 {
169     auto* context = PlatformDisplay::sharedDisplayForCompositing().sharingGLContext();
170     context->makeContextCurrent();
171
172     // We must generate the texture ourselves, because there is no Cairo API for extracting it
173     // from a pre-existing surface.
174     glGenTextures(1, &m_texture);
175     glBindTexture(GL_TEXTURE_2D, m_texture);
176     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
177     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
178     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
179     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
180
181     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
182
183     glTexImage2D(GL_TEXTURE_2D, 0 /* level */, GL_RGBA, m_size.width(), m_size.height(), 0 /* border */, GL_RGBA, GL_UNSIGNED_BYTE, 0);
184
185     cairo_device_t* device = context->cairoDevice();
186
187     // Thread-awareness is a huge performance hit on non-Intel drivers.
188     cairo_gl_device_set_thread_aware(device, FALSE);
189
190     m_surface = adoptRef(cairo_gl_surface_create_for_texture(device, CAIRO_CONTENT_COLOR_ALPHA, m_texture, m_size.width(), m_size.height()));
191     clearSurface(m_surface.get());
192 }
193 #endif
194
195 ImageBuffer::ImageBuffer(const FloatSize& size, float resolutionScale, ColorSpace, RenderingMode renderingMode, bool& success)
196     : m_data(IntSize(size), renderingMode)
197     , m_logicalSize(size)
198     , m_resolutionScale(resolutionScale)
199 {
200     success = false;  // Make early return mean error.
201
202     float scaledWidth = ceilf(m_resolutionScale * size.width());
203     float scaledHeight = ceilf(m_resolutionScale * size.height());
204
205     // FIXME: Should we automatically use a lower resolution?
206     if (!FloatSize(scaledWidth, scaledHeight).isExpressibleAsIntSize())
207         return;
208
209     m_size = IntSize(scaledWidth, scaledHeight);
210     m_data.m_size = m_size;
211
212     if (m_size.isEmpty())
213         return;
214
215 #if ENABLE(ACCELERATED_2D_CANVAS)
216     if (m_data.m_renderingMode == Accelerated) {
217         m_data.createCairoGLSurface();
218         if (!m_data.m_surface || cairo_surface_status(m_data.m_surface.get()) != CAIRO_STATUS_SUCCESS)
219             m_data.m_renderingMode = Unaccelerated; // If allocation fails, fall back to non-accelerated path.
220     }
221     if (m_data.m_renderingMode == Unaccelerated)
222 #else
223     ASSERT(m_data.m_renderingMode != Accelerated);
224 #endif
225     {
226         static cairo_user_data_key_t s_surfaceDataKey;
227
228         int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, m_size.width());
229         auto* surfaceData = fastZeroedMalloc(m_size.height() * stride);
230
231         m_data.m_surface = adoptRef(cairo_image_surface_create_for_data(static_cast<unsigned char*>(surfaceData), CAIRO_FORMAT_ARGB32, m_size.width(), m_size.height(), stride));
232         cairo_surface_set_user_data(m_data.m_surface.get(), &s_surfaceDataKey, surfaceData, [](void* data) { fastFree(data); });
233     }
234
235     if (cairo_surface_status(m_data.m_surface.get()) != CAIRO_STATUS_SUCCESS)
236         return;  // create will notice we didn't set m_initialized and fail.
237
238     cairoSurfaceSetDeviceScale(m_data.m_surface.get(), m_resolutionScale, m_resolutionScale);
239
240     RefPtr<cairo_t> cr = adoptRef(cairo_create(m_data.m_surface.get()));
241     m_data.m_platformContext.setCr(cr.get());
242     m_data.m_context = std::make_unique<GraphicsContext>(&m_data.m_platformContext);
243     success = true;
244 }
245
246 ImageBuffer::~ImageBuffer()
247 {
248 }
249
250 std::unique_ptr<ImageBuffer> ImageBuffer::createCompatibleBuffer(const FloatSize& size, const GraphicsContext& context)
251 {
252     return createCompatibleBuffer(size, ColorSpaceSRGB, context);
253 }
254
255 GraphicsContext& ImageBuffer::context() const
256 {
257     return *m_data.m_context;
258 }
259
260 RefPtr<Image> ImageBuffer::sinkIntoImage(std::unique_ptr<ImageBuffer> imageBuffer, ScaleBehavior scaleBehavior)
261 {
262     return imageBuffer->copyImage(DontCopyBackingStore, scaleBehavior);
263 }
264
265 RefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior) const
266 {
267     // copyCairoImageSurface inherits surface's device scale factor.
268     if (copyBehavior == CopyBackingStore)
269         return BitmapImage::create(copyCairoImageSurface(m_data.m_surface.get()));
270
271     // BitmapImage will release the passed in surface on destruction
272     return BitmapImage::create(RefPtr<cairo_surface_t>(m_data.m_surface));
273 }
274
275 BackingStoreCopy ImageBuffer::fastCopyImageMode()
276 {
277     return DontCopyBackingStore;
278 }
279
280 void ImageBuffer::drawConsuming(std::unique_ptr<ImageBuffer> imageBuffer, GraphicsContext& destContext, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op, BlendMode blendMode)
281 {
282     imageBuffer->draw(destContext, destRect, srcRect, op, blendMode);
283 }
284
285 void ImageBuffer::draw(GraphicsContext& destinationContext, const FloatRect& destRect, const FloatRect& srcRect,
286     CompositeOperator op, BlendMode blendMode)
287 {
288     BackingStoreCopy copyMode = &destinationContext == &context() ? CopyBackingStore : DontCopyBackingStore;
289     RefPtr<Image> image = copyImage(copyMode);
290     destinationContext.drawImage(*image, destRect, srcRect, ImagePaintingOptions(op, blendMode, DecodingMode::Synchronous, ImageOrientationDescription()));
291 }
292
293 void ImageBuffer::drawPattern(GraphicsContext& context, const FloatRect& destRect, const FloatRect& srcRect, const AffineTransform& patternTransform,
294     const FloatPoint& phase, const FloatSize& spacing, CompositeOperator op, BlendMode)
295 {
296     if (RefPtr<Image> image = copyImage(DontCopyBackingStore))
297         image->drawPattern(context, destRect, srcRect, patternTransform, phase, spacing, op);
298 }
299
300 void ImageBuffer::platformTransformColorSpace(const std::array<uint8_t, 256>& lookUpTable)
301 {
302     // FIXME: Enable color space conversions on accelerated canvases.
303     if (cairo_surface_get_type(m_data.m_surface.get()) != CAIRO_SURFACE_TYPE_IMAGE)
304         return;
305
306     unsigned char* dataSrc = cairo_image_surface_get_data(m_data.m_surface.get());
307     int stride = cairo_image_surface_get_stride(m_data.m_surface.get());
308     for (int y = 0; y < m_size.height(); ++y) {
309         unsigned* row = reinterpret_cast_ptr<unsigned*>(dataSrc + stride * y);
310         for (int x = 0; x < m_size.width(); x++) {
311             unsigned* pixel = row + x;
312             Color pixelColor = colorFromPremultipliedARGB(*pixel);
313             pixelColor = Color(lookUpTable[pixelColor.red()],
314                                lookUpTable[pixelColor.green()],
315                                lookUpTable[pixelColor.blue()],
316                                pixelColor.alpha());
317             *pixel = premultipliedARGBFromColor(pixelColor);
318         }
319     }
320     cairo_surface_mark_dirty_rectangle(m_data.m_surface.get(), 0, 0, m_logicalSize.width(), m_logicalSize.height());
321 }
322
323 RefPtr<cairo_surface_t> copySurfaceToImageAndAdjustRect(cairo_surface_t* surface, IntRect& rect)
324 {
325     cairo_surface_type_t surfaceType = cairo_surface_get_type(surface);
326
327     // If we already have an image, we write directly to the underlying data;
328     // otherwise we create a temporary surface image
329     if (surfaceType == CAIRO_SURFACE_TYPE_IMAGE)
330         return surface;
331     
332     rect.setX(0);
333     rect.setY(0);
334     return adoptRef(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, rect.width(), rect.height()));
335 }
336
337 template <Multiply multiplied>
338 RefPtr<Uint8ClampedArray> getImageData(const IntRect& rect, const IntRect& logicalRect, const ImageBufferData& data, const IntSize& size, const IntSize& logicalSize, float resolutionScale)
339 {
340     auto result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
341     if (!result)
342         return nullptr;
343
344     if (rect.x() < 0 || rect.y() < 0 || (rect.x() + rect.width()) > size.width() || (rect.y() + rect.height()) > size.height())
345         result->zeroFill();
346
347     int originx = rect.x();
348     int destx = 0;
349     if (originx < 0) {
350         destx = -originx;
351         originx = 0;
352     }
353     int endx = rect.maxX();
354     if (endx > size.width())
355         endx = size.width();
356     int numColumns = endx - originx;
357
358     int originy = rect.y();
359     int desty = 0;
360     if (originy < 0) {
361         desty = -originy;
362         originy = 0;
363     }
364     int endy = rect.maxY();
365     if (endy > size.height())
366         endy = size.height();
367     int numRows = endy - originy;
368
369     // The size of the derived surface is in BackingStoreCoordinateSystem.
370     // We need to set the device scale for the derived surface from this ImageBuffer.
371     IntRect imageRect(originx, originy, numColumns, numRows);
372     RefPtr<cairo_surface_t> imageSurface = copySurfaceToImageAndAdjustRect(data.m_surface.get(), imageRect);
373     cairoSurfaceSetDeviceScale(imageSurface.get(), resolutionScale, resolutionScale);
374     originx = imageRect.x();
375     originy = imageRect.y();
376     if (imageSurface != data.m_surface.get()) {
377         // This cairo surface operation is done in LogicalCoordinateSystem.
378         IntRect logicalArea = intersection(logicalRect, IntRect(0, 0, logicalSize.width(), logicalSize.height()));
379         copyRectFromOneSurfaceToAnother(data.m_surface.get(), imageSurface.get(), IntSize(-logicalArea.x(), -logicalArea.y()), IntRect(IntPoint(), logicalArea.size()), IntSize(), CAIRO_OPERATOR_SOURCE);
380     }
381
382     unsigned char* dataSrc = cairo_image_surface_get_data(imageSurface.get());
383     unsigned char* dataDst = result->data();
384     int stride = cairo_image_surface_get_stride(imageSurface.get());
385     unsigned destBytesPerRow = 4 * rect.width();
386
387     unsigned char* destRows = dataDst + desty * destBytesPerRow + destx * 4;
388     for (int y = 0; y < numRows; ++y) {
389         unsigned* row = reinterpret_cast_ptr<unsigned*>(dataSrc + stride * (y + originy));
390         for (int x = 0; x < numColumns; x++) {
391             int basex = x * 4;
392             unsigned* pixel = row + x + originx;
393
394             // Avoid calling Color::colorFromPremultipliedARGB() because one
395             // function call per pixel is too expensive.
396             unsigned alpha = (*pixel & 0xFF000000) >> 24;
397             unsigned red = (*pixel & 0x00FF0000) >> 16;
398             unsigned green = (*pixel & 0x0000FF00) >> 8;
399             unsigned blue = (*pixel & 0x000000FF);
400
401             if (multiplied == Unmultiplied) {
402                 if (alpha && alpha != 255) {
403                     red = red * 255 / alpha;
404                     green = green * 255 / alpha;
405                     blue = blue * 255 / alpha;
406                 }
407             }
408
409             destRows[basex]     = red;
410             destRows[basex + 1] = green;
411             destRows[basex + 2] = blue;
412             destRows[basex + 3] = alpha;
413         }
414         destRows += destBytesPerRow;
415     }
416
417     return result;
418 }
419
420 template<typename Unit>
421 inline Unit logicalUnit(const Unit& value, ImageBuffer::CoordinateSystem coordinateSystemOfValue, float resolutionScale)
422 {
423     if (coordinateSystemOfValue == ImageBuffer::LogicalCoordinateSystem || resolutionScale == 1.0)
424         return value;
425     Unit result(value);
426     result.scale(1.0 / resolutionScale);
427     return result;
428 }
429
430 template<typename Unit>
431 inline Unit backingStoreUnit(const Unit& value, ImageBuffer::CoordinateSystem coordinateSystemOfValue, float resolutionScale)
432 {
433     if (coordinateSystemOfValue == ImageBuffer::BackingStoreCoordinateSystem || resolutionScale == 1.0)
434         return value;
435     Unit result(value);
436     result.scale(resolutionScale);
437     return result;
438 }
439
440 RefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, IntSize* pixelArrayDimensions, CoordinateSystem coordinateSystem) const
441 {
442     IntRect logicalRect = logicalUnit(rect, coordinateSystem, m_resolutionScale);
443     IntRect backingStoreRect = backingStoreUnit(rect, coordinateSystem, m_resolutionScale);
444     if (pixelArrayDimensions)
445         *pixelArrayDimensions = backingStoreRect.size();
446     return getImageData<Unmultiplied>(backingStoreRect, logicalRect, m_data, m_size, m_logicalSize, m_resolutionScale);
447 }
448
449 RefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, IntSize* pixelArrayDimensions, CoordinateSystem coordinateSystem) const
450 {
451     IntRect logicalRect = logicalUnit(rect, coordinateSystem, m_resolutionScale);
452     IntRect backingStoreRect = backingStoreUnit(rect, coordinateSystem, m_resolutionScale);
453     if (pixelArrayDimensions)
454         *pixelArrayDimensions = backingStoreRect.size();
455     return getImageData<Premultiplied>(backingStoreRect, logicalRect, m_data, m_size, m_logicalSize, m_resolutionScale);
456 }
457
458 void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem coordinateSystem)
459 {
460     IntRect scaledSourceRect = backingStoreUnit(sourceRect, coordinateSystem, m_resolutionScale);
461     IntSize scaledSourceSize = backingStoreUnit(sourceSize, coordinateSystem, m_resolutionScale);
462     IntPoint scaledDestPoint = backingStoreUnit(destPoint, coordinateSystem, m_resolutionScale);
463     IntRect logicalSourceRect = logicalUnit(sourceRect, coordinateSystem, m_resolutionScale);
464     IntPoint logicalDestPoint = logicalUnit(destPoint, coordinateSystem, m_resolutionScale);
465
466     ASSERT(scaledSourceRect.width() > 0);
467     ASSERT(scaledSourceRect.height() > 0);
468
469     int originx = scaledSourceRect.x();
470     int destx = scaledDestPoint.x() + scaledSourceRect.x();
471     int logicalDestx = logicalDestPoint.x() + logicalSourceRect.x();
472     ASSERT(destx >= 0);
473     ASSERT(destx < m_size.width());
474     ASSERT(originx >= 0);
475     ASSERT(originx <= scaledSourceRect.maxX());
476
477     int endx = scaledDestPoint.x() + scaledSourceRect.maxX();
478     int logicalEndx = logicalDestPoint.x() + logicalSourceRect.maxX();
479     ASSERT(endx <= m_size.width());
480
481     int numColumns = endx - destx;
482     int logicalNumColumns = logicalEndx - logicalDestx;
483
484     int originy = scaledSourceRect.y();
485     int desty = scaledDestPoint.y() + scaledSourceRect.y();
486     int logicalDesty = logicalDestPoint.y() + logicalSourceRect.y();
487     ASSERT(desty >= 0);
488     ASSERT(desty < m_size.height());
489     ASSERT(originy >= 0);
490     ASSERT(originy <= scaledSourceRect.maxY());
491
492     int endy = scaledDestPoint.y() + scaledSourceRect.maxY();
493     int logicalEndy = logicalDestPoint.y() + logicalSourceRect.maxY();
494     ASSERT(endy <= m_size.height());
495     int numRows = endy - desty;
496     int logicalNumRows = logicalEndy - logicalDesty;
497
498     // The size of the derived surface is in BackingStoreCoordinateSystem.
499     // We need to set the device scale for the derived surface from this ImageBuffer.
500     IntRect imageRect(destx, desty, numColumns, numRows);
501     RefPtr<cairo_surface_t> imageSurface = copySurfaceToImageAndAdjustRect(m_data.m_surface.get(), imageRect);
502     cairoSurfaceSetDeviceScale(imageSurface.get(), m_resolutionScale, m_resolutionScale);
503     destx = imageRect.x();
504     desty = imageRect.y();
505
506     unsigned char* pixelData = cairo_image_surface_get_data(imageSurface.get());
507
508     unsigned srcBytesPerRow = 4 * scaledSourceSize.width();
509     int stride = cairo_image_surface_get_stride(imageSurface.get());
510
511     unsigned char* srcRows = source->data() + originy * srcBytesPerRow + originx * 4;
512     for (int y = 0; y < numRows; ++y) {
513         unsigned* row = reinterpret_cast_ptr<unsigned*>(pixelData + stride * (y + desty));
514         for (int x = 0; x < numColumns; x++) {
515             int basex = x * 4;
516             unsigned* pixel = row + x + destx;
517
518             // Avoid calling Color::premultipliedARGBFromColor() because one
519             // function call per pixel is too expensive.
520             unsigned red = srcRows[basex];
521             unsigned green = srcRows[basex + 1];
522             unsigned blue = srcRows[basex + 2];
523             unsigned alpha = srcRows[basex + 3];
524
525             if (multiplied == Unmultiplied) {
526                 if (alpha != 255) {
527                     red = (red * alpha + 254) / 255;
528                     green = (green * alpha + 254) / 255;
529                     blue = (blue * alpha + 254) / 255;
530                 }
531             }
532
533             *pixel = (alpha << 24) | red  << 16 | green  << 8 | blue;
534         }
535         srcRows += srcBytesPerRow;
536     }
537
538     // This cairo surface operation is done in LogicalCoordinateSystem.
539     cairo_surface_mark_dirty_rectangle(imageSurface.get(), logicalDestx, logicalDesty, logicalNumColumns, logicalNumRows);
540
541     if (imageSurface != m_data.m_surface.get()) {
542         // This cairo surface operation is done in LogicalCoordinateSystem.
543         copyRectFromOneSurfaceToAnother(imageSurface.get(), m_data.m_surface.get(), IntSize(), IntRect(0, 0, logicalNumColumns, logicalNumRows), IntSize(logicalDestPoint.x() + logicalSourceRect.x(), logicalDestPoint.y() + logicalSourceRect.y()), CAIRO_OPERATOR_SOURCE);
544     }
545 }
546
547 #if !PLATFORM(GTK)
548 static cairo_status_t writeFunction(void* output, const unsigned char* data, unsigned int length)
549 {
550     if (!reinterpret_cast<Vector<uint8_t>*>(output)->tryAppend(data, length))
551         return CAIRO_STATUS_WRITE_ERROR;
552     return CAIRO_STATUS_SUCCESS;
553 }
554
555 static bool encodeImage(cairo_surface_t* image, const String& mimeType, Vector<uint8_t>* output)
556 {
557     ASSERT_UNUSED(mimeType, mimeType == "image/png"); // Only PNG output is supported for now.
558
559     return cairo_surface_write_to_png_stream(image, writeFunction, output) == CAIRO_STATUS_SUCCESS;
560 }
561
562 String ImageBuffer::toDataURL(const String& mimeType, std::optional<double> quality, CoordinateSystem) const
563 {
564     Vector<uint8_t> encodedImage = toData(mimeType, quality);
565     if (encodedImage.isEmpty())
566         return "data:,";
567
568     Vector<char> base64Data;
569     base64Encode(encodedImage.data(), encodedImage.size(), base64Data);
570
571     return "data:" + mimeType + ";base64," + base64Data;
572 }
573
574 Vector<uint8_t> ImageBuffer::toData(const String& mimeType, std::optional<double>) const
575 {
576     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
577
578     cairo_surface_t* image = cairo_get_target(context().platformContext()->cr());
579
580     Vector<uint8_t> encodedImage;
581     if (!image || !encodeImage(image, mimeType, &encodedImage))
582         return { };
583
584     return encodedImage;
585 }
586
587 #endif
588
589 #if ENABLE(ACCELERATED_2D_CANVAS) && !USE(COORDINATED_GRAPHICS_THREADED)
590 void ImageBufferData::paintToTextureMapper(TextureMapper& textureMapper, const FloatRect& targetRect, const TransformationMatrix& matrix, float opacity)
591 {
592     ASSERT(m_texture);
593
594     // Cairo may change the active context, so we make sure to change it back after flushing.
595     GLContext* previousActiveContext = GLContext::current();
596     cairo_surface_flush(m_surface.get());
597     previousActiveContext->makeContextCurrent();
598
599     static_cast<TextureMapperGL&>(textureMapper).drawTexture(m_texture, TextureMapperGL::ShouldBlend, m_size, targetRect, matrix, opacity);
600 }
601 #endif
602
603 PlatformLayer* ImageBuffer::platformLayer() const
604 {
605 #if ENABLE(ACCELERATED_2D_CANVAS)
606     if (m_data.m_texture)
607         return const_cast<ImageBufferData*>(&m_data);
608 #endif
609     return 0;
610 }
611
612 bool ImageBuffer::copyToPlatformTexture(GraphicsContext3D&, GC3Denum target, Platform3DObject destinationTexture, GC3Denum internalformat, bool premultiplyAlpha, bool flipY)
613 {
614 #if ENABLE(ACCELERATED_2D_CANVAS)
615     ASSERT_WITH_MESSAGE(m_resolutionScale == 1.0, "Since the HiDPI Canvas feature is removed, the resolution factor here is always 1.");
616     if (premultiplyAlpha || flipY)
617         return false;
618
619     if (!m_data.m_texture)
620         return false;
621
622     GC3Denum bindTextureTarget;
623     switch (target) {
624     case GL_TEXTURE_2D:
625         bindTextureTarget = GL_TEXTURE_2D;
626         break;
627     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
628     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
629     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
630     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
631     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
632     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
633         bindTextureTarget = GL_TEXTURE_CUBE_MAP;
634         break;
635     default:
636         return false;
637     }
638
639     cairo_surface_flush(m_data.m_surface.get());
640
641     std::unique_ptr<GLContext> context = GLContext::createOffscreenContext(&PlatformDisplay::sharedDisplayForCompositing());
642     context->makeContextCurrent();
643     uint32_t fbo;
644     glGenFramebuffers(1, &fbo);
645     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
646     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_data.m_texture, 0);
647     glBindTexture(bindTextureTarget, destinationTexture);
648     glCopyTexImage2D(target, 0, internalformat, 0, 0, m_size.width(), m_size.height(), 0);
649     glBindTexture(bindTextureTarget, 0);
650     glBindFramebuffer(GL_FRAMEBUFFER, 0);
651     glFlush();
652     glDeleteFramebuffers(1, &fbo);
653     return true;
654 #else
655     UNUSED_PARAM(target);
656     UNUSED_PARAM(destinationTexture);
657     UNUSED_PARAM(internalformat);
658     UNUSED_PARAM(premultiplyAlpha);
659     UNUSED_PARAM(flipY);
660     return false;
661 #endif
662 }
663
664 } // namespace WebCore
665
666 #endif // USE(CAIRO)