[cairo] Solid stroke of lines with thickness less than 1 pixel broken after r191658
[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 AffineTransform GraphicsContext::getCTM(IncludeDeviceScale) const
198 {
199     if (paintingDisabled())
200         return AffineTransform();
201
202     cairo_t* cr = platformContext()->cr();
203     cairo_matrix_t m;
204     cairo_get_matrix(cr, &m);
205     return AffineTransform(m.xx, m.yx, m.xy, m.yy, m.x0, m.y0);
206 }
207
208 PlatformContextCairo* GraphicsContext::platformContext() const
209 {
210     return m_data->platformContext;
211 }
212
213 void GraphicsContext::savePlatformState()
214 {
215     platformContext()->save();
216     m_data->save();
217 }
218
219 void GraphicsContext::restorePlatformState()
220 {
221     platformContext()->restore();
222     m_data->restore();
223
224     platformContext()->shadowBlur().setShadowValues(FloatSize(m_state.shadowBlur, m_state.shadowBlur),
225                                                     m_state.shadowOffset,
226                                                     m_state.shadowColor,
227                                                     m_state.shadowsIgnoreTransforms);
228 }
229
230 // Draws a filled rectangle with a stroked border.
231 void GraphicsContext::drawRect(const FloatRect& rect, float)
232 {
233     if (paintingDisabled())
234         return;
235
236     ASSERT(!rect.isEmpty());
237
238     cairo_t* cr = platformContext()->cr();
239     cairo_save(cr);
240
241     fillRectWithColor(cr, rect, fillColor());
242
243     if (strokeStyle() != NoStroke) {
244         setSourceRGBAFromColor(cr, strokeColor());
245         FloatRect r(rect);
246         r.inflate(-.5f);
247         cairo_rectangle(cr, r.x(), r.y(), r.width(), r.height());
248         cairo_set_line_width(cr, 1.0);
249         cairo_stroke(cr);
250     }
251
252     cairo_restore(cr);
253 }
254
255 // This is only used to draw borders, so we should not draw shadows.
256 void GraphicsContext::drawLine(const FloatPoint& point1, const FloatPoint& point2)
257 {
258     if (paintingDisabled())
259         return;
260
261     if (strokeStyle() == NoStroke)
262         return;
263
264     const Color& strokeColor = this->strokeColor();
265     float thickness = strokeThickness();
266     bool isVerticalLine = (point1.x() + thickness == point2.x());
267     float strokeWidth = isVerticalLine ? point2.y() - point1.y() : point2.x() - point1.x();
268     if (!thickness || !strokeWidth)
269         return;
270
271     cairo_t* cairoContext = platformContext()->cr();
272     StrokeStyle strokeStyle = this->strokeStyle();
273     float cornerWidth = 0;
274     bool drawsDashedLine = strokeStyle == DottedStroke || strokeStyle == DashedStroke;
275
276     if (drawsDashedLine) {
277         cairo_save(cairoContext);
278         // Figure out end points to ensure we always paint corners.
279         cornerWidth = strokeStyle == DottedStroke ? thickness : std::min(2 * thickness, std::max(thickness, strokeWidth / 3));
280         if (isVerticalLine) {
281             fillRectWithColor(cairoContext, FloatRect(point1.x(), point1.y(), thickness, cornerWidth), strokeColor);
282             fillRectWithColor(cairoContext, FloatRect(point1.x(), point2.y() - cornerWidth, thickness, cornerWidth), strokeColor);
283         } else {
284             fillRectWithColor(cairoContext, FloatRect(point1.x(), point1.y(), cornerWidth, thickness), strokeColor);
285             fillRectWithColor(cairoContext, FloatRect(point2.x() - cornerWidth, point1.y(), cornerWidth, thickness), strokeColor);
286         }
287         strokeWidth -= 2 * cornerWidth;
288         float patternWidth = strokeStyle == DottedStroke ? thickness : std::min(3 * thickness, std::max(thickness, strokeWidth / 3));
289         // Check if corner drawing sufficiently covers the line.
290         if (strokeWidth <= patternWidth + 1) {
291             cairo_restore(cairoContext);
292             return;
293         }
294
295         // Pattern starts with full fill and ends with the empty fill.
296         // 1. Let's start with the empty phase after the corner.
297         // 2. Check if we've got odd or even number of patterns and whether they fully cover the line.
298         // 3. In case of even number of patterns and/or remainder, move the pattern start position
299         // so that the pattern is balanced between the corners.
300         float patternOffset = patternWidth;
301         int numberOfSegments = std::floor(strokeWidth / patternWidth);
302         bool oddNumberOfSegments = numberOfSegments % 2;
303         float remainder = strokeWidth - (numberOfSegments * patternWidth);
304         if (oddNumberOfSegments && remainder)
305             patternOffset -= remainder / 2.f;
306         else if (!oddNumberOfSegments) {
307             if (remainder)
308                 patternOffset += patternOffset - (patternWidth + remainder) / 2.f;
309             else
310                 patternOffset += patternWidth / 2.f;
311         }
312         const double dashedLine[2] = { static_cast<double>(patternWidth), static_cast<double>(patternWidth) };
313         cairo_set_dash(cairoContext, dashedLine, 2, patternOffset);
314     } else {
315         setSourceRGBAFromColor(cairoContext, strokeColor);
316         if (thickness < 1)
317             cairo_set_line_width(cairoContext, 1);
318     }
319
320
321     FloatPoint p1 = point1;
322     FloatPoint p2 = point2;
323     // Center line and cut off corners for pattern patining.
324     if (isVerticalLine) {
325         float centerOffset = (p2.x() - p1.x()) / 2;
326         p1.move(centerOffset, cornerWidth);
327         p2.move(-centerOffset, -cornerWidth);
328     } else {
329         float centerOffset = (p2.y() - p1.y()) / 2;
330         p1.move(cornerWidth, centerOffset);
331         p2.move(-cornerWidth, -centerOffset);
332     }
333
334     if (shouldAntialias())
335         cairo_set_antialias(cairoContext, CAIRO_ANTIALIAS_NONE);
336
337     cairo_new_path(cairoContext);
338     cairo_move_to(cairoContext, p1.x(), p1.y());
339     cairo_line_to(cairoContext, p2.x(), p2.y());
340     cairo_stroke(cairoContext);
341     if (drawsDashedLine)
342         cairo_restore(cairoContext);
343     if (shouldAntialias())
344         cairo_set_antialias(cairoContext, CAIRO_ANTIALIAS_DEFAULT);
345 }
346
347 // This method is only used to draw the little circles used in lists.
348 void GraphicsContext::drawEllipse(const FloatRect& rect)
349 {
350     if (paintingDisabled())
351         return;
352
353     cairo_t* cr = platformContext()->cr();
354     cairo_save(cr);
355     float yRadius = .5 * rect.height();
356     float xRadius = .5 * rect.width();
357     cairo_translate(cr, rect.x() + xRadius, rect.y() + yRadius);
358     cairo_scale(cr, xRadius, yRadius);
359     cairo_arc(cr, 0., 0., 1., 0., 2 * piFloat);
360     cairo_restore(cr);
361
362     if (fillColor().alpha()) {
363         setSourceRGBAFromColor(cr, fillColor());
364         cairo_fill_preserve(cr);
365     }
366
367     if (strokeStyle() != NoStroke) {
368         setSourceRGBAFromColor(cr, strokeColor());
369         cairo_set_line_width(cr, strokeThickness());
370         cairo_stroke(cr);
371     } else
372         cairo_new_path(cr);
373 }
374
375 void GraphicsContext::drawConvexPolygon(size_t npoints, const FloatPoint* points, bool shouldAntialias)
376 {
377     if (paintingDisabled())
378         return;
379
380     if (npoints <= 1)
381         return;
382
383     cairo_t* cr = platformContext()->cr();
384
385     cairo_save(cr);
386     cairo_set_antialias(cr, shouldAntialias ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
387     addConvexPolygonToContext(cr, npoints, points);
388
389     if (fillColor().alpha()) {
390         setSourceRGBAFromColor(cr, fillColor());
391         cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
392         cairo_fill_preserve(cr);
393     }
394
395     if (strokeStyle() != NoStroke) {
396         setSourceRGBAFromColor(cr, strokeColor());
397         cairo_set_line_width(cr, strokeThickness());
398         cairo_stroke(cr);
399     } else
400         cairo_new_path(cr);
401
402     cairo_restore(cr);
403 }
404
405 void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
406 {
407     if (paintingDisabled())
408         return;
409
410     if (numPoints <= 1)
411         return;
412
413     cairo_t* cr = platformContext()->cr();
414
415     cairo_new_path(cr);
416     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
417     cairo_antialias_t savedAntialiasRule = cairo_get_antialias(cr);
418
419     cairo_set_antialias(cr, antialiased ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
420     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
421     addConvexPolygonToContext(cr, numPoints, points);
422     cairo_clip(cr);
423
424     cairo_set_antialias(cr, savedAntialiasRule);
425     cairo_set_fill_rule(cr, savedFillRule);
426 }
427
428 void GraphicsContext::fillPath(const Path& path)
429 {
430     if (paintingDisabled() || path.isEmpty())
431         return;
432
433     cairo_t* cr = platformContext()->cr();
434     setPathOnCairoContext(cr, path.platformPath()->context());
435     shadowAndFillCurrentCairoPath(*this);
436 }
437
438 void GraphicsContext::strokePath(const Path& path)
439 {
440     if (paintingDisabled() || path.isEmpty())
441         return;
442
443     cairo_t* cr = platformContext()->cr();
444     setPathOnCairoContext(cr, path.platformPath()->context());
445     shadowAndStrokeCurrentCairoPath(*this);
446 }
447
448 void GraphicsContext::fillRect(const FloatRect& rect)
449 {
450     if (paintingDisabled())
451         return;
452
453     cairo_t* cr = platformContext()->cr();
454     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
455     shadowAndFillCurrentCairoPath(*this);
456 }
457
458 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color)
459 {
460     if (paintingDisabled())
461         return;
462
463     if (hasShadow())
464         platformContext()->shadowBlur().drawRectShadow(*this, FloatRoundedRect(rect));
465
466     fillRectWithColor(platformContext()->cr(), rect, color);
467 }
468
469 void GraphicsContext::clip(const FloatRect& rect)
470 {
471     if (paintingDisabled())
472         return;
473
474     cairo_t* cr = platformContext()->cr();
475     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
476     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
477     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
478     // The rectangular clip function is traditionally not expected to
479     // antialias. If we don't force antialiased clipping here,
480     // edge fringe artifacts may occur at the layer edges
481     // when a transformation is applied to the GraphicsContext
482     // while drawing the transformed layer.
483     cairo_antialias_t savedAntialiasRule = cairo_get_antialias(cr);
484     cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
485     cairo_clip(cr);
486     cairo_set_fill_rule(cr, savedFillRule);
487     cairo_set_antialias(cr, savedAntialiasRule);
488     m_data->clip(rect);
489 }
490
491 void GraphicsContext::clipPath(const Path& path, WindRule clipRule)
492 {
493     if (paintingDisabled())
494         return;
495
496     cairo_t* cr = platformContext()->cr();
497     if (!path.isNull())
498         setPathOnCairoContext(cr, path.platformPath()->context());
499
500     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
501     cairo_set_fill_rule(cr, clipRule == RULE_EVENODD ? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING);
502     cairo_clip(cr);
503     cairo_set_fill_rule(cr, savedFillRule);
504
505     m_data->clip(path);
506 }
507
508 IntRect GraphicsContext::clipBounds() const
509 {
510     double x1, x2, y1, y2;
511     cairo_clip_extents(platformContext()->cr(), &x1, &y1, &x2, &y2);
512     return enclosingIntRect(FloatRect(x1, y1, x2 - x1, y2 - y1));
513 }
514
515 static inline void adjustFocusRingColor(Color& color)
516 {
517 #if !PLATFORM(GTK)
518     // Force the alpha to 50%.  This matches what the Mac does with outline rings.
519     color.setRGB(makeRGBA(color.red(), color.green(), color.blue(), 127));
520 #else
521     UNUSED_PARAM(color);
522 #endif
523 }
524
525 static inline void adjustFocusRingLineWidth(int& width)
526 {
527 #if PLATFORM(GTK)
528     width = 2;
529 #else
530     UNUSED_PARAM(width);
531 #endif
532 }
533
534 static inline StrokeStyle focusRingStrokeStyle()
535 {
536 #if PLATFORM(GTK)
537     return DottedStroke;
538 #else
539     return SolidStroke;
540 #endif
541 }
542
543 void GraphicsContext::drawFocusRing(const Path& path, int width, int /* offset */, const Color& color)
544 {
545     // FIXME: We should draw paths that describe a rectangle with rounded corners
546     // so as to be consistent with how we draw rectangular focus rings.
547     Color ringColor = color;
548     adjustFocusRingColor(ringColor);
549     adjustFocusRingLineWidth(width);
550
551     cairo_t* cr = platformContext()->cr();
552     cairo_save(cr);
553     appendWebCorePathToCairoContext(cr, path);
554     setSourceRGBAFromColor(cr, ringColor);
555     cairo_set_line_width(cr, width);
556     setPlatformStrokeStyle(focusRingStrokeStyle());
557     cairo_stroke(cr);
558     cairo_restore(cr);
559 }
560
561 void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int /* offset */, const Color& color)
562 {
563     if (paintingDisabled())
564         return;
565
566     cairo_t* cr = platformContext()->cr();
567     cairo_save(cr);
568     cairo_push_group(cr);
569     cairo_new_path(cr);
570
571 #if PLATFORM(GTK)
572     for (const auto& rect : rects)
573         cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
574 #else
575     unsigned rectCount = rects.size();
576     int radius = (width - 1) / 2;
577     Path path;
578     for (unsigned i = 0; i < rectCount; ++i) {
579         if (i > 0)
580             path.clear();
581         path.addRoundedRect(rects[i], FloatSize(radius, radius));
582         appendWebCorePathToCairoContext(cr, path);
583     }
584 #endif
585     Color ringColor = color;
586     adjustFocusRingColor(ringColor);
587     adjustFocusRingLineWidth(width);
588     setSourceRGBAFromColor(cr, ringColor);
589     cairo_set_line_width(cr, width);
590     setPlatformStrokeStyle(focusRingStrokeStyle());
591
592     cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
593     cairo_stroke_preserve(cr);
594
595     cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
596     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_WINDING);
597     cairo_fill(cr);
598
599     cairo_pop_group_to_source(cr);
600     cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
601     cairo_paint(cr);
602     cairo_restore(cr);
603 }
604
605 FloatRect GraphicsContext::computeLineBoundsForText(const FloatPoint& origin, float width, bool printing)
606 {
607     bool dummyBool;
608     Color dummyColor;
609     return computeLineBoundsAndAntialiasingModeForText(origin, width, printing, dummyBool, dummyColor);
610 }
611
612 void GraphicsContext::drawLineForText(const FloatPoint& origin, float width, bool printing, bool doubleUnderlines)
613 {
614     DashArray widths;
615     widths.append(width);
616     widths.append(0);
617     drawLinesForText(origin, widths, printing, doubleUnderlines);
618 }
619
620 void GraphicsContext::drawLinesForText(const FloatPoint& point, const DashArray& widths, bool printing, bool doubleUnderlines)
621 {
622     if (paintingDisabled())
623         return;
624
625     if (widths.size() <= 0)
626         return;
627
628     Color localStrokeColor(strokeColor());
629
630     bool shouldAntialiasLine;
631     FloatRect bounds = computeLineBoundsAndAntialiasingModeForText(point, widths.last(), printing, shouldAntialiasLine, localStrokeColor);
632
633     Vector<FloatRect, 4> dashBounds;
634     ASSERT(!(widths.size() % 2));
635     dashBounds.reserveInitialCapacity(dashBounds.size() / 2);
636     for (size_t i = 0; i < widths.size(); i += 2)
637         dashBounds.append(FloatRect(FloatPoint(bounds.x() + widths[i], bounds.y()), FloatSize(widths[i+1] - widths[i], bounds.height())));
638
639     if (doubleUnderlines) {
640         // The space between double underlines is equal to the height of the underline
641         for (size_t i = 0; i < widths.size(); i += 2)
642             dashBounds.append(FloatRect(FloatPoint(bounds.x() + widths[i], bounds.y() + 2 * bounds.height()), FloatSize(widths[i+1] - widths[i], bounds.height())));
643     }
644
645     cairo_t* cr = platformContext()->cr();
646     cairo_save(cr);
647
648     for (auto& dash : dashBounds)
649         fillRectWithColor(cr, dash, localStrokeColor);
650
651     cairo_restore(cr);
652 }
653
654 void GraphicsContext::updateDocumentMarkerResources()
655 {
656     // Unnecessary, since our document markers don't use resources.
657 }
658
659 void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& origin, float width, DocumentMarkerLineStyle style)
660 {
661     if (paintingDisabled())
662         return;
663
664     cairo_t* cr = platformContext()->cr();
665     cairo_save(cr);
666
667     switch (style) {
668     case DocumentMarkerSpellingLineStyle:
669         cairo_set_source_rgb(cr, 1, 0, 0);
670         break;
671     case DocumentMarkerGrammarLineStyle:
672         cairo_set_source_rgb(cr, 0, 1, 0);
673         break;
674     default:
675         cairo_restore(cr);
676         return;
677     }
678
679     drawErrorUnderline(cr, origin.x(), origin.y(), width, cMisspellingLineThickness);
680
681     cairo_restore(cr);
682 }
683
684 FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& frect, RoundingMode)
685 {
686     FloatRect result;
687     double x = frect.x();
688     double y = frect.y();
689     cairo_t* cr = platformContext()->cr();
690     cairo_user_to_device(cr, &x, &y);
691     x = round(x);
692     y = round(y);
693     cairo_device_to_user(cr, &x, &y);
694     result.setX(narrowPrecisionToFloat(x));
695     result.setY(narrowPrecisionToFloat(y));
696
697     // We must ensure width and height are at least 1 (or -1) when
698     // we're given float values in the range between 0 and 1 (or -1 and 0).
699     double width = frect.width();
700     double height = frect.height();
701     cairo_user_to_device_distance(cr, &width, &height);
702     if (width > -1 && width < 0)
703         width = -1;
704     else if (width > 0 && width < 1)
705         width = 1;
706     else
707         width = round(width);
708     if (height > -1 && width < 0)
709         height = -1;
710     else if (height > 0 && height < 1)
711         height = 1;
712     else
713         height = round(height);
714     cairo_device_to_user_distance(cr, &width, &height);
715     result.setWidth(narrowPrecisionToFloat(width));
716     result.setHeight(narrowPrecisionToFloat(height));
717
718     return result;
719 }
720
721 void GraphicsContext::translate(float x, float y)
722 {
723     if (paintingDisabled())
724         return;
725
726     cairo_t* cr = platformContext()->cr();
727     cairo_translate(cr, x, y);
728     m_data->translate(x, y);
729 }
730
731 void GraphicsContext::setPlatformFillColor(const Color&)
732 {
733     // Cairo contexts can't hold separate fill and stroke colors
734     // so we set them just before we actually fill or stroke
735 }
736
737 void GraphicsContext::setPlatformStrokeColor(const Color&)
738 {
739     // Cairo contexts can't hold separate fill and stroke colors
740     // so we set them just before we actually fill or stroke
741 }
742
743 void GraphicsContext::setPlatformStrokeThickness(float strokeThickness)
744 {
745     if (paintingDisabled())
746         return;
747
748     cairo_set_line_width(platformContext()->cr(), strokeThickness);
749 }
750
751 void GraphicsContext::setPlatformStrokeStyle(StrokeStyle strokeStyle)
752 {
753     static const double dashPattern[] = { 5.0, 5.0 };
754     static const double dotPattern[] = { 1.0, 1.0 };
755
756     if (paintingDisabled())
757         return;
758
759     switch (strokeStyle) {
760     case NoStroke:
761         // FIXME: is it the right way to emulate NoStroke?
762         cairo_set_line_width(platformContext()->cr(), 0);
763         break;
764     case SolidStroke:
765     case DoubleStroke:
766     case WavyStroke: // FIXME: https://bugs.webkit.org/show_bug.cgi?id=94110 - Needs platform support.
767         cairo_set_dash(platformContext()->cr(), 0, 0, 0);
768         break;
769     case DottedStroke:
770         cairo_set_dash(platformContext()->cr(), dotPattern, 2, 0);
771         break;
772     case DashedStroke:
773         cairo_set_dash(platformContext()->cr(), dashPattern, 2, 0);
774         break;
775     }
776 }
777
778 void GraphicsContext::setURLForRect(const URL&, const IntRect&)
779 {
780     notImplemented();
781 }
782
783 void GraphicsContext::concatCTM(const AffineTransform& transform)
784 {
785     if (paintingDisabled())
786         return;
787
788     cairo_t* cr = platformContext()->cr();
789     const cairo_matrix_t matrix = cairo_matrix_t(transform);
790     cairo_transform(cr, &matrix);
791     m_data->concatCTM(transform);
792 }
793
794 void GraphicsContext::setCTM(const AffineTransform& transform)
795 {
796     if (paintingDisabled())
797         return;
798
799     cairo_t* cr = platformContext()->cr();
800     const cairo_matrix_t matrix = cairo_matrix_t(transform);
801     cairo_set_matrix(cr, &matrix);
802     m_data->setCTM(transform);
803 }
804
805 void GraphicsContext::setPlatformShadow(FloatSize const& size, float, Color const&)
806 {
807     if (paintingDisabled())
808         return;
809
810     if (m_state.shadowsIgnoreTransforms) {
811         // Meaning that this graphics context is associated with a CanvasRenderingContext
812         // We flip the height since CG and HTML5 Canvas have opposite Y axis
813         m_state.shadowOffset = FloatSize(size.width(), -size.height());
814     }
815
816     // Cairo doesn't support shadows natively, they are drawn manually in the draw* functions using ShadowBlur.
817     platformContext()->shadowBlur().setShadowValues(FloatSize(m_state.shadowBlur, m_state.shadowBlur),
818                                                     m_state.shadowOffset,
819                                                     m_state.shadowColor,
820                                                     m_state.shadowsIgnoreTransforms);
821 }
822
823 void GraphicsContext::clearPlatformShadow()
824 {
825     if (paintingDisabled())
826         return;
827
828     platformContext()->shadowBlur().clear();
829 }
830
831 void GraphicsContext::beginPlatformTransparencyLayer(float opacity)
832 {
833     if (paintingDisabled())
834         return;
835
836     cairo_t* cr = platformContext()->cr();
837     cairo_push_group(cr);
838     m_data->layers.append(opacity);
839 }
840
841 void GraphicsContext::endPlatformTransparencyLayer()
842 {
843     if (paintingDisabled())
844         return;
845
846     cairo_t* cr = platformContext()->cr();
847
848     cairo_pop_group_to_source(cr);
849     cairo_paint_with_alpha(cr, m_data->layers.last());
850     m_data->layers.removeLast();
851 }
852
853 bool GraphicsContext::supportsTransparencyLayers()
854 {
855     return true;
856 }
857
858 void GraphicsContext::clearRect(const FloatRect& rect)
859 {
860     if (paintingDisabled())
861         return;
862
863     cairo_t* cr = platformContext()->cr();
864
865     cairo_save(cr);
866     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
867     cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR);
868     cairo_fill(cr);
869     cairo_restore(cr);
870 }
871
872 void GraphicsContext::strokeRect(const FloatRect& rect, float width)
873 {
874     if (paintingDisabled())
875         return;
876
877     cairo_t* cr = platformContext()->cr();
878     cairo_save(cr);
879     cairo_rectangle(cr, rect.x(), rect.y(), rect.width(), rect.height());
880     cairo_set_line_width(cr, width);
881     shadowAndStrokeCurrentCairoPath(*this);
882     cairo_restore(cr);
883 }
884
885 void GraphicsContext::setLineCap(LineCap lineCap)
886 {
887     if (paintingDisabled())
888         return;
889
890     cairo_line_cap_t cairoCap = CAIRO_LINE_CAP_BUTT;
891     switch (lineCap) {
892     case ButtCap:
893         // no-op
894         break;
895     case RoundCap:
896         cairoCap = CAIRO_LINE_CAP_ROUND;
897         break;
898     case SquareCap:
899         cairoCap = CAIRO_LINE_CAP_SQUARE;
900         break;
901     }
902     cairo_set_line_cap(platformContext()->cr(), cairoCap);
903 }
904
905 static inline bool isDashArrayAllZero(const DashArray& dashes)
906 {
907     for (auto& dash : dashes) {
908         if (dash)
909             return false;
910     }
911     return true;
912 }
913
914 void GraphicsContext::setLineDash(const DashArray& dashes, float dashOffset)
915 {
916     if (isDashArrayAllZero(dashes))
917         cairo_set_dash(platformContext()->cr(), 0, 0, 0);
918     else
919         cairo_set_dash(platformContext()->cr(), dashes.data(), dashes.size(), dashOffset);
920 }
921
922 void GraphicsContext::setLineJoin(LineJoin lineJoin)
923 {
924     if (paintingDisabled())
925         return;
926
927     cairo_line_join_t cairoJoin = CAIRO_LINE_JOIN_MITER;
928     switch (lineJoin) {
929     case MiterJoin:
930         // no-op
931         break;
932     case RoundJoin:
933         cairoJoin = CAIRO_LINE_JOIN_ROUND;
934         break;
935     case BevelJoin:
936         cairoJoin = CAIRO_LINE_JOIN_BEVEL;
937         break;
938     }
939     cairo_set_line_join(platformContext()->cr(), cairoJoin);
940 }
941
942 void GraphicsContext::setMiterLimit(float miter)
943 {
944     if (paintingDisabled())
945         return;
946
947     cairo_set_miter_limit(platformContext()->cr(), miter);
948 }
949
950 void GraphicsContext::setPlatformAlpha(float alpha)
951 {
952     platformContext()->setGlobalAlpha(alpha);
953 }
954
955 void GraphicsContext::setPlatformCompositeOperation(CompositeOperator op, BlendMode blendOp)
956 {
957     if (paintingDisabled())
958         return;
959
960     cairo_operator_t cairo_op;
961     if (blendOp == BlendModeNormal)
962         cairo_op = toCairoOperator(op);
963     else
964         cairo_op = toCairoOperator(blendOp);
965
966     cairo_set_operator(platformContext()->cr(), cairo_op);
967 }
968
969 void GraphicsContext::canvasClip(const Path& path, WindRule windRule)
970 {
971     clipPath(path, windRule);
972 }
973
974 void GraphicsContext::clipOut(const Path& path)
975 {
976     if (paintingDisabled())
977         return;
978
979     cairo_t* cr = platformContext()->cr();
980     double x1, y1, x2, y2;
981     cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
982     cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
983     appendWebCorePathToCairoContext(cr, path);
984
985     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
986     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
987     cairo_clip(cr);
988     cairo_set_fill_rule(cr, savedFillRule);
989 }
990
991 void GraphicsContext::rotate(float radians)
992 {
993     if (paintingDisabled())
994         return;
995
996     cairo_rotate(platformContext()->cr(), radians);
997     m_data->rotate(radians);
998 }
999
1000 void GraphicsContext::scale(const FloatSize& size)
1001 {
1002     if (paintingDisabled())
1003         return;
1004
1005     cairo_scale(platformContext()->cr(), size.width(), size.height());
1006     m_data->scale(size);
1007 }
1008
1009 void GraphicsContext::clipOut(const FloatRect& r)
1010 {
1011     if (paintingDisabled())
1012         return;
1013
1014     cairo_t* cr = platformContext()->cr();
1015     double x1, y1, x2, y2;
1016     cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
1017     cairo_rectangle(cr, x1, y1, x2 - x1, y2 - y1);
1018     cairo_rectangle(cr, r.x(), r.y(), r.width(), r.height());
1019     cairo_fill_rule_t savedFillRule = cairo_get_fill_rule(cr);
1020     cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD);
1021     cairo_clip(cr);
1022     cairo_set_fill_rule(cr, savedFillRule);
1023 }
1024
1025 void GraphicsContext::platformFillRoundedRect(const FloatRoundedRect& rect, const Color& color)
1026 {
1027     if (paintingDisabled())
1028         return;
1029
1030     if (hasShadow())
1031         platformContext()->shadowBlur().drawRectShadow(*this, rect);
1032
1033     cairo_t* cr = platformContext()->cr();
1034     cairo_save(cr);
1035     Path path;
1036     path.addRoundedRect(rect);
1037     appendWebCorePathToCairoContext(cr, path);
1038     setSourceRGBAFromColor(cr, color);
1039     cairo_fill(cr);
1040     cairo_restore(cr);
1041 }
1042
1043 void GraphicsContext::fillRectWithRoundedHole(const FloatRect& rect, const FloatRoundedRect& roundedHoleRect, const Color& color)
1044 {
1045     if (paintingDisabled() || !color.isValid())
1046         return;
1047
1048     if (this->mustUseShadowBlur())
1049         platformContext()->shadowBlur().drawInsetShadow(*this, rect, roundedHoleRect);
1050
1051     Path path;
1052     path.addRect(rect);
1053     if (!roundedHoleRect.radii().isZero())
1054         path.addRoundedRect(roundedHoleRect);
1055     else
1056         path.addRect(roundedHoleRect.rect());
1057
1058     cairo_t* cr = platformContext()->cr();
1059     cairo_save(cr);
1060     setPathOnCairoContext(platformContext()->cr(), path.platformPath()->context());
1061     fillCurrentCairoPath(*this);
1062     cairo_restore(cr);
1063 }
1064
1065 void GraphicsContext::drawPattern(Image& image, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, const FloatSize&, CompositeOperator op, const FloatRect& destRect, BlendMode)
1066 {
1067     RefPtr<cairo_surface_t> surface = image.nativeImageForCurrentFrame();
1068     if (!surface) // If it's too early we won't have an image yet.
1069         return;
1070
1071     cairo_t* cr = platformContext()->cr();
1072     drawPatternToCairoContext(cr, surface.get(), IntSize(image.size()), tileRect, patternTransform, phase, toCairoOperator(op), destRect);
1073 }
1074
1075 void GraphicsContext::setPlatformShouldAntialias(bool enable)
1076 {
1077     if (paintingDisabled())
1078         return;
1079
1080     // When true, use the default Cairo backend antialias mode (usually this
1081     // enables standard 'grayscale' antialiasing); false to explicitly disable
1082     // antialiasing. This is the same strategy as used in drawConvexPolygon().
1083     cairo_set_antialias(platformContext()->cr(), enable ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE);
1084 }
1085
1086 void GraphicsContext::setPlatformImageInterpolationQuality(InterpolationQuality quality)
1087 {
1088     platformContext()->setImageInterpolationQuality(quality);
1089 }
1090
1091 bool GraphicsContext::isAcceleratedContext() const
1092 {
1093     return cairo_surface_get_type(cairo_get_target(platformContext()->cr())) == CAIRO_SURFACE_TYPE_GL;
1094 }
1095
1096 #if ENABLE(3D_TRANSFORMS) && USE(TEXTURE_MAPPER)
1097 TransformationMatrix GraphicsContext::get3DTransform() const
1098 {
1099     // FIXME: Can we approximate the transformation better than this?
1100     return getCTM().toTransformationMatrix();
1101 }
1102
1103 void GraphicsContext::concat3DTransform(const TransformationMatrix& transform)
1104 {
1105     concatCTM(transform.toAffineTransform());
1106 }
1107
1108 void GraphicsContext::set3DTransform(const TransformationMatrix& transform)
1109 {
1110     setCTM(transform.toAffineTransform());
1111 }
1112 #endif // ENABLE(3D_TRANSFORMS) && USE(TEXTURE_MAPPER)
1113
1114 } // namespace WebCore
1115
1116 #endif // USE(CAIRO)