Host GraphicsContext's CTM inside GraphicsContextState
[WebKit-https.git] / Source / WebCore / platform / graphics / cairo / GraphicsContextCairo.cpp
1 /*
2  * Copyright (C) 2006 Apple Inc.  All rights reserved.
3  * Copyright (C) 2007 Alp Toker <alp@atoker.com>
4  * Copyright (C) 2008, 2009 Dirk Schulze <krit@webkit.org>
5  * Copyright (C) 2008 Nuanti Ltd.
6  * Copyright (C) 2009 Brent Fulgham <bfulgham@webkit.org>
7  * Copyright (C) 2010, 2011 Igalia S.L.
8  * Copyright (C) Research In Motion Limited 2010. All rights reserved.
9  * Copyright (C) 2012, Intel Corporation
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
21  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
24  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
28  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "config.h"
34 #include "GraphicsContext.h"
35
36 #if USE(CAIRO)
37
38 #include "AffineTransform.h"
39 #include "CairoUtilities.h"
40 #include "DrawErrorUnderline.h"
41 #include "FloatConversion.h"
42 #include "FloatRect.h"
43 #include "FloatRoundedRect.h"
44 #include "Font.h"
45 #include "GraphicsContextPlatformPrivateCairo.h"
46 #include "IntRect.h"
47 #include "NotImplemented.h"
48 #include "Path.h"
49 #include "Pattern.h"
50 #include "PlatformContextCairo.h"
51 #include "PlatformPathCairo.h"
52 #include "RefPtrCairo.h"
53 #include "ShadowBlur.h"
54 #include "TransformationMatrix.h"
55 #include <cairo.h>
56 #include <math.h>
57 #include <stdio.h>
58 #include <wtf/MathExtras.h>
59
60 #if PLATFORM(WIN)
61 #include <cairo-win32.h>
62 #endif
63
64 using namespace std;
65
66 namespace WebCore {
67
68 // A helper which quickly fills a rectangle with a simple color fill.
69 static inline void fillRectWithColor(cairo_t* cr, const FloatRect& rect, const Color& color)
70 {
71     if (!color.alpha() && cairo_get_operator(cr) == CAIRO_OPERATOR_OVER)
72         return;
73     setSourceRGBAFromColor(cr, color);
74     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
75     cairo_fill(cr);
76 }
77
78 static void addConvexPolygonToContext(cairo_t* context, size_t numPoints, const FloatPoint* points)
79 {
80     cairo_move_to(context, points[0].x(), points[0].y());
81     for (size_t i = 1; i < numPoints; i++)
82         cairo_line_to(context, points[i].x(), points[i].y());
83     cairo_close_path(context);
84 }
85
86 enum PathDrawingStyle { 
87     Fill = 1,
88     Stroke = 2,
89     FillAndStroke = Fill + Stroke
90 };
91
92 static inline void drawPathShadow(GraphicsContext& context, PathDrawingStyle drawingStyle)
93 {
94     ShadowBlur& shadow = context.platformContext()->shadowBlur();
95     if (shadow.type() == ShadowBlur::NoShadow)
96         return;
97
98     // Calculate the extents of the rendered solid paths.
99     cairo_t* cairoContext = context.platformContext()->cr();
100     std::unique_ptr<cairo_path_t, void(*)(cairo_path_t*)> path(cairo_copy_path(cairoContext), [](cairo_path_t* path) {
101         cairo_path_destroy(path);
102     });
103
104     FloatRect solidFigureExtents;
105     double x0 = 0;
106     double x1 = 0;
107     double y0 = 0;
108     double y1 = 0;
109     if (drawingStyle & Stroke) {
110         cairo_stroke_extents(cairoContext, &x0, &y0, &x1, &y1);
111         solidFigureExtents = FloatRect(x0, y0, x1 - x0, y1 - y0);
112     }
113     if (drawingStyle & Fill) {
114         cairo_fill_extents(cairoContext, &x0, &y0, &x1, &y1);
115         FloatRect fillExtents(x0, y0, x1 - x0, y1 - y0);
116         solidFigureExtents.unite(fillExtents);
117     }
118
119     GraphicsContext* shadowContext = shadow.beginShadowLayer(context, solidFigureExtents);
120     if (!shadowContext)
121         return;
122
123     cairo_t* cairoShadowContext = shadowContext->platformContext()->cr();
124
125     // It's important to copy the context properties to the new shadow
126     // context to preserve things such as the fill rule and stroke width.
127     copyContextProperties(cairoContext, cairoShadowContext);
128
129     if (drawingStyle & Fill) {
130         cairo_save(cairoShadowContext);
131         cairo_append_path(cairoShadowContext, path.get());
132         shadowContext->platformContext()->prepareForFilling(context.state(), PlatformContextCairo::NoAdjustment);
133         cairo_fill(cairoShadowContext);
134         cairo_restore(cairoShadowContext);
135     }
136
137     if (drawingStyle & Stroke) {
138         cairo_append_path(cairoShadowContext, path.get());
139         shadowContext->platformContext()->prepareForStroking(context.state(), PlatformContextCairo::DoNotPreserveAlpha);
140         cairo_stroke(cairoShadowContext);
141     }
142
143     // The original path may still be hanging around on the context and endShadowLayer
144     // will take care of properly creating a path to draw the result shadow. We remove the path
145     // temporarily and then restore it.
146     // See: https://bugs.webkit.org/show_bug.cgi?id=108897
147     cairo_new_path(cairoContext);
148     shadow.endShadowLayer(context);
149     cairo_append_path(cairoContext, path.get());
150 }
151
152 static inline void fillCurrentCairoPath(GraphicsContext& context)
153 {
154     cairo_t* cr = context.platformContext()->cr();
155     cairo_save(cr);
156
157     context.platformContext()->prepareForFilling(context.state(), PlatformContextCairo::AdjustPatternForGlobalAlpha);
158     cairo_fill(cr);
159
160     cairo_restore(cr);
161 }
162
163 static inline void shadowAndFillCurrentCairoPath(GraphicsContext& context)
164 {
165     drawPathShadow(context, Fill);
166     fillCurrentCairoPath(context);
167 }
168
169 static inline void shadowAndStrokeCurrentCairoPath(GraphicsContext& context)
170 {
171     drawPathShadow(context, Stroke);
172     context.platformContext()->prepareForStroking(context.state());
173     cairo_stroke(context.platformContext()->cr());
174 }
175
176 GraphicsContext::GraphicsContext(cairo_t* cr)
177     : m_updatingControlTints(false)
178     , m_transparencyCount(0)
179 {
180     m_data = new GraphicsContextPlatformPrivateToplevel(new PlatformContextCairo(cr));
181 }
182
183 void GraphicsContext::platformInit(PlatformContextCairo* platformContext)
184 {
185     m_data = new GraphicsContextPlatformPrivate(platformContext);
186     if (platformContext)
187         m_data->syncContext(platformContext->cr());
188     else
189         setPaintingDisabled(true);
190 }
191
192 void GraphicsContext::platformDestroy()
193 {
194     delete m_data;
195 }
196
197 void GraphicsContext::resetPlatformCTM()
198 {
199     if (platformContext())
200         m_state.ctm = getPlatformCTM();
201     else
202         m_state.ctm.makeIdentity();
203 }
204
205 AffineTransform GraphicsContext::getPlatformCTM(IncludeDeviceScale) const
206 {
207     if (paintingDisabled())
208         return AffineTransform();
209
210     cairo_t* cr = platformContext()->cr();
211     cairo_matrix_t m;
212     cairo_get_matrix(cr, &m);
213     return AffineTransform(m.xx, m.yx, m.xy, m.yy, m.x0, m.y0);
214 }
215
216 PlatformContextCairo* GraphicsContext::platformContext() const
217 {
218     return m_data->platformContext;
219 }
220
221 void GraphicsContext::savePlatformState()
222 {
223     platformContext()->save();
224     m_data->save();
225 }
226
227 void GraphicsContext::restorePlatformState()
228 {
229     platformContext()->restore();
230     m_data->restore();
231
232     platformContext()->shadowBlur().setShadowValues(FloatSize(m_state.shadowBlur, m_state.shadowBlur),
233                                                     m_state.shadowOffset,
234                                                     m_state.shadowColor,
235                                                     m_state.shadowColorSpace,
236                                                     m_state.shadowsIgnoreTransforms);
237 }
238
239 // Draws a filled rectangle with a stroked border.
240 void GraphicsContext::drawRect(const FloatRect& rect, float)
241 {
242     if (paintingDisabled())
243         return;
244
245     ASSERT(!rect.isEmpty());
246
247     cairo_t* cr = platformContext()->cr();
248     cairo_save(cr);
249
250     fillRectWithColor(cr, rect, fillColor());
251
252     if (strokeStyle() != NoStroke) {
253         setSourceRGBAFromColor(cr, strokeColor());
254         FloatRect r(rect);
255         r.inflate(-.5f);
256         cairo_rectangle(cr, r.x(), r.y(), r.width(), r.height());
257         cairo_set_line_width(cr, 1.0);
258         cairo_stroke(cr);
259     }
260
261     cairo_restore(cr);
262 }
263
264 static double calculateStrokePatternOffset(int distance, int patternWidth)
265 {
266     // Example: 80 pixels with a width of 30 pixels. Remainder is 20.
267     // The maximum pixels of line we could paint will be 50 pixels.
268     int remainder = distance % patternWidth;
269     int numSegments = (distance - remainder) / patternWidth;
270
271     // Special case 1px dotted borders for speed.
272     if (patternWidth == 1)
273         return 1;
274
275     bool evenNumberOfSegments = !(numSegments % 2);
276     if (remainder)
277         evenNumberOfSegments = !evenNumberOfSegments;
278
279     if (evenNumberOfSegments) {
280         if (remainder)
281             return (patternWidth - remainder) + (remainder / 2);
282         return patternWidth / 2;
283     }
284
285     // Odd number of segments.
286     if (remainder)
287         return (patternWidth - remainder) / 2.f;
288     return 0;
289 }
290
291 static void drawLineOnCairoContext(GraphicsContext* graphicsContext, cairo_t* context, const FloatPoint& point1, const FloatPoint& point2)
292 {
293     StrokeStyle style = graphicsContext->strokeStyle();
294     if (style == NoStroke)
295         return;
296
297     const Color& strokeColor = graphicsContext->strokeColor();
298     int strokeThickness = floorf(graphicsContext->strokeThickness());
299     if (graphicsContext->strokeThickness() < 1)
300         strokeThickness = 1;
301
302     int patternWidth = 0;
303     if (style == DottedStroke)
304         patternWidth = strokeThickness;
305     else if (style == DashedStroke)
306         patternWidth = 3 * strokeThickness;
307
308     bool isVerticalLine = point1.x() == point2.x();
309     FloatPoint point1OnPixelBoundaries = point1;
310     FloatPoint point2OnPixelBoundaries = point2;
311     GraphicsContext::adjustLineToPixelBoundaries(point1OnPixelBoundaries, point2OnPixelBoundaries, strokeThickness, style);
312
313     if (patternWidth) {
314         // Do a rect fill of our endpoints.  This ensures we always have the
315         // appearance of being a border.  We then draw the actual dotted/dashed line.
316         FloatRect firstRect(point1OnPixelBoundaries, FloatSize(strokeThickness, strokeThickness));
317         FloatRect secondRect(point2OnPixelBoundaries, FloatSize(strokeThickness, strokeThickness));
318         if (isVerticalLine) {
319             firstRect.move(-strokeThickness / 2, -strokeThickness);
320             secondRect.move(-strokeThickness / 2, 0);
321         } else {
322             firstRect.move(-strokeThickness, -strokeThickness / 2);
323             secondRect.move(0, -strokeThickness / 2);
324         }
325         fillRectWithColor(context, firstRect, strokeColor);
326         fillRectWithColor(context, secondRect, strokeColor);
327
328         int distance = (isVerticalLine ? (point2.y() - point1.y()) : (point2.x() - point1.x())) - 2 * strokeThickness;
329         double patternOffset = calculateStrokePatternOffset(distance, patternWidth);
330         double patternWidthAsDouble = patternWidth;
331         cairo_set_dash(context, &patternWidthAsDouble, 1, patternOffset);
332     }
333
334     setSourceRGBAFromColor(context, strokeColor);
335     cairo_set_line_width(context, strokeThickness);
336     cairo_move_to(context, point1OnPixelBoundaries.x(), point1OnPixelBoundaries.y());
337     cairo_line_to(context, point2OnPixelBoundaries.x(), point2OnPixelBoundaries.y());
338     cairo_stroke(context);
339 }
340
341 // This is only used to draw borders, so we should not draw shadows.
342 void GraphicsContext::drawLine(const FloatPoint& point1, const FloatPoint& point2)
343 {
344     if (paintingDisabled())
345         return;
346
347     cairo_t* cairoContext = platformContext()->cr();
348     cairo_save(cairoContext);
349     drawLineOnCairoContext(this, cairoContext, point1, point2);
350     cairo_restore(cairoContext);
351 }
352
353 // This method is only used to draw the little circles used in lists.
354 void GraphicsContext::drawEllipse(const FloatRect& rect)
355 {
356     if (paintingDisabled())
357         return;
358
359     cairo_t* cr = platformContext()->cr();
360     cairo_save(cr);
361     float yRadius = .5 * rect.height();
362     float xRadius = .5 * rect.width();
363     cairo_translate(cr, rect.x() + xRadius, rect.y() + yRadius);
364     cairo_scale(cr, xRadius, yRadius);
365     cairo_arc(cr, 0., 0., 1., 0., 2 * piFloat);
366     cairo_restore(cr);
367
368     if (fillColor().alpha()) {
369         setSourceRGBAFromColor(cr, fillColor());
370         cairo_fill_preserve(cr);
371     }
372
373     if (strokeStyle() != NoStroke) {
374         setSourceRGBAFromColor(cr, strokeColor());
375         cairo_set_line_width(cr, strokeThickness());
376         cairo_stroke(cr);
377     } else
378         cairo_new_path(cr);
379 }
380
381 void GraphicsContext::drawConvexPolygon(size_t npoints, const FloatPoint* points, bool shouldAntialias)
382 {
383     if (paintingDisabled())
384         return;
385
386     if (npoints <= 1)
387         return;
388
389     cairo_t* cr = platformContext()->cr();
390
391     cairo_save(cr);
392     cairo_set_antialias(cr, shouldAntialias ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
393     addConvexPolygonToContext(cr, npoints, points);
394
395     if (fillColor().alpha()) {
396         setSourceRGBAFromColor(cr, fillColor());
397         cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
398         cairo_fill_preserve(cr);
399     }
400
401     if (strokeStyle() != NoStroke) {
402         setSourceRGBAFromColor(cr, strokeColor());
403         cairo_set_line_width(cr, strokeThickness());
404         cairo_stroke(cr);
405     } else
406         cairo_new_path(cr);
407
408     cairo_restore(cr);
409 }
410
411 void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
412 {
413     if (paintingDisabled())
414         return;
415
416     if (numPoints <= 1)
417         return;
418
419     cairo_t* cr = platformContext()->cr();
420
421     cairo_new_path(cr);
422     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
423     cairo_antialias_t savedAntialiasRule = cairo_get_antialias(cr);
424
425     cairo_set_antialias(cr, antialiased ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
426     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
427     addConvexPolygonToContext(cr, numPoints, points);
428     cairo_clip(cr);
429
430     cairo_set_antialias(cr, savedAntialiasRule);
431     cairo_set_fill_rule(cr, savedFillRule);
432 }
433
434 void GraphicsContext::fillPath(const Path& path)
435 {
436     if (paintingDisabled() || path.isEmpty())
437         return;
438
439     cairo_t* cr = platformContext()->cr();
440     setPathOnCairoContext(cr, path.platformPath()->context());
441     shadowAndFillCurrentCairoPath(*this);
442 }
443
444 void GraphicsContext::strokePath(const Path& path)
445 {
446     if (paintingDisabled() || path.isEmpty())
447         return;
448
449     cairo_t* cr = platformContext()->cr();
450     setPathOnCairoContext(cr, path.platformPath()->context());
451     shadowAndStrokeCurrentCairoPath(*this);
452 }
453
454 void GraphicsContext::fillRect(const FloatRect& rect)
455 {
456     if (paintingDisabled())
457         return;
458
459     cairo_t* cr = platformContext()->cr();
460     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
461     shadowAndFillCurrentCairoPath(*this);
462 }
463
464 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, ColorSpace)
465 {
466     if (paintingDisabled())
467         return;
468
469     if (hasShadow())
470         platformContext()->shadowBlur().drawRectShadow(*this, FloatRoundedRect(rect));
471
472     fillRectWithColor(platformContext()->cr(), rect, color);
473 }
474
475 void GraphicsContext::clip(const FloatRect& rect)
476 {
477     if (paintingDisabled())
478         return;
479
480     cairo_t* cr = platformContext()->cr();
481     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
482     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
483     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
484     // The rectangular clip function is traditionally not expected to
485     // antialias. If we don't force antialiased clipping here,
486     // edge fringe artifacts may occur at the layer edges
487     // when a transformation is applied to the GraphicsContext
488     // while drawing the transformed layer.
489     cairo_antialias_t savedAntialiasRule = cairo_get_antialias(cr);
490     cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
491     cairo_clip(cr);
492     cairo_set_fill_rule(cr, savedFillRule);
493     cairo_set_antialias(cr, savedAntialiasRule);
494     m_data->clip(rect);
495 }
496
497 void GraphicsContext::clipPath(const Path& path, WindRule clipRule)
498 {
499     if (paintingDisabled())
500         return;
501
502     cairo_t* cr = platformContext()->cr();
503     if (!path.isNull())
504         setPathOnCairoContext(cr, path.platformPath()->context());
505     cairo_set_fill_rule(cr, clipRule == RULE_EVENODD ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
506     cairo_clip(cr);
507 }
508
509 IntRect GraphicsContext::clipBounds() const
510 {
511     double x1, x2, y1, y2;
512     cairo_clip_extents(platformContext()->cr(), &x1, &y1, &x2, &y2);
513     return enclosingIntRect(FloatRect(x1, y1, x2 - x1, y2 - y1));
514 }
515
516 static inline void adjustFocusRingColor(Color& color)
517 {
518 #if !PLATFORM(GTK)
519     // Force the alpha to 50%.  This matches what the Mac does with outline rings.
520     color.setRGB(makeRGBA(color.red(), color.green(), color.blue(), 127));
521 #else
522     UNUSED_PARAM(color);
523 #endif
524 }
525
526 static inline void adjustFocusRingLineWidth(int& width)
527 {
528 #if PLATFORM(GTK)
529     width = 2;
530 #else
531     UNUSED_PARAM(width);
532 #endif
533 }
534
535 static inline StrokeStyle focusRingStrokeStyle()
536 {
537 #if PLATFORM(GTK)
538     return DottedStroke;
539 #else
540     return SolidStroke;
541 #endif
542 }
543
544 void GraphicsContext::drawFocusRing(const Path& path, int width, int /* offset */, const Color& color)
545 {
546     // FIXME: We should draw paths that describe a rectangle with rounded corners
547     // so as to be consistent with how we draw rectangular focus rings.
548     Color ringColor = color;
549     adjustFocusRingColor(ringColor);
550     adjustFocusRingLineWidth(width);
551
552     cairo_t* cr = platformContext()->cr();
553     cairo_save(cr);
554     appendWebCorePathToCairoContext(cr, path);
555     setSourceRGBAFromColor(cr, ringColor);
556     cairo_set_line_width(cr, width);
557     setPlatformStrokeStyle(focusRingStrokeStyle());
558     cairo_stroke(cr);
559     cairo_restore(cr);
560 }
561
562 void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int /* offset */, const Color& color)
563 {
564     if (paintingDisabled())
565         return;
566
567     cairo_t* cr = platformContext()->cr();
568     cairo_save(cr);
569     cairo_push_group(cr);
570     cairo_new_path(cr);
571
572 #if PLATFORM(GTK)
573     for (const auto& rect : rects)
574         cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
575 #else
576     unsigned rectCount = rects.size();
577     int radius = (width - 1) / 2;
578     Path path;
579     for (unsigned i = 0; i < rectCount; ++i) {
580         if (i > 0)
581             path.clear();
582         path.addRoundedRect(rects[i], FloatSize(radius, radius));
583         appendWebCorePathToCairoContext(cr, path);
584     }
585 #endif
586     Color ringColor = color;
587     adjustFocusRingColor(ringColor);
588     adjustFocusRingLineWidth(width);
589     setSourceRGBAFromColor(cr, ringColor);
590     cairo_set_line_width(cr, width);
591     setPlatformStrokeStyle(focusRingStrokeStyle());
592
593     cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
594     cairo_stroke_preserve(cr);
595
596     cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
597     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
598     cairo_fill(cr);
599
600     cairo_pop_group_to_source(cr);
601     cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
602     cairo_paint(cr);
603     cairo_restore(cr);
604 }
605
606 FloatRect GraphicsContext::computeLineBoundsForText(const FloatPoint& origin, float width, bool printing)
607 {
608     bool dummyBool;
609     Color dummyColor;
610     return computeLineBoundsAndAntialiasingModeForText(origin, width, printing, dummyBool, dummyColor);
611 }
612
613 void GraphicsContext::drawLineForText(const FloatPoint& origin, float width, bool printing, bool doubleUnderlines)
614 {
615     DashArray widths;
616     widths.append(width);
617     widths.append(0);
618     drawLinesForText(origin, widths, printing, doubleUnderlines);
619 }
620
621 void GraphicsContext::drawLinesForText(const FloatPoint& point, const DashArray& widths, bool printing, bool doubleUnderlines)
622 {
623     if (paintingDisabled())
624         return;
625
626     if (widths.size() <= 0)
627         return;
628
629     Color localStrokeColor(strokeColor());
630
631     bool shouldAntialiasLine;
632     FloatRect bounds = computeLineBoundsAndAntialiasingModeForText(point, widths.last(), printing, shouldAntialiasLine, localStrokeColor);
633
634     Vector<FloatRect, 4> dashBounds;
635     ASSERT(!(widths.size() % 2));
636     dashBounds.reserveInitialCapacity(dashBounds.size() / 2);
637     for (size_t i = 0; i < widths.size(); i += 2)
638         dashBounds.append(FloatRect(FloatPoint(bounds.x() + widths[i], bounds.y()), FloatSize(widths[i+1] - widths[i], bounds.height())));
639
640     if (doubleUnderlines) {
641         // The space between double underlines is equal to the height of the underline
642         for (size_t i = 0; i < widths.size(); i += 2)
643             dashBounds.append(FloatRect(FloatPoint(bounds.x() + widths[i], bounds.y() + 2 * bounds.height()), FloatSize(widths[i+1] - widths[i], bounds.height())));
644     }
645
646     cairo_t* cr = platformContext()->cr();
647     cairo_save(cr);
648
649     for (auto& dash : dashBounds)
650         fillRectWithColor(cr, dash, localStrokeColor);
651
652     cairo_restore(cr);
653 }
654
655 void GraphicsContext::updateDocumentMarkerResources()
656 {
657     // Unnecessary, since our document markers don't use resources.
658 }
659
660 void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& origin, float width, DocumentMarkerLineStyle style)
661 {
662     if (paintingDisabled())
663         return;
664
665     cairo_t* cr = platformContext()->cr();
666     cairo_save(cr);
667
668     switch (style) {
669     case DocumentMarkerSpellingLineStyle:
670         cairo_set_source_rgb(cr, 1, 0, 0);
671         break;
672     case DocumentMarkerGrammarLineStyle:
673         cairo_set_source_rgb(cr, 0, 1, 0);
674         break;
675     default:
676         cairo_restore(cr);
677         return;
678     }
679
680     drawErrorUnderline(cr, origin.x(), origin.y(), width, cMisspellingLineThickness);
681
682     cairo_restore(cr);
683 }
684
685 FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& frect, RoundingMode)
686 {
687     FloatRect result;
688     double x = frect.x();
689     double y = frect.y();
690     cairo_t* cr = platformContext()->cr();
691     cairo_user_to_device(cr, &x, &y);
692     x = round(x);
693     y = round(y);
694     cairo_device_to_user(cr, &x, &y);
695     result.setX(narrowPrecisionToFloat(x));
696     result.setY(narrowPrecisionToFloat(y));
697
698     // We must ensure width and height are at least 1 (or -1) when
699     // we're given float values in the range between 0 and 1 (or -1 and 0).
700     double width = frect.width();
701     double height = frect.height();
702     cairo_user_to_device_distance(cr, &width, &height);
703     if (width > -1 && width < 0)
704         width = -1;
705     else if (width > 0 && width < 1)
706         width = 1;
707     else
708         width = round(width);
709     if (height > -1 && width < 0)
710         height = -1;
711     else if (height > 0 && height < 1)
712         height = 1;
713     else
714         height = round(height);
715     cairo_device_to_user_distance(cr, &width, &height);
716     result.setWidth(narrowPrecisionToFloat(width));
717     result.setHeight(narrowPrecisionToFloat(height));
718
719     return result;
720 }
721
722 void GraphicsContext::translatePlatformCTM(float x, float y)
723 {
724     if (paintingDisabled())
725         return;
726
727     cairo_t* cr = platformContext()->cr();
728     cairo_translate(cr, x, y);
729     m_data->translate(x, y);
730 }
731
732 void GraphicsContext::setPlatformFillColor(const Color&, ColorSpace)
733 {
734     // Cairo contexts can't hold separate fill and stroke colors
735     // so we set them just before we actually fill or stroke
736 }
737
738 void GraphicsContext::setPlatformStrokeColor(const Color&, ColorSpace)
739 {
740     // Cairo contexts can't hold separate fill and stroke colors
741     // so we set them just before we actually fill or stroke
742 }
743
744 void GraphicsContext::setPlatformStrokeThickness(float strokeThickness)
745 {
746     if (paintingDisabled())
747         return;
748
749     cairo_set_line_width(platformContext()->cr(), strokeThickness);
750 }
751
752 void GraphicsContext::setPlatformStrokeStyle(StrokeStyle strokeStyle)
753 {
754     static const double dashPattern[] = { 5.0, 5.0 };
755     static const double dotPattern[] = { 1.0, 1.0 };
756
757     if (paintingDisabled())
758         return;
759
760     switch (strokeStyle) {
761     case NoStroke:
762         // FIXME: is it the right way to emulate NoStroke?
763         cairo_set_line_width(platformContext()->cr(), 0);
764         break;
765     case SolidStroke:
766     case DoubleStroke:
767     case WavyStroke: // FIXME: https://bugs.webkit.org/show_bug.cgi?id=94110 - Needs platform support.
768         cairo_set_dash(platformContext()->cr(), 0, 0, 0);
769         break;
770     case DottedStroke:
771         cairo_set_dash(platformContext()->cr(), dotPattern, 2, 0);
772         break;
773     case DashedStroke:
774         cairo_set_dash(platformContext()->cr(), dashPattern, 2, 0);
775         break;
776     }
777 }
778
779 void GraphicsContext::setURLForRect(const URL&, const IntRect&)
780 {
781     notImplemented();
782 }
783
784 void GraphicsContext::concatPlatformCTM(const AffineTransform& transform)
785 {
786     if (paintingDisabled())
787         return;
788
789     cairo_t* cr = platformContext()->cr();
790     const cairo_matrix_t matrix = cairo_matrix_t(transform);
791     cairo_transform(cr, &matrix);
792     m_data->concatCTM(transform);
793 }
794
795 void GraphicsContext::setPlatformCTM(const AffineTransform& transform)
796 {
797     if (paintingDisabled())
798         return;
799
800     cairo_t* cr = platformContext()->cr();
801     const cairo_matrix_t matrix = cairo_matrix_t(transform);
802     cairo_set_matrix(cr, &matrix);
803     m_data->setCTM(transform);
804 }
805
806 void GraphicsContext::setPlatformShadow(FloatSize const& size, float, Color const&, ColorSpace)
807 {
808     if (paintingDisabled())
809         return;
810
811     if (m_state.shadowsIgnoreTransforms) {
812         // Meaning that this graphics context is associated with a CanvasRenderingContext
813         // We flip the height since CG and HTML5 Canvas have opposite Y axis
814         m_state.shadowOffset = FloatSize(size.width(), -size.height());
815     }
816
817     // Cairo doesn't support shadows natively, they are drawn manually in the draw* functions using ShadowBlur.
818     platformContext()->shadowBlur().setShadowValues(FloatSize(m_state.shadowBlur, m_state.shadowBlur),
819                                                     m_state.shadowOffset,
820                                                     m_state.shadowColor,
821                                                     m_state.shadowColorSpace,
822                                                     m_state.shadowsIgnoreTransforms);
823 }
824
825 void GraphicsContext::clearPlatformShadow()
826 {
827     if (paintingDisabled())
828         return;
829
830     platformContext()->shadowBlur().clear();
831 }
832
833 void GraphicsContext::beginPlatformTransparencyLayer(float opacity)
834 {
835     if (paintingDisabled())
836         return;
837
838     cairo_t* cr = platformContext()->cr();
839     cairo_push_group(cr);
840     m_data->layers.append(opacity);
841 }
842
843 void GraphicsContext::endPlatformTransparencyLayer()
844 {
845     if (paintingDisabled())
846         return;
847
848     cairo_t* cr = platformContext()->cr();
849
850     cairo_pop_group_to_source(cr);
851     cairo_paint_with_alpha(cr, m_data->layers.last());
852     m_data->layers.removeLast();
853 }
854
855 bool GraphicsContext::supportsTransparencyLayers()
856 {
857     return true;
858 }
859
860 void GraphicsContext::clearRect(const FloatRect& rect)
861 {
862     if (paintingDisabled())
863         return;
864
865     cairo_t* cr = platformContext()->cr();
866
867     cairo_save(cr);
868     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
869     cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
870     cairo_fill(cr);
871     cairo_restore(cr);
872 }
873
874 void GraphicsContext::strokeRect(const FloatRect& rect, float width)
875 {
876     if (paintingDisabled())
877         return;
878
879     cairo_t* cr = platformContext()->cr();
880     cairo_save(cr);
881     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
882     cairo_set_line_width(cr, width);
883     shadowAndStrokeCurrentCairoPath(*this);
884     cairo_restore(cr);
885 }
886
887 void GraphicsContext::setLineCap(LineCap lineCap)
888 {
889     if (paintingDisabled())
890         return;
891
892     cairo_line_cap_t cairoCap = CAIRO_LINE_CAP_BUTT;
893     switch (lineCap) {
894     case ButtCap:
895         // no-op
896         break;
897     case RoundCap:
898         cairoCap = CAIRO_LINE_CAP_ROUND;
899         break;
900     case SquareCap:
901         cairoCap = CAIRO_LINE_CAP_SQUARE;
902         break;
903     }
904     cairo_set_line_cap(platformContext()->cr(), cairoCap);
905 }
906
907 static inline bool isDashArrayAllZero(const DashArray& dashes)
908 {
909     for (auto& dash : dashes) {
910         if (dash)
911             return false;
912     }
913     return true;
914 }
915
916 void GraphicsContext::setLineDash(const DashArray& dashes, float dashOffset)
917 {
918     if (isDashArrayAllZero(dashes))
919         cairo_set_dash(platformContext()->cr(), 0, 0, 0);
920     else
921         cairo_set_dash(platformContext()->cr(), dashes.data(), dashes.size(), dashOffset);
922 }
923
924 void GraphicsContext::setLineJoin(LineJoin lineJoin)
925 {
926     if (paintingDisabled())
927         return;
928
929     cairo_line_join_t cairoJoin = CAIRO_LINE_JOIN_MITER;
930     switch (lineJoin) {
931     case MiterJoin:
932         // no-op
933         break;
934     case RoundJoin:
935         cairoJoin = CAIRO_LINE_JOIN_ROUND;
936         break;
937     case BevelJoin:
938         cairoJoin = CAIRO_LINE_JOIN_BEVEL;
939         break;
940     }
941     cairo_set_line_join(platformContext()->cr(), cairoJoin);
942 }
943
944 void GraphicsContext::setMiterLimit(float miter)
945 {
946     if (paintingDisabled())
947         return;
948
949     cairo_set_miter_limit(platformContext()->cr(), miter);
950 }
951
952 void GraphicsContext::setPlatformAlpha(float alpha)
953 {
954     platformContext()->setGlobalAlpha(alpha);
955 }
956
957 void GraphicsContext::setPlatformCompositeOperation(CompositeOperator op, BlendMode blendOp)
958 {
959     if (paintingDisabled())
960         return;
961
962     cairo_operator_t cairo_op;
963     if (blendOp == BlendModeNormal)
964         cairo_op = toCairoOperator(op);
965     else
966         cairo_op = toCairoOperator(blendOp);
967
968     cairo_set_operator(platformContext()->cr(), cairo_op);
969 }
970
971 void GraphicsContext::clip(const Path& path, WindRule windRule)
972 {
973     if (paintingDisabled())
974         return;
975
976     cairo_t* cr = platformContext()->cr();
977     if (!path.isNull()) {
978         cairo_path_t* pathCopy = cairo_copy_path(path.platformPath()->context());
979         cairo_append_path(cr, pathCopy);
980         cairo_path_destroy(pathCopy);
981     }
982     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
983     if (windRule == RULE_NONZERO)
984         cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
985     else
986         cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
987     cairo_clip(cr);
988     cairo_set_fill_rule(cr, savedFillRule);
989     m_data->clip(path);
990 }
991
992 void GraphicsContext::canvasClip(const Path& path, WindRule windRule)
993 {
994     clip(path, windRule);
995 }
996
997 void GraphicsContext::clipOut(const Path& path)
998 {
999     if (paintingDisabled())
1000         return;
1001
1002     cairo_t* cr = platformContext()->cr();
1003     double x1, y1, x2, y2;
1004     cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
1005     cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
1006     appendWebCorePathToCairoContext(cr, path);
1007
1008     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
1009     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
1010     cairo_clip(cr);
1011     cairo_set_fill_rule(cr, savedFillRule);
1012 }
1013
1014 void GraphicsContext::rotatePlatformCTM(float radians)
1015 {
1016     if (paintingDisabled())
1017         return;
1018
1019     cairo_rotate(platformContext()->cr(), radians);
1020     m_data->rotate(radians);
1021 }
1022
1023 void GraphicsContext::scalePlatformCTM(float x, float y)
1024 {
1025     if (paintingDisabled())
1026         return;
1027
1028     cairo_scale(platformContext()->cr(), x, y);
1029     m_data->scale(FloatSize(x, y));
1030 }
1031
1032 void GraphicsContext::clipOut(const FloatRect& r)
1033 {
1034     if (paintingDisabled())
1035         return;
1036
1037     cairo_t* cr = platformContext()->cr();
1038     double x1, y1, x2, y2;
1039     cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
1040     cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
1041     cairo_rectangle(cr, r.x(), r.y(), r.width(), r.height());
1042     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
1043     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
1044     cairo_clip(cr);
1045     cairo_set_fill_rule(cr, savedFillRule);
1046 }
1047
1048 void GraphicsContext::platformFillRoundedRect(const FloatRoundedRect& rect, const Color& color, ColorSpace)
1049 {
1050     if (paintingDisabled())
1051         return;
1052
1053     if (hasShadow())
1054         platformContext()->shadowBlur().drawRectShadow(*this, rect);
1055
1056     cairo_t* cr = platformContext()->cr();
1057     cairo_save(cr);
1058     Path path;
1059     path.addRoundedRect(rect);
1060     appendWebCorePathToCairoContext(cr, path);
1061     setSourceRGBAFromColor(cr, color);
1062     cairo_fill(cr);
1063     cairo_restore(cr);
1064 }
1065
1066 void GraphicsContext::fillRectWithRoundedHole(const FloatRect& rect, const FloatRoundedRect& roundedHoleRect, const Color& color, ColorSpace)
1067 {
1068     if (paintingDisabled() || !color.isValid())
1069         return;
1070
1071     if (this->mustUseShadowBlur())
1072         platformContext()->shadowBlur().drawInsetShadow(*this, rect, roundedHoleRect);
1073
1074     Path path;
1075     path.addRect(rect);
1076     if (!roundedHoleRect.radii().isZero())
1077         path.addRoundedRect(roundedHoleRect);
1078     else
1079         path.addRect(roundedHoleRect.rect());
1080
1081     cairo_t* cr = platformContext()->cr();
1082     cairo_save(cr);
1083     setPathOnCairoContext(platformContext()->cr(), path.platformPath()->context());
1084     fillCurrentCairoPath(*this);
1085     cairo_restore(cr);
1086 }
1087
1088 void GraphicsContext::drawPattern(Image& image, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, const FloatSize&, ColorSpace, CompositeOperator op, const FloatRect& destRect, BlendMode)
1089 {
1090     RefPtr<cairo_surface_t> surface = image.nativeImageForCurrentFrame();
1091     if (!surface) // If it's too early we won't have an image yet.
1092         return;
1093
1094     cairo_t* cr = platformContext()->cr();
1095     drawPatternToCairoContext(cr, surface.get(), IntSize(image.size()), tileRect, patternTransform, phase, toCairoOperator(op), destRect);
1096 }
1097
1098 void GraphicsContext::setPlatformShouldAntialias(bool enable)
1099 {
1100     if (paintingDisabled())
1101         return;
1102
1103     // When true, use the default Cairo backend antialias mode (usually this
1104     // enables standard 'grayscale' antialiasing); false to explicitly disable
1105     // antialiasing. This is the same strategy as used in drawConvexPolygon().
1106     cairo_set_antialias(platformContext()->cr(), enable ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
1107 }
1108
1109 void GraphicsContext::setImageInterpolationQuality(InterpolationQuality quality)
1110 {
1111     platformContext()->setImageInterpolationQuality(quality);
1112 }
1113
1114 InterpolationQuality GraphicsContext::imageInterpolationQuality() const
1115 {
1116     return platformContext()->imageInterpolationQuality();
1117 }
1118
1119 bool GraphicsContext::isAcceleratedContext() const
1120 {
1121     return cairo_surface_get_type(cairo_get_target(platformContext()->cr())) == CAIRO_SURFACE_TYPE_GL;
1122 }
1123
1124 #if ENABLE(3D_TRANSFORMS) && USE(TEXTURE_MAPPER)
1125 TransformationMatrix GraphicsContext::get3DTransform() const
1126 {
1127     // FIXME: Can we approximate the transformation better than this?
1128     return getCTM().toTransformationMatrix();
1129 }
1130
1131 void GraphicsContext::concat3DTransform(const TransformationMatrix& transform)
1132 {
1133     concatCTM(transform.toAffineTransform());
1134 }
1135
1136 void GraphicsContext::set3DTransform(const TransformationMatrix& transform)
1137 {
1138     setCTM(transform.toAffineTransform());
1139 }
1140 #endif // ENABLE(3D_TRANSFORMS) && USE(TEXTURE_MAPPER)
1141
1142 } // namespace WebCore
1143
1144 #endif // USE(CAIRO)