78df2b3420020b4f920e015386fc7171c3ef71ec
[WebKit-https.git] / Source / WebCore / platform / graphics / cg / GraphicsContextCG.cpp
1 /*
2  * Copyright (C) 2003-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
25  */
26
27 #include "config.h"
28 #include "GraphicsContextCG.h"
29
30 #if USE(CG)
31
32 #include "AffineTransform.h"
33 #include "DisplayListRecorder.h"
34 #include "FloatConversion.h"
35 #include "GraphicsContextPlatformPrivateCG.h"
36 #include "ImageBuffer.h"
37 #include "ImageOrientation.h"
38 #include "Logging.h"
39 #include "Path.h"
40 #include "Pattern.h"
41 #include "ShadowBlur.h"
42 #include "SubimageCacheWithTimer.h"
43 #include "Timer.h"
44 #include "URL.h"
45 #include <pal/spi/cg/CoreGraphicsSPI.h>
46 #include <wtf/CurrentTime.h>
47 #include <wtf/MathExtras.h>
48 #include <wtf/RetainPtr.h>
49 #include <wtf/text/TextStream.h>
50
51 #if PLATFORM(COCOA)
52 #include "WebCoreSystemInterface.h"
53 #endif
54
55 #if PLATFORM(WIN)
56 #include <WebKitSystemInterface/WebKitSystemInterface.h>
57 #endif
58
59 // FIXME: The following using declaration should be in <wtf/HashFunctions.h>.
60 using WTF::pairIntHash;
61
62 // FIXME: The following using declaration should be in <wtf/HashTraits.h>.
63 using WTF::GenericHashTraits;
64
65 namespace WebCore {
66
67 static void setCGFillColor(CGContextRef context, const Color& color)
68 {
69     CGContextSetFillColorWithColor(context, cachedCGColor(color));
70 }
71
72 static void setCGStrokeColor(CGContextRef context, const Color& color)
73 {
74     CGContextSetStrokeColorWithColor(context, cachedCGColor(color));
75 }
76
77 // FIXME: This should be removed soon.
78 CGColorSpaceRef deviceRGBColorSpaceRef()
79 {
80     static CGColorSpaceRef deviceSpace = CGColorSpaceCreateDeviceRGB();
81     return deviceSpace;
82 }
83
84 CGColorSpaceRef sRGBColorSpaceRef()
85 {
86     static CGColorSpaceRef sRGBSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
87 #if PLATFORM(WIN)
88     // Out-of-date CG installations will not honor kCGColorSpaceSRGB. This logic avoids
89     // causing a crash under those conditions. Since the default color space in Windows
90     // is sRGB, this all works out nicely.
91     if (!sRGBSpace)
92         sRGBSpace = deviceRGBColorSpaceRef();
93 #endif // PLATFORM(WIN)
94     return sRGBSpace;
95 }
96     
97 CGColorSpaceRef extendedSRGBColorSpaceRef()
98 {
99     static CGColorSpaceRef extendedSRGBSpace;
100 #if PLATFORM(IOS) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200)
101     extendedSRGBSpace = CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB);
102 #endif
103     // If there is no support for exteneded sRGB, fall back to sRGB.
104     if (!extendedSRGBSpace)
105         extendedSRGBSpace = sRGBColorSpaceRef();
106     return extendedSRGBSpace;
107 }
108
109 CGColorSpaceRef displayP3ColorSpaceRef()
110 {
111 #if PLATFORM(IOS) || (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED > 101100)
112     static CGColorSpaceRef displayP3Space = CGColorSpaceCreateWithName(kCGColorSpaceDisplayP3);
113 #else
114     static CGColorSpaceRef displayP3Space = sRGBColorSpaceRef();
115 #endif
116     return displayP3Space;
117 }
118
119 #if PLATFORM(WIN)
120 CGColorSpaceRef linearRGBColorSpaceRef()
121 {
122     // FIXME: Windows should be able to use linear sRGB, this is tracked by http://webkit.org/b/80000.
123     return deviceRGBColorSpaceRef();
124 }
125 #endif
126
127 static InterpolationQuality convertInterpolationQuality(CGInterpolationQuality quality)
128 {
129     switch (quality) {
130     case kCGInterpolationDefault:
131         return InterpolationDefault;
132     case kCGInterpolationNone:
133         return InterpolationNone;
134     case kCGInterpolationLow:
135         return InterpolationLow;
136     case kCGInterpolationMedium:
137         return InterpolationMedium;
138     case kCGInterpolationHigh:
139         return InterpolationHigh;
140     }
141     return InterpolationDefault;
142 }
143
144 void GraphicsContext::platformInit(CGContextRef cgContext)
145 {
146     if (!cgContext)
147         return;
148
149     m_data = new GraphicsContextPlatformPrivate(cgContext);
150     // Make sure the context starts in sync with our state.
151     setPlatformFillColor(fillColor());
152     setPlatformStrokeColor(strokeColor());
153     setPlatformStrokeThickness(strokeThickness());
154     m_state.imageInterpolationQuality = convertInterpolationQuality(CGContextGetInterpolationQuality(platformContext()));
155 }
156
157 void GraphicsContext::platformDestroy()
158 {
159     delete m_data;
160 }
161
162 CGContextRef GraphicsContext::platformContext() const
163 {
164     ASSERT(!paintingDisabled());
165     ASSERT(m_data->m_cgContext);
166     return m_data->m_cgContext.get();
167 }
168
169 void GraphicsContext::savePlatformState()
170 {
171     ASSERT(!paintingDisabled());
172     ASSERT(!isRecording());
173
174     // Note: Do not use this function within this class implementation, since we want to avoid the extra
175     // save of the secondary context (in GraphicsContextPlatformPrivateCG.h).
176     CGContextSaveGState(platformContext());
177     m_data->save();
178 }
179
180 void GraphicsContext::restorePlatformState()
181 {
182     ASSERT(!paintingDisabled());
183     ASSERT(!isRecording());
184
185     // Note: Do not use this function within this class implementation, since we want to avoid the extra
186     // restore of the secondary context (in GraphicsContextPlatformPrivateCG.h).
187     CGContextRestoreGState(platformContext());
188     m_data->restore();
189     m_data->m_userToDeviceTransformKnownToBeIdentity = false;
190 }
191
192 void GraphicsContext::drawNativeImage(const RetainPtr<CGImageRef>& image, const FloatSize& imageSize, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator op, BlendMode blendMode, ImageOrientation orientation)
193 {
194     if (paintingDisabled())
195         return;
196
197     if (isRecording()) {
198         m_displayListRecorder->drawNativeImage(image, imageSize, destRect, srcRect, op, blendMode, orientation);
199         return;
200     }
201
202 #if !LOG_DISABLED
203     double startTime = currentTime();
204 #endif
205     RetainPtr<CGImageRef> subImage(image);
206
207     float currHeight = orientation.usesWidthAsHeight() ? CGImageGetWidth(subImage.get()) : CGImageGetHeight(subImage.get());
208     if (currHeight <= srcRect.y())
209         return;
210
211     CGContextRef context = platformContext();
212     CGAffineTransform transform = CGContextGetCTM(context);
213     CGContextStateSaver stateSaver(context, false);
214     
215     bool shouldUseSubimage = false;
216
217     // If the source rect is a subportion of the image, then we compute an inflated destination rect that will hold the entire image
218     // and then set a clip to the portion that we want to display.
219     FloatRect adjustedDestRect = destRect;
220
221     if (srcRect.size() != imageSize) {
222         CGInterpolationQuality interpolationQuality = CGContextGetInterpolationQuality(context);
223         // When the image is scaled using high-quality interpolation, we create a temporary CGImage
224         // containing only the portion we want to display. We need to do this because high-quality
225         // interpolation smoothes sharp edges, causing pixels from outside the source rect to bleed
226         // into the destination rect. See <rdar://problem/6112909>.
227         shouldUseSubimage = (interpolationQuality != kCGInterpolationNone) && (srcRect.size() != destRect.size() || !getCTM().isIdentityOrTranslationOrFlipped());
228         float xScale = srcRect.width() / destRect.width();
229         float yScale = srcRect.height() / destRect.height();
230         if (shouldUseSubimage) {
231             FloatRect subimageRect = srcRect;
232             float leftPadding = srcRect.x() - floorf(srcRect.x());
233             float topPadding = srcRect.y() - floorf(srcRect.y());
234
235             subimageRect.move(-leftPadding, -topPadding);
236             adjustedDestRect.move(-leftPadding / xScale, -topPadding / yScale);
237
238             subimageRect.setWidth(ceilf(subimageRect.width() + leftPadding));
239             adjustedDestRect.setWidth(subimageRect.width() / xScale);
240
241             subimageRect.setHeight(ceilf(subimageRect.height() + topPadding));
242             adjustedDestRect.setHeight(subimageRect.height() / yScale);
243
244 #if CACHE_SUBIMAGES
245             subImage = subimageCache().getSubimage(subImage.get(), subimageRect);
246 #else
247             subImage = adoptCF(CGImageCreateWithImageInRect(subImage.get(), subimageRect));
248 #endif
249             if (currHeight < srcRect.maxY()) {
250                 ASSERT(CGImageGetHeight(subImage.get()) == currHeight - CGRectIntegral(srcRect).origin.y);
251                 adjustedDestRect.setHeight(CGImageGetHeight(subImage.get()) / yScale);
252             }
253         } else {
254             adjustedDestRect.setLocation(FloatPoint(destRect.x() - srcRect.x() / xScale, destRect.y() - srcRect.y() / yScale));
255             adjustedDestRect.setSize(FloatSize(imageSize.width() / xScale, imageSize.height() / yScale));
256         }
257
258         if (!destRect.contains(adjustedDestRect)) {
259             stateSaver.save();
260             CGContextClipToRect(context, destRect);
261         }
262     }
263
264     // If the image is only partially loaded, then shrink the destination rect that we're drawing into accordingly.
265     if (!shouldUseSubimage && currHeight < imageSize.height())
266         adjustedDestRect.setHeight(adjustedDestRect.height() * currHeight / imageSize.height());
267
268 #if PLATFORM(IOS)
269     bool wasAntialiased = CGContextGetShouldAntialias(context);
270     // Anti-aliasing is on by default on the iPhone. Need to turn it off when drawing images.
271     CGContextSetShouldAntialias(context, false);
272
273     // Align to pixel boundaries
274     adjustedDestRect = roundToDevicePixels(adjustedDestRect);
275 #endif
276
277     setPlatformCompositeOperation(op, blendMode);
278
279     // ImageOrientation expects the origin to be at (0, 0)
280     CGContextTranslateCTM(context, adjustedDestRect.x(), adjustedDestRect.y());
281     adjustedDestRect.setLocation(FloatPoint());
282
283     if (orientation != DefaultImageOrientation) {
284         CGContextConcatCTM(context, orientation.transformFromDefault(adjustedDestRect.size()));
285         if (orientation.usesWidthAsHeight()) {
286             // The destination rect will have it's width and height already reversed for the orientation of
287             // the image, as it was needed for page layout, so we need to reverse it back here.
288             adjustedDestRect = FloatRect(adjustedDestRect.x(), adjustedDestRect.y(), adjustedDestRect.height(), adjustedDestRect.width());
289         }
290     }
291     
292     // Flip the coords.
293     CGContextTranslateCTM(context, 0, adjustedDestRect.height());
294     CGContextScaleCTM(context, 1, -1);
295
296     // Draw the image.
297     CGContextDrawImage(context, adjustedDestRect, subImage.get());
298     
299     if (!stateSaver.didSave()) {
300         CGContextSetCTM(context, transform);
301 #if PLATFORM(IOS)
302         CGContextSetShouldAntialias(context, wasAntialiased);
303 #endif
304     }
305
306     LOG_WITH_STREAM(Images, stream << "GraphicsContext::drawNativeImage " << image.get() << " size " << imageSize << " into " << destRect << " took " << 1000.0 * (currentTime() - startTime) << "ms");
307 }
308
309 static void drawPatternCallback(void* info, CGContextRef context)
310 {
311     CGImageRef image = (CGImageRef)info;
312     CGFloat height = CGImageGetHeight(image);
313 #if PLATFORM(IOS)
314     CGContextScaleCTM(context, 1, -1);
315     CGContextTranslateCTM(context, 0, -height);
316 #endif
317     CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(0, 0, CGImageGetWidth(image), height)), image);
318 }
319
320 static void patternReleaseCallback(void* info)
321 {
322     callOnMainThread([image = static_cast<CGImageRef>(info)] {
323         CGImageRelease(image);
324     });
325 }
326
327 void GraphicsContext::drawPattern(Image& image, const FloatRect& destRect, const FloatRect& tileRect, const AffineTransform& patternTransform, const FloatPoint& phase, const FloatSize& spacing, CompositeOperator op, BlendMode blendMode)
328 {
329     if (paintingDisabled() || !patternTransform.isInvertible())
330         return;
331
332     if (isRecording()) {
333         m_displayListRecorder->drawPattern(image, destRect, tileRect, patternTransform, phase, spacing, op, blendMode);
334         return;
335     }
336
337     CGContextRef context = platformContext();
338     CGContextStateSaver stateSaver(context);
339     CGContextClipToRect(context, destRect);
340
341     setPlatformCompositeOperation(op, blendMode);
342
343     CGContextTranslateCTM(context, destRect.x(), destRect.y() + destRect.height());
344     CGContextScaleCTM(context, 1, -1);
345     
346     // Compute the scaled tile size.
347     float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());
348     
349     // We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being
350     // the origin).
351     float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); // We translated the context so that destRect.x() is the origin, so subtract it out.
352     float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);
353
354     auto tileImage = image.nativeImageForCurrentFrame();
355     float h = CGImageGetHeight(tileImage.get());
356
357     RetainPtr<CGImageRef> subImage;
358 #if PLATFORM(IOS)
359     FloatSize imageSize = image.originalSize();
360 #else
361     FloatSize imageSize = image.size();
362 #endif
363     if (tileRect.size() == imageSize)
364         subImage = tileImage;
365     else {
366         // Copying a sub-image out of a partially-decoded image stops the decoding of the original image. It should never happen
367         // because sub-images are only used for border-image, which only renders when the image is fully decoded.
368         ASSERT(h == image.height());
369         subImage = adoptCF(CGImageCreateWithImageInRect(tileImage.get(), tileRect));
370     }
371
372     // If we need to paint gaps between tiles because we have a partially loaded image or non-zero spacing,
373     // fall back to the less efficient CGPattern-based mechanism.
374     float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());
375     float w = CGImageGetWidth(tileImage.get());
376     if (w == image.size().width() && h == image.size().height() && !spacing.width() && !spacing.height()) {
377         // FIXME: CG seems to snap the images to integral sizes. When we care (e.g. with border-image-repeat: round),
378         // we should tile all but the last, and stetch the last image to fit.
379         CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), subImage.get());
380     } else {
381         static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, patternReleaseCallback };
382         CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);
383         matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));
384         // The top of a partially-decoded image is drawn at the bottom of the tile. Map it to the top.
385         matrix = CGAffineTransformTranslate(matrix, 0, image.size().height() - h);
386 #if PLATFORM(IOS)
387         matrix = CGAffineTransformScale(matrix, 1, -1);
388         matrix = CGAffineTransformTranslate(matrix, 0, -h);
389 #endif
390         CGImageRef platformImage = CGImageRetain(subImage.get());
391         RetainPtr<CGPatternRef> pattern = adoptCF(CGPatternCreate(platformImage, CGRectMake(0, 0, tileRect.width(), tileRect.height()), matrix,
392             tileRect.width() + spacing.width() * (1 / narrowPrecisionToFloat(patternTransform.a())),
393             tileRect.height() + spacing.height() * (1 / narrowPrecisionToFloat(patternTransform.d())),
394             kCGPatternTilingConstantSpacing, true, &patternCallbacks));
395         
396         if (!pattern)
397             return;
398
399         RetainPtr<CGColorSpaceRef> patternSpace = adoptCF(CGColorSpaceCreatePattern(nullptr));
400
401         CGFloat alpha = 1;
402         RetainPtr<CGColorRef> color = adoptCF(CGColorCreateWithPattern(patternSpace.get(), pattern.get(), &alpha));
403         CGContextSetFillColorSpace(context, patternSpace.get());
404
405         CGContextSetBaseCTM(context, CGAffineTransformIdentity);
406         CGContextSetPatternPhase(context, CGSizeZero);
407
408         CGContextSetFillColorWithColor(context, color.get());
409         CGContextFillRect(context, CGContextGetClipBoundingBox(context)); // FIXME: we know the clip; we set it above.
410     }
411 }
412
413 void GraphicsContext::clipToImageBuffer(ImageBuffer& buffer, const FloatRect& destRect)
414 {
415     if (paintingDisabled())
416         return;
417
418     FloatSize bufferDestinationSize = buffer.sizeForDestinationSize(destRect.size());
419     RetainPtr<CGImageRef> image = buffer.copyNativeImage(DontCopyBackingStore);
420
421     CGContextRef context = platformContext();
422     // FIXME: This image needs to be grayscale to be used as an alpha mask here.
423     CGContextTranslateCTM(context, destRect.x(), destRect.y() + bufferDestinationSize.height());
424     CGContextScaleCTM(context, 1, -1);
425     CGContextClipToRect(context, FloatRect(FloatPoint(0, bufferDestinationSize.height() - destRect.height()), destRect.size()));
426     CGContextClipToMask(context, FloatRect(FloatPoint(), bufferDestinationSize), image.get());
427     CGContextScaleCTM(context, 1, -1);
428     CGContextTranslateCTM(context, -destRect.x(), -destRect.y() - destRect.height());
429 }
430
431 // Draws a filled rectangle with a stroked border.
432 void GraphicsContext::drawRect(const FloatRect& rect, float borderThickness)
433 {
434     if (paintingDisabled())
435         return;
436
437     if (isRecording()) {
438         m_displayListRecorder->drawRect(rect, borderThickness);
439         return;
440     }
441
442     // FIXME: this function does not handle patterns and gradients like drawPath does, it probably should.
443     ASSERT(!rect.isEmpty());
444
445     CGContextRef context = platformContext();
446
447     CGContextFillRect(context, rect);
448
449     if (strokeStyle() != NoStroke) {
450         // We do a fill of four rects to simulate the stroke of a border.
451         Color oldFillColor = fillColor();
452         if (oldFillColor != strokeColor())
453             setCGFillColor(context, strokeColor());
454         CGRect rects[4] = {
455             FloatRect(rect.x(), rect.y(), rect.width(), borderThickness),
456             FloatRect(rect.x(), rect.maxY() - borderThickness, rect.width(), borderThickness),
457             FloatRect(rect.x(), rect.y() + borderThickness, borderThickness, rect.height() - 2 * borderThickness),
458             FloatRect(rect.maxX() - borderThickness, rect.y() + borderThickness, borderThickness, rect.height() - 2 * borderThickness)
459         };
460         CGContextFillRects(context, rects, 4);
461         if (oldFillColor != strokeColor())
462             setCGFillColor(context, oldFillColor);
463     }
464 }
465
466 // This is only used to draw borders.
467 void GraphicsContext::drawLine(const FloatPoint& point1, const FloatPoint& point2)
468 {
469     if (paintingDisabled())
470         return;
471
472     if (strokeStyle() == NoStroke)
473         return;
474
475     if (isRecording()) {
476         m_displayListRecorder->drawLine(point1, point2);
477         return;
478     }
479
480     float thickness = strokeThickness();
481     bool isVerticalLine = (point1.x() + thickness == point2.x());
482     float strokeWidth = isVerticalLine ? point2.y() - point1.y() : point2.x() - point1.x();
483     if (!thickness || !strokeWidth)
484         return;
485
486     CGContextRef context = platformContext();
487
488     StrokeStyle strokeStyle = this->strokeStyle();
489     float cornerWidth = 0;
490     bool drawsDashedLine = strokeStyle == DottedStroke || strokeStyle == DashedStroke;
491
492     CGContextStateSaver stateSaver(context, drawsDashedLine);
493     if (drawsDashedLine) {
494         // Figure out end points to ensure we always paint corners.
495         cornerWidth = dashedLineCornerWidthForStrokeWidth(strokeWidth);
496         setCGFillColor(context, strokeColor());
497         if (isVerticalLine) {
498             CGContextFillRect(context, FloatRect(point1.x(), point1.y(), thickness, cornerWidth));
499             CGContextFillRect(context, FloatRect(point1.x(), point2.y() - cornerWidth, thickness, cornerWidth));
500         } else {
501             CGContextFillRect(context, FloatRect(point1.x(), point1.y(), cornerWidth, thickness));
502             CGContextFillRect(context, FloatRect(point2.x() - cornerWidth, point1.y(), cornerWidth, thickness));
503         }
504         strokeWidth -= 2 * cornerWidth;
505         float patternWidth = dashedLinePatternWidthForStrokeWidth(strokeWidth);
506         // Check if corner drawing sufficiently covers the line.
507         if (strokeWidth <= patternWidth + 1)
508             return;
509
510         float patternOffset = dashedLinePatternOffsetForPatternAndStrokeWidth(patternWidth, strokeWidth);
511         const CGFloat dashedLine[2] = { static_cast<CGFloat>(patternWidth), static_cast<CGFloat>(patternWidth) };
512         CGContextSetLineDash(context, patternOffset, dashedLine, 2);
513     }
514
515     auto centeredPoints = centerLineAndCutOffCorners(isVerticalLine, cornerWidth, point1, point2);
516     auto p1 = centeredPoints[0];
517     auto p2 = centeredPoints[1];
518
519     if (shouldAntialias()) {
520 #if PLATFORM(IOS)
521         // Force antialiasing on for line patterns as they don't look good with it turned off (<rdar://problem/5459772>).
522         CGContextSetShouldAntialias(context, strokeStyle == DottedStroke || strokeStyle == DashedStroke);
523 #else
524         CGContextSetShouldAntialias(context, false);
525 #endif
526     }
527     CGContextBeginPath(context);
528     CGContextMoveToPoint(context, p1.x(), p1.y());
529     CGContextAddLineToPoint(context, p2.x(), p2.y());
530     CGContextStrokePath(context);
531     if (shouldAntialias())
532         CGContextSetShouldAntialias(context, true);
533 }
534
535 void GraphicsContext::drawEllipse(const FloatRect& rect)
536 {
537     if (paintingDisabled())
538         return;
539
540     if (isRecording()) {
541         m_displayListRecorder->drawEllipse(rect);
542         return;
543     }
544
545     Path path;
546     path.addEllipse(rect);
547     drawPath(path);
548 }
549
550 void GraphicsContext::applyStrokePattern()
551 {
552     if (paintingDisabled())
553         return;
554
555     if (isRecording()) {
556         m_displayListRecorder->applyStrokePattern();
557         return;
558     }
559
560     CGContextRef cgContext = platformContext();
561     AffineTransform userToBaseCTM = AffineTransform(getUserToBaseCTM(cgContext));
562
563     RetainPtr<CGPatternRef> platformPattern = adoptCF(m_state.strokePattern->createPlatformPattern(userToBaseCTM));
564     if (!platformPattern)
565         return;
566
567     RetainPtr<CGColorSpaceRef> patternSpace = adoptCF(CGColorSpaceCreatePattern(0));
568     CGContextSetStrokeColorSpace(cgContext, patternSpace.get());
569
570     const CGFloat patternAlpha = 1;
571     CGContextSetStrokePattern(cgContext, platformPattern.get(), &patternAlpha);
572 }
573
574 void GraphicsContext::applyFillPattern()
575 {
576     if (paintingDisabled())
577         return;
578
579     if (isRecording()) {
580         m_displayListRecorder->applyFillPattern();
581         return;
582     }
583
584     CGContextRef cgContext = platformContext();
585     AffineTransform userToBaseCTM = AffineTransform(getUserToBaseCTM(cgContext));
586
587     RetainPtr<CGPatternRef> platformPattern = adoptCF(m_state.fillPattern->createPlatformPattern(userToBaseCTM));
588     if (!platformPattern)
589         return;
590
591     RetainPtr<CGColorSpaceRef> patternSpace = adoptCF(CGColorSpaceCreatePattern(nullptr));
592     CGContextSetFillColorSpace(cgContext, patternSpace.get());
593
594     const CGFloat patternAlpha = 1;
595     CGContextSetFillPattern(cgContext, platformPattern.get(), &patternAlpha);
596 }
597
598 static inline bool calculateDrawingMode(const GraphicsContextState& state, CGPathDrawingMode& mode)
599 {
600     bool shouldFill = state.fillPattern || state.fillColor.isVisible();
601     bool shouldStroke = state.strokePattern || (state.strokeStyle != NoStroke && state.strokeColor.isVisible());
602     bool useEOFill = state.fillRule == RULE_EVENODD;
603
604     if (shouldFill) {
605         if (shouldStroke) {
606             if (useEOFill)
607                 mode = kCGPathEOFillStroke;
608             else
609                 mode = kCGPathFillStroke;
610         } else { // fill, no stroke
611             if (useEOFill)
612                 mode = kCGPathEOFill;
613             else
614                 mode = kCGPathFill;
615         }
616     } else {
617         // Setting mode to kCGPathStroke even if shouldStroke is false. In that case, we return false and mode will not be used,
618         // but the compiler will not complain about an uninitialized variable.
619         mode = kCGPathStroke;
620     }
621
622     return shouldFill || shouldStroke;
623 }
624
625 void GraphicsContext::drawPath(const Path& path)
626 {
627     if (paintingDisabled() || path.isEmpty())
628         return;
629
630     if (isRecording()) {
631         m_displayListRecorder->drawPath(path);
632         return;
633     }
634
635     CGContextRef context = platformContext();
636     const GraphicsContextState& state = m_state;
637
638     if (state.fillGradient || state.strokeGradient) {
639         // We don't have any optimized way to fill & stroke a path using gradients
640         // FIXME: Be smarter about this.
641         fillPath(path);
642         strokePath(path);
643         return;
644     }
645
646     CGContextBeginPath(context);
647     CGContextAddPath(context, path.platformPath());
648
649     if (state.fillPattern)
650         applyFillPattern();
651     if (state.strokePattern)
652         applyStrokePattern();
653
654     CGPathDrawingMode drawingMode;
655     if (calculateDrawingMode(state, drawingMode))
656         CGContextDrawPath(context, drawingMode);
657 }
658
659 void GraphicsContext::fillPath(const Path& path)
660 {
661     if (paintingDisabled() || path.isEmpty())
662         return;
663
664     if (isRecording()) {
665         m_displayListRecorder->fillPath(path);
666         return;
667     }
668
669     CGContextRef context = platformContext();
670
671     if (m_state.fillGradient) {
672         if (hasShadow()) {
673             FloatRect rect = path.fastBoundingRect();
674             FloatSize layerSize = getCTM().mapSize(rect.size());
675
676             CGLayerRef layer = CGLayerCreateWithContext(context, layerSize, 0);
677             CGContextRef layerContext = CGLayerGetContext(layer);
678
679             CGContextScaleCTM(layerContext, layerSize.width() / rect.width(), layerSize.height() / rect.height());
680             CGContextTranslateCTM(layerContext, -rect.x(), -rect.y());
681             CGContextBeginPath(layerContext);
682             CGContextAddPath(layerContext, path.platformPath());
683             CGContextConcatCTM(layerContext, m_state.fillGradient->gradientSpaceTransform());
684
685             if (fillRule() == RULE_EVENODD)
686                 CGContextEOClip(layerContext);
687             else
688                 CGContextClip(layerContext);
689
690             m_state.fillGradient->paint(layerContext);
691             CGContextDrawLayerInRect(context, rect, layer);
692             CGLayerRelease(layer);
693         } else {
694             CGContextBeginPath(context);
695             CGContextAddPath(context, path.platformPath());
696             CGContextStateSaver stateSaver(context);
697             CGContextConcatCTM(context, m_state.fillGradient->gradientSpaceTransform());
698
699             if (fillRule() == RULE_EVENODD)
700                 CGContextEOClip(context);
701             else
702                 CGContextClip(context);
703
704             m_state.fillGradient->paint(this);
705         }
706
707         return;
708     }
709
710     CGContextBeginPath(context);
711     CGContextAddPath(context, path.platformPath());
712
713     if (m_state.fillPattern)
714         applyFillPattern();
715
716     if (fillRule() == RULE_EVENODD)
717         CGContextEOFillPath(context);
718     else
719         CGContextFillPath(context);
720 }
721
722 void GraphicsContext::strokePath(const Path& path)
723 {
724     if (paintingDisabled() || path.isEmpty())
725         return;
726
727     if (isRecording()) {
728         m_displayListRecorder->strokePath(path);
729         return;
730     }
731
732     CGContextRef context = platformContext();
733
734     CGContextBeginPath(context);
735     CGContextAddPath(context, path.platformPath());
736
737     if (m_state.strokeGradient) {
738         if (hasShadow()) {
739             FloatRect rect = path.fastBoundingRect();
740             float lineWidth = strokeThickness();
741             float doubleLineWidth = lineWidth * 2;
742             float adjustedWidth = ceilf(rect.width() + doubleLineWidth);
743             float adjustedHeight = ceilf(rect.height() + doubleLineWidth);
744
745             FloatSize layerSize = getCTM().mapSize(FloatSize(adjustedWidth, adjustedHeight));
746
747             CGLayerRef layer = CGLayerCreateWithContext(context, layerSize, 0);
748             CGContextRef layerContext = CGLayerGetContext(layer);
749             CGContextSetLineWidth(layerContext, lineWidth);
750
751             // Compensate for the line width, otherwise the layer's top-left corner would be
752             // aligned with the rect's top-left corner. This would result in leaving pixels out of
753             // the layer on the left and top sides.
754             float translationX = lineWidth - rect.x();
755             float translationY = lineWidth - rect.y();
756             CGContextScaleCTM(layerContext, layerSize.width() / adjustedWidth, layerSize.height() / adjustedHeight);
757             CGContextTranslateCTM(layerContext, translationX, translationY);
758
759             CGContextAddPath(layerContext, path.platformPath());
760             CGContextReplacePathWithStrokedPath(layerContext);
761             CGContextClip(layerContext);
762             CGContextConcatCTM(layerContext, m_state.strokeGradient->gradientSpaceTransform());
763             m_state.strokeGradient->paint(layerContext);
764
765             float destinationX = roundf(rect.x() - lineWidth);
766             float destinationY = roundf(rect.y() - lineWidth);
767             CGContextDrawLayerInRect(context, CGRectMake(destinationX, destinationY, adjustedWidth, adjustedHeight), layer);
768             CGLayerRelease(layer);
769         } else {
770             CGContextStateSaver stateSaver(context);
771             CGContextReplacePathWithStrokedPath(context);
772             CGContextClip(context);
773             CGContextConcatCTM(context, m_state.strokeGradient->gradientSpaceTransform());
774             m_state.strokeGradient->paint(this);
775         }
776         return;
777     }
778
779     if (m_state.strokePattern)
780         applyStrokePattern();
781     CGContextStrokePath(context);
782 }
783
784 void GraphicsContext::fillRect(const FloatRect& rect)
785 {
786     if (paintingDisabled())
787         return;
788
789     if (isRecording()) {
790         m_displayListRecorder->fillRect(rect);
791         return;
792     }
793
794     CGContextRef context = platformContext();
795
796     if (m_state.fillGradient) {
797         CGContextStateSaver stateSaver(context);
798         if (hasShadow()) {
799             FloatSize layerSize = getCTM().mapSize(rect.size());
800
801             CGLayerRef layer = CGLayerCreateWithContext(context, layerSize, 0);
802             CGContextRef layerContext = CGLayerGetContext(layer);
803
804             CGContextScaleCTM(layerContext, layerSize.width() / rect.width(), layerSize.height() / rect.height());
805             CGContextTranslateCTM(layerContext, -rect.x(), -rect.y());
806             CGContextAddRect(layerContext, rect);
807             CGContextClip(layerContext);
808
809             CGContextConcatCTM(layerContext, m_state.fillGradient->gradientSpaceTransform());
810             m_state.fillGradient->paint(layerContext);
811             CGContextDrawLayerInRect(context, rect, layer);
812             CGLayerRelease(layer);
813         } else {
814             CGContextClipToRect(context, rect);
815             CGContextConcatCTM(context, m_state.fillGradient->gradientSpaceTransform());
816             m_state.fillGradient->paint(this);
817         }
818         return;
819     }
820
821     if (m_state.fillPattern)
822         applyFillPattern();
823
824     bool drawOwnShadow = !isAcceleratedContext() && hasBlurredShadow() && !m_state.shadowsIgnoreTransforms; // Don't use ShadowBlur for canvas yet.
825     CGContextStateSaver stateSaver(context, drawOwnShadow);
826     if (drawOwnShadow) {
827         // Turn off CG shadows.
828         CGContextSetShadowWithColor(platformContext(), CGSizeZero, 0, 0);
829
830         ShadowBlur contextShadow(m_state);
831         contextShadow.drawRectShadow(*this, FloatRoundedRect(rect));
832     }
833
834     CGContextFillRect(context, rect);
835 }
836
837 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color)
838 {
839     if (paintingDisabled())
840         return;
841
842     if (isRecording()) {
843         m_displayListRecorder->fillRect(rect, color);
844         return;
845     }
846
847     CGContextRef context = platformContext();
848     Color oldFillColor = fillColor();
849
850     if (oldFillColor != color)
851         setCGFillColor(context, color);
852
853     bool drawOwnShadow = !isAcceleratedContext() && hasBlurredShadow() && !m_state.shadowsIgnoreTransforms; // Don't use ShadowBlur for canvas yet.
854     CGContextStateSaver stateSaver(context, drawOwnShadow);
855     if (drawOwnShadow) {
856         // Turn off CG shadows.
857         CGContextSetShadowWithColor(platformContext(), CGSizeZero, 0, 0);
858
859         ShadowBlur contextShadow(m_state);
860         contextShadow.drawRectShadow(*this, FloatRoundedRect(rect));
861     }
862
863     CGContextFillRect(context, rect);
864     
865     if (drawOwnShadow)
866         stateSaver.restore();
867
868     if (oldFillColor != color)
869         setCGFillColor(context, oldFillColor);
870 }
871
872 void GraphicsContext::platformFillRoundedRect(const FloatRoundedRect& rect, const Color& color)
873 {
874     if (paintingDisabled())
875         return;
876     
877     ASSERT(!isRecording());
878
879     CGContextRef context = platformContext();
880     Color oldFillColor = fillColor();
881
882     if (oldFillColor != color)
883         setCGFillColor(context, color);
884
885     bool drawOwnShadow = !isAcceleratedContext() && hasBlurredShadow() && !m_state.shadowsIgnoreTransforms; // Don't use ShadowBlur for canvas yet.
886     CGContextStateSaver stateSaver(context, drawOwnShadow);
887     if (drawOwnShadow) {
888         // Turn off CG shadows.
889         CGContextSetShadowWithColor(platformContext(), CGSizeZero, 0, 0);
890
891         ShadowBlur contextShadow(m_state);
892         contextShadow.drawRectShadow(*this, rect);
893     }
894
895     const FloatRect& r = rect.rect();
896     const FloatRoundedRect::Radii& radii = rect.radii();
897     bool equalWidths = (radii.topLeft().width() == radii.topRight().width() && radii.topRight().width() == radii.bottomLeft().width() && radii.bottomLeft().width() == radii.bottomRight().width());
898     bool equalHeights = (radii.topLeft().height() == radii.bottomLeft().height() && radii.bottomLeft().height() == radii.topRight().height() && radii.topRight().height() == radii.bottomRight().height());
899     bool hasCustomFill = m_state.fillGradient || m_state.fillPattern;
900     if (!hasCustomFill && equalWidths && equalHeights && radii.topLeft().width() * 2 == r.width() && radii.topLeft().height() * 2 == r.height())
901         CGContextFillEllipseInRect(context, r);
902     else {
903         Path path;
904         path.addRoundedRect(rect);
905         fillPath(path);
906     }
907
908     if (drawOwnShadow)
909         stateSaver.restore();
910
911     if (oldFillColor != color)
912         setCGFillColor(context, oldFillColor);
913 }
914
915 void GraphicsContext::fillRectWithRoundedHole(const FloatRect& rect, const FloatRoundedRect& roundedHoleRect, const Color& color)
916 {
917     if (paintingDisabled())
918         return;
919
920     if (isRecording()) {
921         m_displayListRecorder->fillRectWithRoundedHole(rect, roundedHoleRect, color);
922         return;
923     }
924
925     CGContextRef context = platformContext();
926
927     Path path;
928     path.addRect(rect);
929
930     if (!roundedHoleRect.radii().isZero())
931         path.addRoundedRect(roundedHoleRect);
932     else
933         path.addRect(roundedHoleRect.rect());
934
935     WindRule oldFillRule = fillRule();
936     Color oldFillColor = fillColor();
937
938     setFillRule(RULE_EVENODD);
939     setFillColor(color);
940
941     // fillRectWithRoundedHole() assumes that the edges of rect are clipped out, so we only care about shadows cast around inside the hole.
942     bool drawOwnShadow = !isAcceleratedContext() && hasBlurredShadow() && !m_state.shadowsIgnoreTransforms;
943     CGContextStateSaver stateSaver(context, drawOwnShadow);
944     if (drawOwnShadow) {
945         // Turn off CG shadows.
946         CGContextSetShadowWithColor(platformContext(), CGSizeZero, 0, 0);
947
948         ShadowBlur contextShadow(m_state);
949         contextShadow.drawInsetShadow(*this, rect, roundedHoleRect);
950     }
951
952     fillPath(path);
953
954     if (drawOwnShadow)
955         stateSaver.restore();
956     
957     setFillRule(oldFillRule);
958     setFillColor(oldFillColor);
959 }
960
961 void GraphicsContext::clip(const FloatRect& rect)
962 {
963     if (paintingDisabled())
964         return;
965
966     if (isRecording()) {
967         m_displayListRecorder->clip(rect);
968         return;
969     }
970
971     CGContextClipToRect(platformContext(), rect);
972     m_data->clip(rect);
973 }
974
975 void GraphicsContext::clipOut(const FloatRect& rect)
976 {
977     if (paintingDisabled())
978         return;
979
980     if (isRecording()) {
981         m_displayListRecorder->clipOut(rect);
982         return;
983     }
984
985     // FIXME: Using CGRectInfinite is much faster than getting the clip bounding box. However, due
986     // to <rdar://problem/12584492>, CGRectInfinite can't be used with an accelerated context that
987     // has certain transforms that aren't just a translation or a scale. And due to <rdar://problem/14634453>
988     // we cannot use it in for a printing context either.
989     const AffineTransform& ctm = getCTM();
990     bool canUseCGRectInfinite = CGContextGetType(platformContext()) != kCGContextTypePDF && (!isAcceleratedContext() || (!ctm.b() && !ctm.c()));
991     CGRect rects[2] = { canUseCGRectInfinite ? CGRectInfinite : CGContextGetClipBoundingBox(platformContext()), rect };
992     CGContextBeginPath(platformContext());
993     CGContextAddRects(platformContext(), rects, 2);
994     CGContextEOClip(platformContext());
995 }
996
997 void GraphicsContext::clipOut(const Path& path)
998 {
999     if (paintingDisabled())
1000         return;
1001
1002     if (isRecording()) {
1003         m_displayListRecorder->clipOut(path);
1004         return;
1005     }
1006
1007     CGContextBeginPath(platformContext());
1008     CGContextAddRect(platformContext(), CGContextGetClipBoundingBox(platformContext()));
1009     if (!path.isEmpty())
1010         CGContextAddPath(platformContext(), path.platformPath());
1011     CGContextEOClip(platformContext());
1012 }
1013
1014 void GraphicsContext::clipPath(const Path& path, WindRule clipRule)
1015 {
1016     if (paintingDisabled())
1017         return;
1018
1019     if (isRecording()) {
1020         m_displayListRecorder->clipPath(path, clipRule);
1021         return;
1022     }
1023
1024     CGContextRef context = platformContext();
1025     if (path.isEmpty())
1026         CGContextClipToRect(context, CGRectZero);
1027     else {
1028         CGContextBeginPath(platformContext());
1029         CGContextAddPath(platformContext(), path.platformPath());
1030
1031         if (clipRule == RULE_EVENODD)
1032             CGContextEOClip(context);
1033         else
1034             CGContextClip(context);
1035     }
1036     
1037     m_data->clip(path);
1038 }
1039
1040 IntRect GraphicsContext::clipBounds() const
1041 {
1042     if (paintingDisabled())
1043         return IntRect();
1044
1045     if (isRecording()) {
1046         WTFLogAlways("Getting the clip bounds not yet supported with display lists");
1047         return IntRect(-2048, -2048, 4096, 4096); // FIXME: display lists.
1048     }
1049
1050     return enclosingIntRect(CGContextGetClipBoundingBox(platformContext()));
1051 }
1052
1053 void GraphicsContext::beginPlatformTransparencyLayer(float opacity)
1054 {
1055     if (paintingDisabled())
1056         return;
1057
1058     ASSERT(!isRecording());
1059
1060     save();
1061
1062     CGContextRef context = platformContext();
1063     CGContextSetAlpha(context, opacity);
1064     CGContextBeginTransparencyLayer(context, 0);
1065     m_data->m_userToDeviceTransformKnownToBeIdentity = false;
1066 }
1067
1068 void GraphicsContext::endPlatformTransparencyLayer()
1069 {
1070     if (paintingDisabled())
1071         return;
1072
1073     ASSERT(!isRecording());
1074
1075     CGContextRef context = platformContext();
1076     CGContextEndTransparencyLayer(context);
1077
1078     restore();
1079 }
1080
1081 bool GraphicsContext::supportsTransparencyLayers()
1082 {
1083     return true;
1084 }
1085
1086 static void applyShadowOffsetWorkaroundIfNeeded(const GraphicsContext& context, CGFloat& xOffset, CGFloat& yOffset)
1087 {
1088 #if PLATFORM(IOS) || PLATFORM(WIN)
1089     UNUSED_PARAM(context);
1090     UNUSED_PARAM(xOffset);
1091     UNUSED_PARAM(yOffset);
1092 #else
1093     if (context.isAcceleratedContext())
1094         return;
1095
1096     if (CGContextDrawsWithCorrectShadowOffsets(context.platformContext()))
1097         return;
1098
1099     // Work around <rdar://problem/5539388> by ensuring that the offsets will get truncated
1100     // to the desired integer. Also see: <rdar://problem/10056277>
1101     static const CGFloat extraShadowOffset = narrowPrecisionToCGFloat(1.0 / 128);
1102     if (xOffset > 0)
1103         xOffset += extraShadowOffset;
1104     else if (xOffset < 0)
1105         xOffset -= extraShadowOffset;
1106
1107     if (yOffset > 0)
1108         yOffset += extraShadowOffset;
1109     else if (yOffset < 0)
1110         yOffset -= extraShadowOffset;
1111 #endif
1112 }
1113
1114 void GraphicsContext::setPlatformShadow(const FloatSize& offset, float blur, const Color& color)
1115 {
1116     if (paintingDisabled())
1117         return;
1118
1119     ASSERT(!isRecording());
1120     
1121     // FIXME: we could avoid the shadow setup cost when we know we'll render the shadow ourselves.
1122
1123     CGFloat xOffset = offset.width();
1124     CGFloat yOffset = offset.height();
1125     CGFloat blurRadius = blur;
1126     CGContextRef context = platformContext();
1127
1128     if (!m_state.shadowsIgnoreTransforms) {
1129         CGAffineTransform userToBaseCTM = getUserToBaseCTM(context);
1130
1131         CGFloat A = userToBaseCTM.a * userToBaseCTM.a + userToBaseCTM.b * userToBaseCTM.b;
1132         CGFloat B = userToBaseCTM.a * userToBaseCTM.c + userToBaseCTM.b * userToBaseCTM.d;
1133         CGFloat C = B;
1134         CGFloat D = userToBaseCTM.c * userToBaseCTM.c + userToBaseCTM.d * userToBaseCTM.d;
1135
1136         CGFloat smallEigenvalue = narrowPrecisionToCGFloat(sqrt(0.5 * ((A + D) - sqrt(4 * B * C + (A - D) * (A - D)))));
1137
1138         blurRadius = blur * smallEigenvalue;
1139
1140         CGSize offsetInBaseSpace = CGSizeApplyAffineTransform(offset, userToBaseCTM);
1141
1142         xOffset = offsetInBaseSpace.width;
1143         yOffset = offsetInBaseSpace.height;
1144     }
1145
1146     // Extreme "blur" values can make text drawing crash or take crazy long times, so clamp
1147     blurRadius = std::min(blurRadius, narrowPrecisionToCGFloat(1000.0));
1148
1149     applyShadowOffsetWorkaroundIfNeeded(*this, xOffset, yOffset);
1150
1151     // Check for an invalid color, as this means that the color was not set for the shadow
1152     // and we should therefore just use the default shadow color.
1153     if (!color.isValid())
1154         CGContextSetShadow(context, CGSizeMake(xOffset, yOffset), blurRadius);
1155     else
1156         CGContextSetShadowWithColor(context, CGSizeMake(xOffset, yOffset), blurRadius, cachedCGColor(color));
1157 }
1158
1159 void GraphicsContext::clearPlatformShadow()
1160 {
1161     if (paintingDisabled())
1162         return;
1163     CGContextSetShadowWithColor(platformContext(), CGSizeZero, 0, 0);
1164 }
1165
1166 void GraphicsContext::setMiterLimit(float limit)
1167 {
1168     if (paintingDisabled())
1169         return;
1170
1171     if (isRecording()) {
1172         // Maybe this should be part of the state.
1173         m_displayListRecorder->setMiterLimit(limit);
1174         return;
1175     }
1176
1177     CGContextSetMiterLimit(platformContext(), limit);
1178 }
1179
1180 void GraphicsContext::clearRect(const FloatRect& r)
1181 {
1182     if (paintingDisabled())
1183         return;
1184
1185     if (isRecording()) {
1186         m_displayListRecorder->clearRect(r);
1187         return;
1188     }
1189
1190     CGContextClearRect(platformContext(), r);
1191 }
1192
1193 void GraphicsContext::strokeRect(const FloatRect& rect, float lineWidth)
1194 {
1195     if (paintingDisabled())
1196         return;
1197
1198     if (isRecording()) {
1199         m_displayListRecorder->strokeRect(rect, lineWidth);
1200         return;
1201     }
1202
1203     CGContextRef context = platformContext();
1204
1205     if (m_state.strokeGradient) {
1206         if (hasShadow()) {
1207             const float doubleLineWidth = lineWidth * 2;
1208             float adjustedWidth = ceilf(rect.width() + doubleLineWidth);
1209             float adjustedHeight = ceilf(rect.height() + doubleLineWidth);
1210             FloatSize layerSize = getCTM().mapSize(FloatSize(adjustedWidth, adjustedHeight));
1211
1212             CGLayerRef layer = CGLayerCreateWithContext(context, layerSize, 0);
1213
1214             CGContextRef layerContext = CGLayerGetContext(layer);
1215             m_state.strokeThickness = lineWidth;
1216             CGContextSetLineWidth(layerContext, lineWidth);
1217
1218             // Compensate for the line width, otherwise the layer's top-left corner would be
1219             // aligned with the rect's top-left corner. This would result in leaving pixels out of
1220             // the layer on the left and top sides.
1221             const float translationX = lineWidth - rect.x();
1222             const float translationY = lineWidth - rect.y();
1223             CGContextScaleCTM(layerContext, layerSize.width() / adjustedWidth, layerSize.height() / adjustedHeight);
1224             CGContextTranslateCTM(layerContext, translationX, translationY);
1225
1226             CGContextAddRect(layerContext, rect);
1227             CGContextReplacePathWithStrokedPath(layerContext);
1228             CGContextClip(layerContext);
1229             CGContextConcatCTM(layerContext, m_state.strokeGradient->gradientSpaceTransform());
1230             m_state.strokeGradient->paint(layerContext);
1231
1232             const float destinationX = roundf(rect.x() - lineWidth);
1233             const float destinationY = roundf(rect.y() - lineWidth);
1234             CGContextDrawLayerInRect(context, CGRectMake(destinationX, destinationY, adjustedWidth, adjustedHeight), layer);
1235             CGLayerRelease(layer);
1236         } else {
1237             CGContextStateSaver stateSaver(context);
1238             setStrokeThickness(lineWidth);
1239             CGContextAddRect(context, rect);
1240             CGContextReplacePathWithStrokedPath(context);
1241             CGContextClip(context);
1242             CGContextConcatCTM(context, m_state.strokeGradient->gradientSpaceTransform());
1243             m_state.strokeGradient->paint(this);
1244         }
1245         return;
1246     }
1247
1248     if (m_state.strokePattern)
1249         applyStrokePattern();
1250
1251     // Using CGContextAddRect and CGContextStrokePath to stroke rect rather than
1252     // convenience functions (CGContextStrokeRect/CGContextStrokeRectWithWidth).
1253     // The convenience functions currently (in at least OSX 10.9.4) fail to
1254     // apply some attributes of the graphics state in certain cases
1255     // (as identified in https://bugs.webkit.org/show_bug.cgi?id=132948)
1256     CGContextStateSaver stateSaver(context);
1257     setStrokeThickness(lineWidth);
1258
1259     CGContextAddRect(context, rect);
1260     CGContextStrokePath(context);
1261 }
1262
1263 void GraphicsContext::setLineCap(LineCap cap)
1264 {
1265     if (paintingDisabled())
1266         return;
1267
1268     if (isRecording()) {
1269         m_displayListRecorder->setLineCap(cap);
1270         return;
1271     }
1272
1273     switch (cap) {
1274     case ButtCap:
1275         CGContextSetLineCap(platformContext(), kCGLineCapButt);
1276         break;
1277     case RoundCap:
1278         CGContextSetLineCap(platformContext(), kCGLineCapRound);
1279         break;
1280     case SquareCap:
1281         CGContextSetLineCap(platformContext(), kCGLineCapSquare);
1282         break;
1283     }
1284 }
1285
1286 void GraphicsContext::setLineDash(const DashArray& dashes, float dashOffset)
1287 {
1288     if (paintingDisabled())
1289         return;
1290
1291     if (isRecording()) {
1292         m_displayListRecorder->setLineDash(dashes, dashOffset);
1293         return;
1294     }
1295
1296     if (dashOffset < 0) {
1297         float length = 0;
1298         for (size_t i = 0; i < dashes.size(); ++i)
1299             length += static_cast<float>(dashes[i]);
1300         if (length)
1301             dashOffset = fmod(dashOffset, length) + length;
1302     }
1303     CGContextSetLineDash(platformContext(), dashOffset, dashes.data(), dashes.size());
1304 }
1305
1306 void GraphicsContext::setLineJoin(LineJoin join)
1307 {
1308     if (paintingDisabled())
1309         return;
1310
1311     if (isRecording()) {
1312         m_displayListRecorder->setLineJoin(join);
1313         return;
1314     }
1315
1316     switch (join) {
1317     case MiterJoin:
1318         CGContextSetLineJoin(platformContext(), kCGLineJoinMiter);
1319         break;
1320     case RoundJoin:
1321         CGContextSetLineJoin(platformContext(), kCGLineJoinRound);
1322         break;
1323     case BevelJoin:
1324         CGContextSetLineJoin(platformContext(), kCGLineJoinBevel);
1325         break;
1326     }
1327 }
1328
1329 void GraphicsContext::canvasClip(const Path& path, WindRule fillRule)
1330 {
1331     clipPath(path, fillRule);
1332 }
1333
1334 void GraphicsContext::scale(const FloatSize& size)
1335 {
1336     if (paintingDisabled())
1337         return;
1338
1339     if (isRecording()) {
1340         m_displayListRecorder->scale(size);
1341         return;
1342     }
1343
1344     CGContextScaleCTM(platformContext(), size.width(), size.height());
1345     m_data->scale(size);
1346     m_data->m_userToDeviceTransformKnownToBeIdentity = false;
1347 }
1348
1349 void GraphicsContext::rotate(float angle)
1350 {
1351     if (paintingDisabled())
1352         return;
1353
1354     if (isRecording()) {
1355         m_displayListRecorder->rotate(angle);
1356         return;
1357     }
1358
1359     CGContextRotateCTM(platformContext(), angle);
1360     m_data->rotate(angle);
1361     m_data->m_userToDeviceTransformKnownToBeIdentity = false;
1362 }
1363
1364 void GraphicsContext::translate(float x, float y)
1365 {
1366     if (paintingDisabled())
1367         return;
1368
1369     if (isRecording()) {
1370         m_displayListRecorder->translate(x, y);
1371         return;
1372     }
1373
1374     CGContextTranslateCTM(platformContext(), x, y);
1375     m_data->translate(x, y);
1376     m_data->m_userToDeviceTransformKnownToBeIdentity = false;
1377 }
1378
1379 void GraphicsContext::concatCTM(const AffineTransform& transform)
1380 {
1381     if (paintingDisabled())
1382         return;
1383
1384     if (isRecording()) {
1385         m_displayListRecorder->concatCTM(transform);
1386         return;
1387     }
1388
1389     CGContextConcatCTM(platformContext(), transform);
1390     m_data->concatCTM(transform);
1391     m_data->m_userToDeviceTransformKnownToBeIdentity = false;
1392 }
1393
1394 void GraphicsContext::setCTM(const AffineTransform& transform)
1395 {
1396     if (paintingDisabled())
1397         return;
1398
1399     if (isRecording()) {
1400         WTFLogAlways("GraphicsContext::setCTM() is not compatible with recording contexts.");
1401         return;
1402     }
1403
1404     CGContextSetCTM(platformContext(), transform);
1405     m_data->setCTM(transform);
1406     m_data->m_userToDeviceTransformKnownToBeIdentity = false;
1407 }
1408
1409 AffineTransform GraphicsContext::getCTM(IncludeDeviceScale includeScale) const
1410 {
1411     if (paintingDisabled())
1412         return AffineTransform();
1413
1414     if (isRecording()) {
1415         WTFLogAlways("GraphicsContext::getCTM() is not yet compatible with recording contexts.");
1416         return AffineTransform();
1417     }
1418
1419     // The CTM usually includes the deviceScaleFactor except in WebKit 1 when the
1420     // content is non-composited, since the scale factor is integrated at a lower
1421     // level. To guarantee the deviceScale is included, we can use this CG API.
1422     if (includeScale == DefinitelyIncludeDeviceScale)
1423         return CGContextGetUserSpaceToDeviceSpaceTransform(platformContext());
1424
1425     return CGContextGetCTM(platformContext());
1426 }
1427
1428 FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& rect, RoundingMode roundingMode)
1429 {
1430     if (paintingDisabled())
1431         return rect;
1432
1433     if (isRecording()) {
1434         WTFLogAlways("GraphicsContext::roundToDevicePixels() is not yet compatible with recording contexts.");
1435         return rect;
1436     }
1437
1438     // It is not enough just to round to pixels in device space. The rotation part of the
1439     // affine transform matrix to device space can mess with this conversion if we have a
1440     // rotating image like the hands of the world clock widget. We just need the scale, so
1441     // we get the affine transform matrix and extract the scale.
1442
1443     if (m_data->m_userToDeviceTransformKnownToBeIdentity)
1444         return roundedIntRect(rect);
1445
1446     CGAffineTransform deviceMatrix = CGContextGetUserSpaceToDeviceSpaceTransform(platformContext());
1447     if (CGAffineTransformIsIdentity(deviceMatrix)) {
1448         m_data->m_userToDeviceTransformKnownToBeIdentity = true;
1449         return roundedIntRect(rect);
1450     }
1451
1452     float deviceScaleX = sqrtf(deviceMatrix.a * deviceMatrix.a + deviceMatrix.b * deviceMatrix.b);
1453     float deviceScaleY = sqrtf(deviceMatrix.c * deviceMatrix.c + deviceMatrix.d * deviceMatrix.d);
1454
1455     CGPoint deviceOrigin = CGPointMake(rect.x() * deviceScaleX, rect.y() * deviceScaleY);
1456     CGPoint deviceLowerRight = CGPointMake((rect.x() + rect.width()) * deviceScaleX,
1457         (rect.y() + rect.height()) * deviceScaleY);
1458
1459     deviceOrigin.x = roundf(deviceOrigin.x);
1460     deviceOrigin.y = roundf(deviceOrigin.y);
1461     if (roundingMode == RoundAllSides) {
1462         deviceLowerRight.x = roundf(deviceLowerRight.x);
1463         deviceLowerRight.y = roundf(deviceLowerRight.y);
1464     } else {
1465         deviceLowerRight.x = deviceOrigin.x + roundf(rect.width() * deviceScaleX);
1466         deviceLowerRight.y = deviceOrigin.y + roundf(rect.height() * deviceScaleY);
1467     }
1468
1469     // Don't let the height or width round to 0 unless either was originally 0
1470     if (deviceOrigin.y == deviceLowerRight.y && rect.height())
1471         deviceLowerRight.y += 1;
1472     if (deviceOrigin.x == deviceLowerRight.x && rect.width())
1473         deviceLowerRight.x += 1;
1474
1475     FloatPoint roundedOrigin = FloatPoint(deviceOrigin.x / deviceScaleX, deviceOrigin.y / deviceScaleY);
1476     FloatPoint roundedLowerRight = FloatPoint(deviceLowerRight.x / deviceScaleX, deviceLowerRight.y / deviceScaleY);
1477     return FloatRect(roundedOrigin, roundedLowerRight - roundedOrigin);
1478 }
1479
1480 void GraphicsContext::drawLineForText(const FloatPoint& point, float width, bool printing, bool doubleLines, StrokeStyle strokeStyle)
1481 {
1482     DashArray widths;
1483     widths.append(width);
1484     widths.append(0);
1485     drawLinesForText(point, widths, printing, doubleLines, strokeStyle);
1486 }
1487
1488 void GraphicsContext::drawLinesForText(const FloatPoint& point, const DashArray& widths, bool printing, bool doubleLines, StrokeStyle strokeStyle)
1489 {
1490     if (paintingDisabled())
1491         return;
1492
1493     if (!widths.size())
1494         return;
1495
1496     if (isRecording()) {
1497         m_displayListRecorder->drawLinesForText(point, widths, printing, doubleLines, strokeThickness());
1498         return;
1499     }
1500
1501     Color localStrokeColor(strokeColor());
1502
1503     FloatRect bounds = computeLineBoundsAndAntialiasingModeForText(point, widths.last(), printing, localStrokeColor);
1504     bool fillColorIsNotEqualToStrokeColor = fillColor() != localStrokeColor;
1505     
1506     Vector<CGRect, 4> dashBounds;
1507     ASSERT(!(widths.size() % 2));
1508     dashBounds.reserveInitialCapacity(dashBounds.size() / 2);
1509
1510     float dashWidth = 0;
1511     switch (strokeStyle) {
1512     case DottedStroke:
1513         dashWidth = bounds.height();
1514         break;
1515     case DashedStroke:
1516         dashWidth = 2 * bounds.height();
1517         break;
1518     case SolidStroke:
1519     default:
1520         break;
1521     }
1522
1523     for (size_t i = 0; i < widths.size(); i += 2) {
1524         auto left = widths[i];
1525         auto width = widths[i+1] - widths[i];
1526         if (!dashWidth)
1527             dashBounds.append(CGRectMake(bounds.x() + left, bounds.y(), width, bounds.height()));
1528         else {
1529             auto startParticle = static_cast<unsigned>(std::ceil(left / (2 * dashWidth)));
1530             auto endParticle = static_cast<unsigned>((left + width) / (2 * dashWidth));
1531             for (unsigned j = startParticle; j < endParticle; ++j)
1532                 dashBounds.append(CGRectMake(bounds.x() + j * 2 * dashWidth, bounds.y(), dashWidth, bounds.height()));
1533         }
1534     }
1535
1536     if (doubleLines) {
1537         // The space between double underlines is equal to the height of the underline
1538         for (size_t i = 0; i < widths.size(); i += 2)
1539             dashBounds.append(CGRectMake(bounds.x() + widths[i], bounds.y() + 2 * bounds.height(), widths[i+1] - widths[i], bounds.height()));
1540     }
1541
1542     if (fillColorIsNotEqualToStrokeColor)
1543         setCGFillColor(platformContext(), localStrokeColor);
1544
1545     CGContextFillRects(platformContext(), dashBounds.data(), dashBounds.size());
1546
1547     if (fillColorIsNotEqualToStrokeColor)
1548         setCGFillColor(platformContext(), fillColor());
1549 }
1550
1551 void GraphicsContext::setURLForRect(const URL& link, const FloatRect& destRect)
1552 {
1553 #if !PLATFORM(IOS)
1554     if (paintingDisabled())
1555         return;
1556
1557     if (isRecording()) {
1558         WTFLogAlways("GraphicsContext::setURLForRect() is not yet compatible with recording contexts.");
1559         return; // FIXME for display lists.
1560     }
1561
1562     RetainPtr<CFURLRef> urlRef = link.createCFURL();
1563     if (!urlRef)
1564         return;
1565
1566     CGContextRef context = platformContext();
1567
1568     FloatRect rect = destRect;
1569     // Get the bounding box to handle clipping.
1570     rect.intersect(CGContextGetClipBoundingBox(context));
1571
1572     CGPDFContextSetURLForRect(context, urlRef.get(), CGRectApplyAffineTransform(rect, CGContextGetCTM(context)));
1573 #else
1574     UNUSED_PARAM(link);
1575     UNUSED_PARAM(destRect);
1576 #endif
1577 }
1578
1579 void GraphicsContext::setPlatformImageInterpolationQuality(InterpolationQuality mode)
1580 {
1581     ASSERT(!paintingDisabled());
1582
1583     CGInterpolationQuality quality = kCGInterpolationDefault;
1584     switch (mode) {
1585     case InterpolationDefault:
1586         quality = kCGInterpolationDefault;
1587         break;
1588     case InterpolationNone:
1589         quality = kCGInterpolationNone;
1590         break;
1591     case InterpolationLow:
1592         quality = kCGInterpolationLow;
1593         break;
1594     case InterpolationMedium:
1595         quality = kCGInterpolationMedium;
1596         break;
1597     case InterpolationHigh:
1598         quality = kCGInterpolationHigh;
1599         break;
1600     }
1601     CGContextSetInterpolationQuality(platformContext(), quality);
1602 }
1603
1604 void GraphicsContext::setIsCALayerContext(bool isLayerContext)
1605 {
1606     if (paintingDisabled())
1607         return;
1608
1609     // FIXME
1610     if (isRecording())
1611         return;
1612
1613     if (isLayerContext)
1614         m_data->m_contextFlags |= IsLayerCGContext;
1615     else
1616         m_data->m_contextFlags &= ~IsLayerCGContext;
1617 }
1618
1619 bool GraphicsContext::isCALayerContext() const
1620 {
1621     if (paintingDisabled())
1622         return false;
1623
1624     // FIXME
1625     if (isRecording())
1626         return false;
1627
1628     return m_data->m_contextFlags & IsLayerCGContext;
1629 }
1630
1631 void GraphicsContext::setIsAcceleratedContext(bool isAccelerated)
1632 {
1633     if (paintingDisabled())
1634         return;
1635
1636     // FIXME
1637     if (isRecording())
1638         return;
1639
1640     if (isAccelerated)
1641         m_data->m_contextFlags |= IsAcceleratedCGContext;
1642     else
1643         m_data->m_contextFlags &= ~IsAcceleratedCGContext;
1644 }
1645
1646 bool GraphicsContext::isAcceleratedContext() const
1647 {
1648     if (paintingDisabled())
1649         return false;
1650
1651     // FIXME
1652     if (isRecording())
1653         return false;
1654
1655     return m_data->m_contextFlags & IsAcceleratedCGContext;
1656 }
1657
1658 void GraphicsContext::setPlatformTextDrawingMode(TextDrawingModeFlags mode)
1659 {
1660     if (paintingDisabled())
1661         return;
1662
1663     ASSERT(!isRecording());
1664
1665     CGContextRef context = platformContext();
1666     switch (mode) {
1667     case TextModeFill:
1668         CGContextSetTextDrawingMode(context, kCGTextFill);
1669         break;
1670     case TextModeStroke:
1671         CGContextSetTextDrawingMode(context, kCGTextStroke);
1672         break;
1673     case TextModeFill | TextModeStroke:
1674         CGContextSetTextDrawingMode(context, kCGTextFillStroke);
1675         break;
1676     default:
1677         break;
1678     }
1679 }
1680
1681 void GraphicsContext::setPlatformStrokeColor(const Color& color)
1682 {
1683     if (paintingDisabled())
1684         return;
1685
1686     ASSERT(!isRecording());
1687
1688     setCGStrokeColor(platformContext(), color);
1689 }
1690
1691 void GraphicsContext::setPlatformStrokeThickness(float thickness)
1692 {
1693     if (paintingDisabled())
1694         return;
1695
1696     ASSERT(!isRecording());
1697
1698     CGContextSetLineWidth(platformContext(), std::max(thickness, 0.f));
1699 }
1700
1701 void GraphicsContext::setPlatformFillColor(const Color& color)
1702 {
1703     if (paintingDisabled())
1704         return;
1705
1706     ASSERT(!isRecording());
1707
1708     setCGFillColor(platformContext(), color);
1709 }
1710
1711 void GraphicsContext::setPlatformShouldAntialias(bool enable)
1712 {
1713     if (paintingDisabled())
1714         return;
1715
1716     ASSERT(!isRecording());
1717
1718     CGContextSetShouldAntialias(platformContext(), enable);
1719 }
1720
1721 void GraphicsContext::setPlatformShouldSmoothFonts(bool enable)
1722 {
1723     if (paintingDisabled())
1724         return;
1725
1726     ASSERT(!isRecording());
1727
1728     CGContextSetShouldSmoothFonts(platformContext(), enable);
1729 }
1730
1731 void GraphicsContext::setPlatformAlpha(float alpha)
1732 {
1733     if (paintingDisabled())
1734         return;
1735
1736     ASSERT(!isRecording());
1737
1738     CGContextSetAlpha(platformContext(), alpha);
1739 }
1740
1741 void GraphicsContext::setPlatformCompositeOperation(CompositeOperator mode, BlendMode blendMode)
1742 {
1743     if (paintingDisabled())
1744         return;
1745
1746     ASSERT(!isRecording());
1747
1748     CGBlendMode target = kCGBlendModeNormal;
1749     if (blendMode != BlendModeNormal) {
1750         switch (blendMode) {
1751         case BlendModeMultiply:
1752             target = kCGBlendModeMultiply;
1753             break;
1754         case BlendModeScreen:
1755             target = kCGBlendModeScreen;
1756             break;
1757         case BlendModeOverlay:
1758             target = kCGBlendModeOverlay;
1759             break;
1760         case BlendModeDarken:
1761             target = kCGBlendModeDarken;
1762             break;
1763         case BlendModeLighten:
1764             target = kCGBlendModeLighten;
1765             break;
1766         case BlendModeColorDodge:
1767             target = kCGBlendModeColorDodge;
1768             break;
1769         case BlendModeColorBurn:
1770             target = kCGBlendModeColorBurn;
1771             break;
1772         case BlendModeHardLight:
1773             target = kCGBlendModeHardLight;
1774             break;
1775         case BlendModeSoftLight:
1776             target = kCGBlendModeSoftLight;
1777             break;
1778         case BlendModeDifference:
1779             target = kCGBlendModeDifference;
1780             break;
1781         case BlendModeExclusion:
1782             target = kCGBlendModeExclusion;
1783             break;
1784         case BlendModeHue:
1785             target = kCGBlendModeHue;
1786             break;
1787         case BlendModeSaturation:
1788             target = kCGBlendModeSaturation;
1789             break;
1790         case BlendModeColor:
1791             target = kCGBlendModeColor;
1792             break;
1793         case BlendModeLuminosity:
1794             target = kCGBlendModeLuminosity;
1795             break;
1796         case BlendModePlusDarker:
1797             target = kCGBlendModePlusDarker;
1798             break;
1799         case BlendModePlusLighter:
1800             target = kCGBlendModePlusLighter;
1801             break;
1802         default:
1803             break;
1804         }
1805     } else {
1806         switch (mode) {
1807         case CompositeClear:
1808             target = kCGBlendModeClear;
1809             break;
1810         case CompositeCopy:
1811             target = kCGBlendModeCopy;
1812             break;
1813         case CompositeSourceOver:
1814             // kCGBlendModeNormal
1815             break;
1816         case CompositeSourceIn:
1817             target = kCGBlendModeSourceIn;
1818             break;
1819         case CompositeSourceOut:
1820             target = kCGBlendModeSourceOut;
1821             break;
1822         case CompositeSourceAtop:
1823             target = kCGBlendModeSourceAtop;
1824             break;
1825         case CompositeDestinationOver:
1826             target = kCGBlendModeDestinationOver;
1827             break;
1828         case CompositeDestinationIn:
1829             target = kCGBlendModeDestinationIn;
1830             break;
1831         case CompositeDestinationOut:
1832             target = kCGBlendModeDestinationOut;
1833             break;
1834         case CompositeDestinationAtop:
1835             target = kCGBlendModeDestinationAtop;
1836             break;
1837         case CompositeXOR:
1838             target = kCGBlendModeXOR;
1839             break;
1840         case CompositePlusDarker:
1841             target = kCGBlendModePlusDarker;
1842             break;
1843         case CompositePlusLighter:
1844             target = kCGBlendModePlusLighter;
1845             break;
1846         case CompositeDifference:
1847             target = kCGBlendModeDifference;
1848             break;
1849         }
1850     }
1851     CGContextSetBlendMode(platformContext(), target);
1852 }
1853
1854 void GraphicsContext::platformApplyDeviceScaleFactor(float deviceScaleFactor)
1855 {
1856     if (paintingDisabled())
1857         return;
1858
1859     ASSERT(!isRecording());
1860
1861     // CoreGraphics expects the base CTM of a HiDPI context to have the scale factor applied to it.
1862     // Failing to change the base level CTM will cause certain CG features, such as focus rings,
1863     // to draw with a scale factor of 1 rather than the actual scale factor.
1864     CGContextSetBaseCTM(platformContext(), CGAffineTransformScale(CGContextGetBaseCTM(platformContext()), deviceScaleFactor, deviceScaleFactor));
1865 }
1866
1867 void GraphicsContext::platformFillEllipse(const FloatRect& ellipse)
1868 {
1869     if (paintingDisabled())
1870         return;
1871
1872     ASSERT(!isRecording());
1873
1874     // CGContextFillEllipseInRect only supports solid colors.
1875     if (m_state.fillGradient || m_state.fillPattern) {
1876         fillEllipseAsPath(ellipse);
1877         return;
1878     }
1879
1880     CGContextRef context = platformContext();
1881     CGContextFillEllipseInRect(context, ellipse);
1882 }
1883
1884 void GraphicsContext::platformStrokeEllipse(const FloatRect& ellipse)
1885 {
1886     if (paintingDisabled())
1887         return;
1888
1889     ASSERT(!isRecording());
1890
1891     // CGContextStrokeEllipseInRect only supports solid colors.
1892     if (m_state.strokeGradient || m_state.strokePattern) {
1893         strokeEllipseAsPath(ellipse);
1894         return;
1895     }
1896
1897     CGContextRef context = platformContext();
1898     CGContextStrokeEllipseInRect(context, ellipse);
1899 }
1900
1901 bool GraphicsContext::supportsInternalLinks() const
1902 {
1903     return true;
1904 }
1905
1906 void GraphicsContext::setDestinationForRect(const String& name, const FloatRect& destRect)
1907 {
1908     if (paintingDisabled())
1909         return;
1910
1911     CGContextRef context = platformContext();
1912
1913     FloatRect rect = destRect;
1914     rect.intersect(CGContextGetClipBoundingBox(context));
1915
1916     CGRect transformedRect = CGRectApplyAffineTransform(rect, CGContextGetCTM(context));
1917     CGPDFContextSetDestinationForRect(context, name.createCFString().get(), transformedRect);
1918 }
1919
1920 void GraphicsContext::addDestinationAtPoint(const String& name, const FloatPoint& position)
1921 {
1922     if (paintingDisabled())
1923         return;
1924
1925     CGContextRef context = platformContext();
1926
1927     CGPoint transformedPoint = CGPointApplyAffineTransform(position, CGContextGetCTM(context));
1928     CGPDFContextAddDestinationAtPoint(context, name.createCFString().get(), transformedPoint);
1929 }
1930
1931 }
1932
1933 #endif