Use "= default" to denote default constructor or destructor
[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 "EpoxyEGL.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
72 namespace WebCore {
73 using namespace std;
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 RefPtr<TextureMapperPlatformLayerProxy> ImageBufferData::proxy() const
136 {
137     return m_platformLayerProxy.copyRef();
138 }
139
140 void ImageBufferData::swapBuffersIfNeeded()
141 {
142     GLContext* previousActiveContext = GLContext::current();
143
144     if (!m_compositorTexture) {
145         createCompositorBuffer();
146         LockHolder holder(m_platformLayerProxy->lock());
147         m_platformLayerProxy->pushNextBuffer(std::make_unique<TextureMapperPlatformLayerBuffer>(m_compositorTexture, m_size, TextureMapperGL::ShouldBlend, GL_RGBA));
148     }
149
150     // It would be great if we could just swap the buffers here as we do with webgl, but that breaks the cases
151     // where one frame uses the content already rendered in the previous frame. So we just copy the content
152     // into the compositor buffer.
153     cairo_set_source_surface(m_compositorCr.get(), m_surface.get(), 0, 0);
154     cairo_set_operator(m_compositorCr.get(), CAIRO_OPERATOR_SOURCE);
155     cairo_paint(m_compositorCr.get());
156
157     if (previousActiveContext)
158         previousActiveContext->makeContextCurrent();
159 }
160 #endif
161
162 void clearSurface(cairo_surface_t* surface)
163 {
164     if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS)
165         return;
166
167     RefPtr<cairo_t> cr = adoptRef(cairo_create(surface));
168     cairo_set_operator(cr.get(), CAIRO_OPERATOR_CLEAR);
169     cairo_paint(cr.get());
170 }
171
172 void ImageBufferData::createCairoGLSurface()
173 {
174     auto* context = PlatformDisplay::sharedDisplayForCompositing().sharingGLContext();
175     context->makeContextCurrent();
176
177     // We must generate the texture ourselves, because there is no Cairo API for extracting it
178     // from a pre-existing surface.
179     glGenTextures(1, &m_texture);
180     glBindTexture(GL_TEXTURE_2D, m_texture);
181     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
182     glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
183     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
184     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
185
186     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
187
188     glTexImage2D(GL_TEXTURE_2D, 0 /* level */, GL_RGBA, m_size.width(), m_size.height(), 0 /* border */, GL_RGBA, GL_UNSIGNED_BYTE, 0);
189
190     cairo_device_t* device = context->cairoDevice();
191
192     // Thread-awareness is a huge performance hit on non-Intel drivers.
193     cairo_gl_device_set_thread_aware(device, FALSE);
194
195     m_surface = adoptRef(cairo_gl_surface_create_for_texture(device, CAIRO_CONTENT_COLOR_ALPHA, m_texture, m_size.width(), m_size.height()));
196     clearSurface(m_surface.get());
197 }
198 #endif
199
200 ImageBuffer::ImageBuffer(const FloatSize& size, float resolutionScale, ColorSpace, RenderingMode renderingMode, bool& success)
201     : m_data(IntSize(size), renderingMode)
202     , m_logicalSize(size)
203     , m_resolutionScale(resolutionScale)
204 {
205     success = false;  // Make early return mean error.
206
207     float scaledWidth = ceilf(m_resolutionScale * size.width());
208     float scaledHeight = ceilf(m_resolutionScale * size.height());
209
210     // FIXME: Should we automatically use a lower resolution?
211     if (!FloatSize(scaledWidth, scaledHeight).isExpressibleAsIntSize())
212         return;
213
214     m_size = IntSize(scaledWidth, scaledHeight);
215     m_data.m_size = m_size;
216
217     if (m_size.isEmpty())
218         return;
219
220 #if ENABLE(ACCELERATED_2D_CANVAS)
221     if (m_data.m_renderingMode == Accelerated) {
222         m_data.createCairoGLSurface();
223         if (!m_data.m_surface || cairo_surface_status(m_data.m_surface.get()) != CAIRO_STATUS_SUCCESS)
224             m_data.m_renderingMode = Unaccelerated; // If allocation fails, fall back to non-accelerated path.
225     }
226     if (m_data.m_renderingMode == Unaccelerated)
227 #else
228     ASSERT(m_data.m_renderingMode != Accelerated);
229 #endif
230     {
231         static cairo_user_data_key_t s_surfaceDataKey;
232
233         int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, m_size.width());
234         auto* surfaceData = fastZeroedMalloc(m_size.height() * stride);
235
236         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));
237         cairo_surface_set_user_data(m_data.m_surface.get(), &s_surfaceDataKey, surfaceData, [](void* data) { fastFree(data); });
238     }
239
240     if (cairo_surface_status(m_data.m_surface.get()) != CAIRO_STATUS_SUCCESS)
241         return;  // create will notice we didn't set m_initialized and fail.
242
243     cairoSurfaceSetDeviceScale(m_data.m_surface.get(), m_resolutionScale, m_resolutionScale);
244
245     RefPtr<cairo_t> cr = adoptRef(cairo_create(m_data.m_surface.get()));
246     m_data.m_platformContext.setCr(cr.get());
247     m_data.m_context = std::make_unique<GraphicsContext>(&m_data.m_platformContext);
248     success = true;
249 }
250
251 ImageBuffer::~ImageBuffer() = default;
252
253 std::unique_ptr<ImageBuffer> ImageBuffer::createCompatibleBuffer(const FloatSize& size, const GraphicsContext& context)
254 {
255     return createCompatibleBuffer(size, ColorSpaceSRGB, context);
256 }
257
258 GraphicsContext& ImageBuffer::context() const
259 {
260     return *m_data.m_context;
261 }
262
263 RefPtr<Image> ImageBuffer::sinkIntoImage(std::unique_ptr<ImageBuffer> imageBuffer, ScaleBehavior scaleBehavior)
264 {
265     return imageBuffer->copyImage(DontCopyBackingStore, scaleBehavior);
266 }
267
268 RefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior) const
269 {
270     // copyCairoImageSurface inherits surface's device scale factor.
271     if (copyBehavior == CopyBackingStore)
272         return BitmapImage::create(copyCairoImageSurface(m_data.m_surface.get()));
273
274     // BitmapImage will release the passed in surface on destruction
275     return BitmapImage::create(RefPtr<cairo_surface_t>(m_data.m_surface));
276 }
277
278 BackingStoreCopy ImageBuffer::fastCopyImageMode()
279 {
280     return DontCopyBackingStore;
281 }
282
283 void ImageBuffer::drawConsuming(std::unique_ptr<ImageBuffer> imageBuffer, GraphicsContext& destContext, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op, BlendMode blendMode)
284 {
285     imageBuffer->draw(destContext, destRect, srcRect, op, blendMode);
286 }
287
288 void ImageBuffer::draw(GraphicsContext& destinationContext, const FloatRect& destRect, const FloatRect& srcRect,
289     CompositeOperator op, BlendMode blendMode)
290 {
291     BackingStoreCopy copyMode = &destinationContext == &context() ? CopyBackingStore : DontCopyBackingStore;
292     RefPtr<Image> image = copyImage(copyMode);
293     destinationContext.drawImage(*image, destRect, srcRect, ImagePaintingOptions(op, blendMode, DecodingMode::Synchronous, ImageOrientationDescription()));
294 }
295
296 void ImageBuffer::drawPattern(GraphicsContext& context, const FloatRect& destRect, const FloatRect& srcRect, const AffineTransform& patternTransform,
297     const FloatPoint& phase, const FloatSize& spacing, CompositeOperator op, BlendMode)
298 {
299     if (RefPtr<Image> image = copyImage(DontCopyBackingStore))
300         image->drawPattern(context, destRect, srcRect, patternTransform, phase, spacing, op);
301 }
302
303 void ImageBuffer::platformTransformColorSpace(const std::array<uint8_t, 256>& lookUpTable)
304 {
305     // FIXME: Enable color space conversions on accelerated canvases.
306     if (cairo_surface_get_type(m_data.m_surface.get()) != CAIRO_SURFACE_TYPE_IMAGE)
307         return;
308
309     unsigned char* dataSrc = cairo_image_surface_get_data(m_data.m_surface.get());
310     int stride = cairo_image_surface_get_stride(m_data.m_surface.get());
311     for (int y = 0; y < m_size.height(); ++y) {
312         unsigned* row = reinterpret_cast_ptr<unsigned*>(dataSrc + stride * y);
313         for (int x = 0; x < m_size.width(); x++) {
314             unsigned* pixel = row + x;
315             Color pixelColor = colorFromPremultipliedARGB(*pixel);
316             pixelColor = Color(lookUpTable[pixelColor.red()],
317                                lookUpTable[pixelColor.green()],
318                                lookUpTable[pixelColor.blue()],
319                                pixelColor.alpha());
320             *pixel = premultipliedARGBFromColor(pixelColor);
321         }
322     }
323     cairo_surface_mark_dirty_rectangle(m_data.m_surface.get(), 0, 0, m_logicalSize.width(), m_logicalSize.height());
324 }
325
326 RefPtr<cairo_surface_t> copySurfaceToImageAndAdjustRect(cairo_surface_t* surface, IntRect& rect)
327 {
328     cairo_surface_type_t surfaceType = cairo_surface_get_type(surface);
329
330     // If we already have an image, we write directly to the underlying data;
331     // otherwise we create a temporary surface image
332     if (surfaceType == CAIRO_SURFACE_TYPE_IMAGE)
333         return surface;
334     
335     rect.setX(0);
336     rect.setY(0);
337     return adoptRef(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, rect.width(), rect.height()));
338 }
339
340 template <Multiply multiplied>
341 RefPtr<Uint8ClampedArray> getImageData(const IntRect& rect, const IntRect& logicalRect, const ImageBufferData& data, const IntSize& size, const IntSize& logicalSize, float resolutionScale)
342 {
343     auto result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
344     if (!result)
345         return nullptr;
346
347     if (rect.x() < 0 || rect.y() < 0 || (rect.x() + rect.width()) > size.width() || (rect.y() + rect.height()) > size.height())
348         result->zeroFill();
349
350     int originx = rect.x();
351     int destx = 0;
352     if (originx < 0) {
353         destx = -originx;
354         originx = 0;
355     }
356     int endx = rect.maxX();
357     if (endx > size.width())
358         endx = size.width();
359     int numColumns = endx - originx;
360
361     int originy = rect.y();
362     int desty = 0;
363     if (originy < 0) {
364         desty = -originy;
365         originy = 0;
366     }
367     int endy = rect.maxY();
368     if (endy > size.height())
369         endy = size.height();
370     int numRows = endy - originy;
371
372     // The size of the derived surface is in BackingStoreCoordinateSystem.
373     // We need to set the device scale for the derived surface from this ImageBuffer.
374     IntRect imageRect(originx, originy, numColumns, numRows);
375     RefPtr<cairo_surface_t> imageSurface = copySurfaceToImageAndAdjustRect(data.m_surface.get(), imageRect);
376     cairoSurfaceSetDeviceScale(imageSurface.get(), resolutionScale, resolutionScale);
377     originx = imageRect.x();
378     originy = imageRect.y();
379     if (imageSurface != data.m_surface.get()) {
380         // This cairo surface operation is done in LogicalCoordinateSystem.
381         IntRect logicalArea = intersection(logicalRect, IntRect(0, 0, logicalSize.width(), logicalSize.height()));
382         copyRectFromOneSurfaceToAnother(data.m_surface.get(), imageSurface.get(), IntSize(-logicalArea.x(), -logicalArea.y()), IntRect(IntPoint(), logicalArea.size()), IntSize(), CAIRO_OPERATOR_SOURCE);
383     }
384
385     unsigned char* dataSrc = cairo_image_surface_get_data(imageSurface.get());
386     unsigned char* dataDst = result->data();
387     int stride = cairo_image_surface_get_stride(imageSurface.get());
388     unsigned destBytesPerRow = 4 * rect.width();
389
390     unsigned char* destRows = dataDst + desty * destBytesPerRow + destx * 4;
391     for (int y = 0; y < numRows; ++y) {
392         unsigned* row = reinterpret_cast_ptr<unsigned*>(dataSrc + stride * (y + originy));
393         for (int x = 0; x < numColumns; x++) {
394             int basex = x * 4;
395             unsigned* pixel = row + x + originx;
396
397             // Avoid calling Color::colorFromPremultipliedARGB() because one
398             // function call per pixel is too expensive.
399             unsigned alpha = (*pixel & 0xFF000000) >> 24;
400             unsigned red = (*pixel & 0x00FF0000) >> 16;
401             unsigned green = (*pixel & 0x0000FF00) >> 8;
402             unsigned blue = (*pixel & 0x000000FF);
403
404             if (multiplied == Unmultiplied) {
405                 if (alpha && alpha != 255) {
406                     red = red * 255 / alpha;
407                     green = green * 255 / alpha;
408                     blue = blue * 255 / alpha;
409                 }
410             }
411
412             destRows[basex]     = red;
413             destRows[basex + 1] = green;
414             destRows[basex + 2] = blue;
415             destRows[basex + 3] = alpha;
416         }
417         destRows += destBytesPerRow;
418     }
419
420     return result;
421 }
422
423 template<typename Unit>
424 inline Unit logicalUnit(const Unit& value, ImageBuffer::CoordinateSystem coordinateSystemOfValue, float resolutionScale)
425 {
426     if (coordinateSystemOfValue == ImageBuffer::LogicalCoordinateSystem || resolutionScale == 1.0)
427         return value;
428     Unit result(value);
429     result.scale(1.0 / resolutionScale);
430     return result;
431 }
432
433 template<typename Unit>
434 inline Unit backingStoreUnit(const Unit& value, ImageBuffer::CoordinateSystem coordinateSystemOfValue, float resolutionScale)
435 {
436     if (coordinateSystemOfValue == ImageBuffer::BackingStoreCoordinateSystem || resolutionScale == 1.0)
437         return value;
438     Unit result(value);
439     result.scale(resolutionScale);
440     return result;
441 }
442
443 RefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, IntSize* pixelArrayDimensions, CoordinateSystem coordinateSystem) const
444 {
445     IntRect logicalRect = logicalUnit(rect, coordinateSystem, m_resolutionScale);
446     IntRect backingStoreRect = backingStoreUnit(rect, coordinateSystem, m_resolutionScale);
447     if (pixelArrayDimensions)
448         *pixelArrayDimensions = backingStoreRect.size();
449     return getImageData<Unmultiplied>(backingStoreRect, logicalRect, m_data, m_size, m_logicalSize, m_resolutionScale);
450 }
451
452 RefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, IntSize* pixelArrayDimensions, CoordinateSystem coordinateSystem) const
453 {
454     IntRect logicalRect = logicalUnit(rect, coordinateSystem, m_resolutionScale);
455     IntRect backingStoreRect = backingStoreUnit(rect, coordinateSystem, m_resolutionScale);
456     if (pixelArrayDimensions)
457         *pixelArrayDimensions = backingStoreRect.size();
458     return getImageData<Premultiplied>(backingStoreRect, logicalRect, m_data, m_size, m_logicalSize, m_resolutionScale);
459 }
460
461 void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem coordinateSystem)
462 {
463     IntRect scaledSourceRect = backingStoreUnit(sourceRect, coordinateSystem, m_resolutionScale);
464     IntSize scaledSourceSize = backingStoreUnit(sourceSize, coordinateSystem, m_resolutionScale);
465     IntPoint scaledDestPoint = backingStoreUnit(destPoint, coordinateSystem, m_resolutionScale);
466     IntRect logicalSourceRect = logicalUnit(sourceRect, coordinateSystem, m_resolutionScale);
467     IntPoint logicalDestPoint = logicalUnit(destPoint, coordinateSystem, m_resolutionScale);
468
469     ASSERT(scaledSourceRect.width() > 0);
470     ASSERT(scaledSourceRect.height() > 0);
471
472     int originx = scaledSourceRect.x();
473     int destx = scaledDestPoint.x() + scaledSourceRect.x();
474     int logicalDestx = logicalDestPoint.x() + logicalSourceRect.x();
475     ASSERT(destx >= 0);
476     ASSERT(destx < m_size.width());
477     ASSERT(originx >= 0);
478     ASSERT(originx <= scaledSourceRect.maxX());
479
480     int endx = scaledDestPoint.x() + scaledSourceRect.maxX();
481     int logicalEndx = logicalDestPoint.x() + logicalSourceRect.maxX();
482     ASSERT(endx <= m_size.width());
483
484     int numColumns = endx - destx;
485     int logicalNumColumns = logicalEndx - logicalDestx;
486
487     int originy = scaledSourceRect.y();
488     int desty = scaledDestPoint.y() + scaledSourceRect.y();
489     int logicalDesty = logicalDestPoint.y() + logicalSourceRect.y();
490     ASSERT(desty >= 0);
491     ASSERT(desty < m_size.height());
492     ASSERT(originy >= 0);
493     ASSERT(originy <= scaledSourceRect.maxY());
494
495     int endy = scaledDestPoint.y() + scaledSourceRect.maxY();
496     int logicalEndy = logicalDestPoint.y() + logicalSourceRect.maxY();
497     ASSERT(endy <= m_size.height());
498     int numRows = endy - desty;
499     int logicalNumRows = logicalEndy - logicalDesty;
500
501     // The size of the derived surface is in BackingStoreCoordinateSystem.
502     // We need to set the device scale for the derived surface from this ImageBuffer.
503     IntRect imageRect(destx, desty, numColumns, numRows);
504     RefPtr<cairo_surface_t> imageSurface = copySurfaceToImageAndAdjustRect(m_data.m_surface.get(), imageRect);
505     cairoSurfaceSetDeviceScale(imageSurface.get(), m_resolutionScale, m_resolutionScale);
506     destx = imageRect.x();
507     desty = imageRect.y();
508
509     unsigned char* pixelData = cairo_image_surface_get_data(imageSurface.get());
510
511     unsigned srcBytesPerRow = 4 * scaledSourceSize.width();
512     int stride = cairo_image_surface_get_stride(imageSurface.get());
513
514     unsigned char* srcRows = source->data() + originy * srcBytesPerRow + originx * 4;
515     for (int y = 0; y < numRows; ++y) {
516         unsigned* row = reinterpret_cast_ptr<unsigned*>(pixelData + stride * (y + desty));
517         for (int x = 0; x < numColumns; x++) {
518             int basex = x * 4;
519             unsigned* pixel = row + x + destx;
520
521             // Avoid calling Color::premultipliedARGBFromColor() because one
522             // function call per pixel is too expensive.
523             unsigned red = srcRows[basex];
524             unsigned green = srcRows[basex + 1];
525             unsigned blue = srcRows[basex + 2];
526             unsigned alpha = srcRows[basex + 3];
527
528             if (multiplied == Unmultiplied) {
529                 if (alpha != 255) {
530                     red = (red * alpha + 254) / 255;
531                     green = (green * alpha + 254) / 255;
532                     blue = (blue * alpha + 254) / 255;
533                 }
534             }
535
536             *pixel = (alpha << 24) | red  << 16 | green  << 8 | blue;
537         }
538         srcRows += srcBytesPerRow;
539     }
540
541     // This cairo surface operation is done in LogicalCoordinateSystem.
542     cairo_surface_mark_dirty_rectangle(imageSurface.get(), logicalDestx, logicalDesty, logicalNumColumns, logicalNumRows);
543
544     if (imageSurface != m_data.m_surface.get()) {
545         // This cairo surface operation is done in LogicalCoordinateSystem.
546         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);
547     }
548 }
549
550 #if !PLATFORM(GTK)
551 static cairo_status_t writeFunction(void* output, const unsigned char* data, unsigned int length)
552 {
553     if (!reinterpret_cast<Vector<uint8_t>*>(output)->tryAppend(data, length))
554         return CAIRO_STATUS_WRITE_ERROR;
555     return CAIRO_STATUS_SUCCESS;
556 }
557
558 static bool encodeImage(cairo_surface_t* image, const String& mimeType, Vector<uint8_t>* output)
559 {
560     ASSERT_UNUSED(mimeType, mimeType == "image/png"); // Only PNG output is supported for now.
561
562     return cairo_surface_write_to_png_stream(image, writeFunction, output) == CAIRO_STATUS_SUCCESS;
563 }
564
565 String ImageBuffer::toDataURL(const String& mimeType, std::optional<double> quality, CoordinateSystem) const
566 {
567     Vector<uint8_t> encodedImage = toData(mimeType, quality);
568     if (encodedImage.isEmpty())
569         return "data:,";
570
571     Vector<char> base64Data;
572     base64Encode(encodedImage.data(), encodedImage.size(), base64Data);
573
574     return "data:" + mimeType + ";base64," + base64Data;
575 }
576
577 Vector<uint8_t> ImageBuffer::toData(const String& mimeType, std::optional<double>) const
578 {
579     ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
580
581     cairo_surface_t* image = cairo_get_target(context().platformContext()->cr());
582
583     Vector<uint8_t> encodedImage;
584     if (!image || !encodeImage(image, mimeType, &encodedImage))
585         return { };
586
587     return encodedImage;
588 }
589
590 #endif
591
592 #if ENABLE(ACCELERATED_2D_CANVAS) && !USE(COORDINATED_GRAPHICS_THREADED)
593 void ImageBufferData::paintToTextureMapper(TextureMapper& textureMapper, const FloatRect& targetRect, const TransformationMatrix& matrix, float opacity)
594 {
595     ASSERT(m_texture);
596
597     // Cairo may change the active context, so we make sure to change it back after flushing.
598     GLContext* previousActiveContext = GLContext::current();
599     cairo_surface_flush(m_surface.get());
600     previousActiveContext->makeContextCurrent();
601
602     static_cast<TextureMapperGL&>(textureMapper).drawTexture(m_texture, TextureMapperGL::ShouldBlend, m_size, targetRect, matrix, opacity);
603 }
604 #endif
605
606 PlatformLayer* ImageBuffer::platformLayer() const
607 {
608 #if ENABLE(ACCELERATED_2D_CANVAS)
609     if (m_data.m_texture)
610         return const_cast<ImageBufferData*>(&m_data);
611 #endif
612     return 0;
613 }
614
615 bool ImageBuffer::copyToPlatformTexture(GraphicsContext3D&, GC3Denum target, Platform3DObject destinationTexture, GC3Denum internalformat, bool premultiplyAlpha, bool flipY)
616 {
617 #if ENABLE(ACCELERATED_2D_CANVAS)
618     ASSERT_WITH_MESSAGE(m_resolutionScale == 1.0, "Since the HiDPI Canvas feature is removed, the resolution factor here is always 1.");
619     if (premultiplyAlpha || flipY)
620         return false;
621
622     if (!m_data.m_texture)
623         return false;
624
625     GC3Denum bindTextureTarget;
626     switch (target) {
627     case GL_TEXTURE_2D:
628         bindTextureTarget = GL_TEXTURE_2D;
629         break;
630     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
631     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
632     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
633     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
634     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
635     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
636         bindTextureTarget = GL_TEXTURE_CUBE_MAP;
637         break;
638     default:
639         return false;
640     }
641
642     cairo_surface_flush(m_data.m_surface.get());
643
644     std::unique_ptr<GLContext> context = GLContext::createOffscreenContext(&PlatformDisplay::sharedDisplayForCompositing());
645     context->makeContextCurrent();
646     uint32_t fbo;
647     glGenFramebuffers(1, &fbo);
648     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
649     glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_data.m_texture, 0);
650     glBindTexture(bindTextureTarget, destinationTexture);
651     glCopyTexImage2D(target, 0, internalformat, 0, 0, m_size.width(), m_size.height(), 0);
652     glBindTexture(bindTextureTarget, 0);
653     glBindFramebuffer(GL_FRAMEBUFFER, 0);
654     glFlush();
655     glDeleteFramebuffers(1, &fbo);
656     return true;
657 #else
658     UNUSED_PARAM(target);
659     UNUSED_PARAM(destinationTexture);
660     UNUSED_PARAM(internalformat);
661     UNUSED_PARAM(premultiplyAlpha);
662     UNUSED_PARAM(flipY);
663     return false;
664 #endif
665 }
666
667 } // namespace WebCore
668
669 #endif // USE(CAIRO)