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