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