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