1 /*
2 * Copyright (C) 2003, 2004, 2005, 2006, 2007 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 COMPUTER, 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 COMPUTER, 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 #define _USE_MATH_DEFINES 1
28 #include "config.h"
29 #include "GraphicsContext.h"
30
31 #include "TransformationMatrix.h"
32 #include "FloatConversion.h"
33 #include "GraphicsContextPrivate.h"
34 #include "GraphicsContextPlatformPrivateCG.h"
35 #include "ImageBuffer.h"
36 #include "KURL.h"
37 #include "Path.h"
38 #include "Pattern.h"
39 #include <CoreGraphics/CGBitmapContext.h>
40 #include <CoreGraphics/CGPDFContext.h>
41 #include <wtf/MathExtras.h>
42 #include <wtf/OwnArrayPtr.h>
43 #include <wtf/RetainPtr.h>
44
45 #if PLATFORM(MAC) && !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD)
46 #define HAVE_CG_INTERPOLATION_MEDIUM 1
47 #endif
48
49 using namespace std;
50
51 namespace WebCore {
52
setCGFillColor(CGContextRef context,const Color & color)53 static void setCGFillColor(CGContextRef context, const Color& color)
54 {
55 CGFloat red, green, blue, alpha;
56 color.getRGBA(red, green, blue, alpha);
57 CGContextSetRGBFillColor(context, red, green, blue, alpha);
58 }
59
setCGStrokeColor(CGContextRef context,const Color & color)60 static void setCGStrokeColor(CGContextRef context, const Color& color)
61 {
62 CGFloat red, green, blue, alpha;
63 color.getRGBA(red, green, blue, alpha);
64 CGContextSetRGBStrokeColor(context, red, green, blue, alpha);
65 }
66
GraphicsContext(CGContextRef cgContext)67 GraphicsContext::GraphicsContext(CGContextRef cgContext)
68 : m_common(createGraphicsContextPrivate())
69 , m_data(new GraphicsContextPlatformPrivate(cgContext))
70 {
71 setPaintingDisabled(!cgContext);
72 if (cgContext) {
73 // Make sure the context starts in sync with our state.
74 setPlatformFillColor(fillColor());
75 setPlatformStrokeColor(strokeColor());
76 }
77 }
78
~GraphicsContext()79 GraphicsContext::~GraphicsContext()
80 {
81 destroyGraphicsContextPrivate(m_common);
82 delete m_data;
83 }
84
platformContext() const85 CGContextRef GraphicsContext::platformContext() const
86 {
87 ASSERT(!paintingDisabled());
88 ASSERT(m_data->m_cgContext);
89 return m_data->m_cgContext;
90 }
91
savePlatformState()92 void GraphicsContext::savePlatformState()
93 {
94 // Note: Do not use this function within this class implementation, since we want to avoid the extra
95 // save of the secondary context (in GraphicsContextPlatformPrivateCG.h).
96 CGContextSaveGState(platformContext());
97 m_data->save();
98 }
99
restorePlatformState()100 void GraphicsContext::restorePlatformState()
101 {
102 // Note: Do not use this function within this class implementation, since we want to avoid the extra
103 // restore of the secondary context (in GraphicsContextPlatformPrivateCG.h).
104 CGContextRestoreGState(platformContext());
105 m_data->restore();
106 m_data->m_userToDeviceTransformKnownToBeIdentity = false;
107 }
108
109 // Draws a filled rectangle with a stroked border.
drawRect(const IntRect & rect)110 void GraphicsContext::drawRect(const IntRect& rect)
111 {
112 // FIXME: this function does not handle patterns and gradients
113 // like drawPath does, it probably should.
114 if (paintingDisabled())
115 return;
116
117 CGContextRef context = platformContext();
118
119 if (fillColor().alpha())
120 CGContextFillRect(context, rect);
121
122 if (strokeStyle() != NoStroke && strokeColor().alpha()) {
123 // We do a fill of four rects to simulate the stroke of a border.
124 Color oldFillColor = fillColor();
125 if (oldFillColor != strokeColor())
126 setCGFillColor(context, strokeColor());
127 CGRect rects[4] = {
128 FloatRect(rect.x(), rect.y(), rect.width(), 1),
129 FloatRect(rect.x(), rect.bottom() - 1, rect.width(), 1),
130 FloatRect(rect.x(), rect.y() + 1, 1, rect.height() - 2),
131 FloatRect(rect.right() - 1, rect.y() + 1, 1, rect.height() - 2)
132 };
133 CGContextFillRects(context, rects, 4);
134 if (oldFillColor != strokeColor())
135 setCGFillColor(context, oldFillColor);
136 }
137 }
138
139 // This is only used to draw borders.
drawLine(const IntPoint & point1,const IntPoint & point2)140 void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
141 {
142 if (paintingDisabled())
143 return;
144
145 if (strokeStyle() == NoStroke || !strokeColor().alpha())
146 return;
147
148 float width = strokeThickness();
149
150 FloatPoint p1 = point1;
151 FloatPoint p2 = point2;
152 bool isVerticalLine = (p1.x() == p2.x());
153
154 // For odd widths, we add in 0.5 to the appropriate x/y so that the float arithmetic
155 // works out. For example, with a border width of 3, KHTML will pass us (y1+y2)/2, e.g.,
156 // (50+53)/2 = 103/2 = 51 when we want 51.5. It is always true that an even width gave
157 // us a perfect position, but an odd width gave us a position that is off by exactly 0.5.
158 if (strokeStyle() == DottedStroke || strokeStyle() == DashedStroke) {
159 if (isVerticalLine) {
160 p1.move(0, width);
161 p2.move(0, -width);
162 } else {
163 p1.move(width, 0);
164 p2.move(-width, 0);
165 }
166 }
167
168 if (((int)width) % 2) {
169 if (isVerticalLine) {
170 // We're a vertical line. Adjust our x.
171 p1.move(0.5f, 0.0f);
172 p2.move(0.5f, 0.0f);
173 } else {
174 // We're a horizontal line. Adjust our y.
175 p1.move(0.0f, 0.5f);
176 p2.move(0.0f, 0.5f);
177 }
178 }
179
180 int patWidth = 0;
181 switch (strokeStyle()) {
182 case NoStroke:
183 case SolidStroke:
184 break;
185 case DottedStroke:
186 patWidth = (int)width;
187 break;
188 case DashedStroke:
189 patWidth = 3 * (int)width;
190 break;
191 }
192
193 CGContextRef context = platformContext();
194
195 if (shouldAntialias())
196 CGContextSetShouldAntialias(context, false);
197
198 if (patWidth) {
199 CGContextSaveGState(context);
200
201 // Do a rect fill of our endpoints. This ensures we always have the
202 // appearance of being a border. We then draw the actual dotted/dashed line.
203 setCGFillColor(context, strokeColor()); // The save/restore make it safe to mutate the fill color here without setting it back to the old color.
204 if (isVerticalLine) {
205 CGContextFillRect(context, FloatRect(p1.x() - width / 2, p1.y() - width, width, width));
206 CGContextFillRect(context, FloatRect(p2.x() - width / 2, p2.y(), width, width));
207 } else {
208 CGContextFillRect(context, FloatRect(p1.x() - width, p1.y() - width / 2, width, width));
209 CGContextFillRect(context, FloatRect(p2.x(), p2.y() - width / 2, width, width));
210 }
211
212 // Example: 80 pixels with a width of 30 pixels.
213 // Remainder is 20. The maximum pixels of line we could paint
214 // will be 50 pixels.
215 int distance = (isVerticalLine ? (point2.y() - point1.y()) : (point2.x() - point1.x())) - 2*(int)width;
216 int remainder = distance % patWidth;
217 int coverage = distance - remainder;
218 int numSegments = coverage / patWidth;
219
220 float patternOffset = 0.0f;
221 // Special case 1px dotted borders for speed.
222 if (patWidth == 1)
223 patternOffset = 1.0f;
224 else {
225 bool evenNumberOfSegments = numSegments % 2 == 0;
226 if (remainder)
227 evenNumberOfSegments = !evenNumberOfSegments;
228 if (evenNumberOfSegments) {
229 if (remainder) {
230 patternOffset += patWidth - remainder;
231 patternOffset += remainder / 2;
232 } else
233 patternOffset = patWidth / 2;
234 } else {
235 if (remainder)
236 patternOffset = (patWidth - remainder)/2;
237 }
238 }
239
240 const CGFloat dottedLine[2] = { patWidth, patWidth };
241 CGContextSetLineDash(context, patternOffset, dottedLine, 2);
242 }
243
244 CGContextBeginPath(context);
245 CGContextMoveToPoint(context, p1.x(), p1.y());
246 CGContextAddLineToPoint(context, p2.x(), p2.y());
247
248 CGContextStrokePath(context);
249
250 if (patWidth)
251 CGContextRestoreGState(context);
252
253 if (shouldAntialias())
254 CGContextSetShouldAntialias(context, true);
255 }
256
257 // This method is only used to draw the little circles used in lists.
drawEllipse(const IntRect & rect)258 void GraphicsContext::drawEllipse(const IntRect& rect)
259 {
260 // FIXME: CG added CGContextAddEllipseinRect in Tiger, so we should be able to quite easily draw an ellipse.
261 // This code can only handle circles, not ellipses. But khtml only
262 // uses it for circles.
263 ASSERT(rect.width() == rect.height());
264
265 if (paintingDisabled())
266 return;
267
268 CGContextRef context = platformContext();
269 CGContextBeginPath(context);
270 float r = (float)rect.width() / 2;
271 CGContextAddArc(context, rect.x() + r, rect.y() + r, r, 0.0f, 2.0f * piFloat, 0);
272 CGContextClosePath(context);
273
274 drawPath();
275 }
276
277
strokeArc(const IntRect & rect,int startAngle,int angleSpan)278 void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan)
279 {
280 if (paintingDisabled() || strokeStyle() == NoStroke || strokeThickness() <= 0.0f || !strokeColor().alpha())
281 return;
282
283 CGContextRef context = platformContext();
284 CGContextSaveGState(context);
285 CGContextBeginPath(context);
286 CGContextSetShouldAntialias(context, false);
287
288 int x = rect.x();
289 int y = rect.y();
290 float w = (float)rect.width();
291 float h = (float)rect.height();
292 float scaleFactor = h / w;
293 float reverseScaleFactor = w / h;
294
295 if (w != h)
296 scale(FloatSize(1, scaleFactor));
297
298 float hRadius = w / 2;
299 float vRadius = h / 2;
300 float fa = startAngle;
301 float falen = fa + angleSpan;
302 float start = -fa * piFloat / 180.0f;
303 float end = -falen * piFloat / 180.0f;
304 CGContextAddArc(context, x + hRadius, (y + vRadius) * reverseScaleFactor, hRadius, start, end, true);
305
306 if (w != h)
307 scale(FloatSize(1, reverseScaleFactor));
308
309
310 float width = strokeThickness();
311 int patWidth = 0;
312
313 switch (strokeStyle()) {
314 case DottedStroke:
315 patWidth = (int)(width / 2);
316 break;
317 case DashedStroke:
318 patWidth = 3 * (int)(width / 2);
319 break;
320 default:
321 break;
322 }
323
324 if (patWidth) {
325 // Example: 80 pixels with a width of 30 pixels.
326 // Remainder is 20. The maximum pixels of line we could paint
327 // will be 50 pixels.
328 int distance;
329 if (hRadius == vRadius)
330 distance = static_cast<int>((piFloat * hRadius) / 2.0f);
331 else // We are elliptical and will have to estimate the distance
332 distance = static_cast<int>((piFloat * sqrtf((hRadius * hRadius + vRadius * vRadius) / 2.0f)) / 2.0f);
333
334 int remainder = distance % patWidth;
335 int coverage = distance - remainder;
336 int numSegments = coverage / patWidth;
337
338 float patternOffset = 0.0f;
339 // Special case 1px dotted borders for speed.
340 if (patWidth == 1)
341 patternOffset = 1.0f;
342 else {
343 bool evenNumberOfSegments = numSegments % 2 == 0;
344 if (remainder)
345 evenNumberOfSegments = !evenNumberOfSegments;
346 if (evenNumberOfSegments) {
347 if (remainder) {
348 patternOffset += patWidth - remainder;
349 patternOffset += remainder / 2.0f;
350 } else
351 patternOffset = patWidth / 2.0f;
352 } else {
353 if (remainder)
354 patternOffset = (patWidth - remainder) / 2.0f;
355 }
356 }
357
358 const CGFloat dottedLine[2] = { patWidth, patWidth };
359 CGContextSetLineDash(context, patternOffset, dottedLine, 2);
360 }
361
362 CGContextStrokePath(context);
363
364 CGContextRestoreGState(context);
365 }
366
drawConvexPolygon(size_t npoints,const FloatPoint * points,bool antialiased)367 void GraphicsContext::drawConvexPolygon(size_t npoints, const FloatPoint* points, bool antialiased)
368 {
369 if (paintingDisabled() || !fillColor().alpha() && (strokeThickness() <= 0 || strokeStyle() == NoStroke))
370 return;
371
372 if (npoints <= 1)
373 return;
374
375 CGContextRef context = platformContext();
376
377 if (antialiased != shouldAntialias())
378 CGContextSetShouldAntialias(context, antialiased);
379
380 CGContextBeginPath(context);
381 CGContextMoveToPoint(context, points[0].x(), points[0].y());
382 for (size_t i = 1; i < npoints; i++)
383 CGContextAddLineToPoint(context, points[i].x(), points[i].y());
384 CGContextClosePath(context);
385
386 drawPath();
387
388 if (antialiased != shouldAntialias())
389 CGContextSetShouldAntialias(context, shouldAntialias());
390 }
391
applyStrokePattern()392 void GraphicsContext::applyStrokePattern()
393 {
394 CGContextRef cgContext = platformContext();
395
396 CGPatternRef platformPattern = m_common->state.strokePattern.get()->createPlatformPattern(getCTM());
397 if (!platformPattern)
398 return;
399
400 CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(0);
401 CGContextSetStrokeColorSpace(cgContext, patternSpace);
402 CGColorSpaceRelease(patternSpace);
403
404 const CGFloat patternAlpha = 1;
405 CGContextSetStrokePattern(cgContext, platformPattern, &patternAlpha);
406 CGPatternRelease(platformPattern);
407 }
408
applyFillPattern()409 void GraphicsContext::applyFillPattern()
410 {
411 CGContextRef cgContext = platformContext();
412
413 CGPatternRef platformPattern = m_common->state.fillPattern.get()->createPlatformPattern(getCTM());
414 if (!platformPattern)
415 return;
416
417 CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(0);
418 CGContextSetFillColorSpace(cgContext, patternSpace);
419 CGColorSpaceRelease(patternSpace);
420
421 const CGFloat patternAlpha = 1;
422 CGContextSetFillPattern(cgContext, platformPattern, &patternAlpha);
423 CGPatternRelease(platformPattern);
424 }
425
calculateDrawingMode(const GraphicsContextState & state,CGPathDrawingMode & mode)426 static inline bool calculateDrawingMode(const GraphicsContextState& state, CGPathDrawingMode& mode)
427 {
428 bool shouldFill = state.fillColorSpace == PatternColorSpace || state.fillColor.alpha();
429 bool shouldStroke = state.strokeColorSpace == PatternColorSpace || (state.strokeStyle != NoStroke && state.strokeColor.alpha());
430 bool useEOFill = state.fillRule == RULE_EVENODD;
431
432 if (shouldFill) {
433 if (shouldStroke) {
434 if (useEOFill)
435 mode = kCGPathEOFillStroke;
436 else
437 mode = kCGPathFillStroke;
438 } else { // fill, no stroke
439 if (useEOFill)
440 mode = kCGPathEOFill;
441 else
442 mode = kCGPathFill;
443 }
444 } else {
445 // Setting mode to kCGPathStroke even if shouldStroke is false. In that case, we return false and mode will not be used,
446 // but the compiler will not compain about an uninitialized variable.
447 mode = kCGPathStroke;
448 }
449
450 return shouldFill || shouldStroke;
451 }
452
drawPath()453 void GraphicsContext::drawPath()
454 {
455 if (paintingDisabled())
456 return;
457
458 CGContextRef context = platformContext();
459 const GraphicsContextState& state = m_common->state;
460
461 if (state.fillColorSpace == GradientColorSpace || state.strokeColorSpace == GradientColorSpace) {
462 // We don't have any optimized way to fill & stroke a path using gradients
463 fillPath();
464 strokePath();
465 return;
466 }
467
468 if (state.fillColorSpace == PatternColorSpace)
469 applyFillPattern();
470 if (state.strokeColorSpace == PatternColorSpace)
471 applyStrokePattern();
472
473 CGPathDrawingMode drawingMode;
474 if (calculateDrawingMode(state, drawingMode))
475 CGContextDrawPath(context, drawingMode);
476 }
477
fillPathWithFillRule(CGContextRef context,WindRule fillRule)478 static inline void fillPathWithFillRule(CGContextRef context, WindRule fillRule)
479 {
480 if (fillRule == RULE_EVENODD)
481 CGContextEOFillPath(context);
482 else
483 CGContextFillPath(context);
484 }
485
fillPath()486 void GraphicsContext::fillPath()
487 {
488 if (paintingDisabled())
489 return;
490
491 CGContextRef context = platformContext();
492 switch (m_common->state.fillColorSpace) {
493 case SolidColorSpace:
494 if (fillColor().alpha())
495 fillPathWithFillRule(context, fillRule());
496 break;
497 case PatternColorSpace:
498 applyFillPattern();
499 fillPathWithFillRule(context, fillRule());
500 break;
501 case GradientColorSpace:
502 CGContextSaveGState(context);
503 if (fillRule() == RULE_EVENODD)
504 CGContextEOClip(context);
505 else
506 CGContextClip(context);
507 CGContextDrawShading(context, m_common->state.fillGradient->platformGradient());
508 CGContextRestoreGState(context);
509 break;
510 }
511 }
512
strokePath()513 void GraphicsContext::strokePath()
514 {
515 if (paintingDisabled())
516 return;
517
518 CGContextRef context = platformContext();
519 switch (m_common->state.strokeColorSpace) {
520 case SolidColorSpace:
521 if (strokeColor().alpha())
522 CGContextStrokePath(context);
523 break;
524 case PatternColorSpace:
525 applyStrokePattern();
526 CGContextStrokePath(context);
527 break;
528 case GradientColorSpace:
529 CGContextSaveGState(context);
530 CGContextReplacePathWithStrokedPath(context);
531 CGContextClip(context);
532 CGContextDrawShading(context, m_common->state.strokeGradient->platformGradient());
533 CGContextRestoreGState(context);
534 break;
535 }
536 }
537
fillRect(const FloatRect & rect)538 void GraphicsContext::fillRect(const FloatRect& rect)
539 {
540 if (paintingDisabled())
541 return;
542 CGContextRef context = platformContext();
543 switch (m_common->state.fillColorSpace) {
544 case SolidColorSpace:
545 if (fillColor().alpha())
546 CGContextFillRect(context, rect);
547 break;
548 case PatternColorSpace:
549 applyFillPattern();
550 CGContextFillRect(context, rect);
551 break;
552 case GradientColorSpace:
553 CGContextSaveGState(context);
554 CGContextClipToRect(context, rect);
555 CGContextDrawShading(context, m_common->state.fillGradient->platformGradient());
556 CGContextRestoreGState(context);
557 break;
558 }
559 }
560
fillRect(const FloatRect & rect,const Color & color)561 void GraphicsContext::fillRect(const FloatRect& rect, const Color& color)
562 {
563 if (paintingDisabled())
564 return;
565 if (color.alpha()) {
566 CGContextRef context = platformContext();
567 Color oldFillColor = fillColor();
568 if (oldFillColor != color)
569 setCGFillColor(context, color);
570 CGContextFillRect(context, rect);
571 if (oldFillColor != color)
572 setCGFillColor(context, oldFillColor);
573 }
574 }
575
fillRoundedRect(const IntRect & rect,const IntSize & topLeft,const IntSize & topRight,const IntSize & bottomLeft,const IntSize & bottomRight,const Color & color)576 void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color)
577 {
578 if (paintingDisabled() || !color.alpha())
579 return;
580
581 CGContextRef context = platformContext();
582 Color oldFillColor = fillColor();
583 if (oldFillColor != color)
584 setCGFillColor(context, color);
585
586 addPath(Path::createRoundedRectangle(rect, topLeft, topRight, bottomLeft, bottomRight));
587 fillPath();
588
589 if (oldFillColor != color)
590 setCGFillColor(context, oldFillColor);
591 }
592
clip(const FloatRect & rect)593 void GraphicsContext::clip(const FloatRect& rect)
594 {
595 if (paintingDisabled())
596 return;
597 CGContextClipToRect(platformContext(), rect);
598 m_data->clip(rect);
599 }
600
clipOut(const IntRect & rect)601 void GraphicsContext::clipOut(const IntRect& rect)
602 {
603 if (paintingDisabled())
604 return;
605
606 CGRect rects[2] = { CGContextGetClipBoundingBox(platformContext()), rect };
607 CGContextBeginPath(platformContext());
608 CGContextAddRects(platformContext(), rects, 2);
609 CGContextEOClip(platformContext());
610 }
611
clipOutEllipseInRect(const IntRect & rect)612 void GraphicsContext::clipOutEllipseInRect(const IntRect& rect)
613 {
614 if (paintingDisabled())
615 return;
616
617 CGContextBeginPath(platformContext());
618 CGContextAddRect(platformContext(), CGContextGetClipBoundingBox(platformContext()));
619 CGContextAddEllipseInRect(platformContext(), rect);
620 CGContextEOClip(platformContext());
621 }
622
clipPath(WindRule clipRule)623 void GraphicsContext::clipPath(WindRule clipRule)
624 {
625 if (paintingDisabled())
626 return;
627
628 CGContextRef context = platformContext();
629
630 if (!CGContextIsPathEmpty(context)) {
631 if (clipRule == RULE_EVENODD)
632 CGContextEOClip(context);
633 else
634 CGContextClip(context);
635 }
636 }
637
addInnerRoundedRectClip(const IntRect & rect,int thickness)638 void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness)
639 {
640 if (paintingDisabled())
641 return;
642
643 clip(rect);
644 CGContextRef context = platformContext();
645
646 // Add outer ellipse
647 CGContextAddEllipseInRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()));
648 // Add inner ellipse.
649 CGContextAddEllipseInRect(context, CGRectMake(rect.x() + thickness, rect.y() + thickness,
650 rect.width() - (thickness * 2), rect.height() - (thickness * 2)));
651
652 CGContextEOClip(context);
653 }
654
clipToImageBuffer(const FloatRect & rect,const ImageBuffer * imageBuffer)655 void GraphicsContext::clipToImageBuffer(const FloatRect& rect, const ImageBuffer* imageBuffer)
656 {
657 if (paintingDisabled())
658 return;
659
660 CGContextTranslateCTM(platformContext(), rect.x(), rect.y() + rect.height());
661 CGContextScaleCTM(platformContext(), 1, -1);
662 CGContextClipToMask(platformContext(), FloatRect(FloatPoint(), rect.size()), imageBuffer->image()->getCGImageRef());
663 CGContextScaleCTM(platformContext(), 1, -1);
664 CGContextTranslateCTM(platformContext(), -rect.x(), -rect.y() - rect.height());
665 }
666
beginTransparencyLayer(float opacity)667 void GraphicsContext::beginTransparencyLayer(float opacity)
668 {
669 if (paintingDisabled())
670 return;
671 CGContextRef context = platformContext();
672 CGContextSaveGState(context);
673 CGContextSetAlpha(context, opacity);
674 CGContextBeginTransparencyLayer(context, 0);
675 m_data->beginTransparencyLayer();
676 m_data->m_userToDeviceTransformKnownToBeIdentity = false;
677 }
678
endTransparencyLayer()679 void GraphicsContext::endTransparencyLayer()
680 {
681 if (paintingDisabled())
682 return;
683 CGContextRef context = platformContext();
684 CGContextEndTransparencyLayer(context);
685 CGContextRestoreGState(context);
686 m_data->endTransparencyLayer();
687 m_data->m_userToDeviceTransformKnownToBeIdentity = false;
688 }
689
setPlatformShadow(const IntSize & size,int blur,const Color & color)690 void GraphicsContext::setPlatformShadow(const IntSize& size, int blur, const Color& color)
691 {
692 if (paintingDisabled())
693 return;
694 CGFloat width = size.width();
695 CGFloat height = size.height();
696 CGFloat blurRadius = blur;
697 CGContextRef context = platformContext();
698
699 if (!m_common->state.shadowsIgnoreTransforms) {
700 CGAffineTransform transform = CGContextGetCTM(context);
701
702 CGFloat A = transform.a * transform.a + transform.b * transform.b;
703 CGFloat B = transform.a * transform.c + transform.b * transform.d;
704 CGFloat C = B;
705 CGFloat D = transform.c * transform.c + transform.d * transform.d;
706
707 CGFloat smallEigenvalue = narrowPrecisionToCGFloat(sqrt(0.5 * ((A + D) - sqrt(4 * B * C + (A - D) * (A - D)))));
708
709 // Extreme "blur" values can make text drawing crash or take crazy long times, so clamp
710 blurRadius = min(blur * smallEigenvalue, narrowPrecisionToCGFloat(1000.0));
711
712 CGSize sizeInDeviceSpace = CGSizeApplyAffineTransform(size, transform);
713
714 width = sizeInDeviceSpace.width;
715 height = sizeInDeviceSpace.height;
716
717 }
718
719 // Work around <rdar://problem/5539388> by ensuring that the offsets will get truncated
720 // to the desired integer.
721 static const CGFloat extraShadowOffset = narrowPrecisionToCGFloat(1.0 / 128);
722 if (width > 0)
723 width += extraShadowOffset;
724 else if (width < 0)
725 width -= extraShadowOffset;
726
727 if (height > 0)
728 height += extraShadowOffset;
729 else if (height < 0)
730 height -= extraShadowOffset;
731
732 // Check for an invalid color, as this means that the color was not set for the shadow
733 // and we should therefore just use the default shadow color.
734 if (!color.isValid())
735 CGContextSetShadow(context, CGSizeMake(width, height), blurRadius);
736 else {
737 CGColorRef colorCG = cgColor(color);
738 CGContextSetShadowWithColor(context,
739 CGSizeMake(width, height),
740 blurRadius,
741 colorCG);
742 CGColorRelease(colorCG);
743 }
744 }
745
clearPlatformShadow()746 void GraphicsContext::clearPlatformShadow()
747 {
748 if (paintingDisabled())
749 return;
750 CGContextSetShadowWithColor(platformContext(), CGSizeZero, 0, 0);
751 }
752
setMiterLimit(float limit)753 void GraphicsContext::setMiterLimit(float limit)
754 {
755 if (paintingDisabled())
756 return;
757 CGContextSetMiterLimit(platformContext(), limit);
758 }
759
setAlpha(float alpha)760 void GraphicsContext::setAlpha(float alpha)
761 {
762 if (paintingDisabled())
763 return;
764 CGContextSetAlpha(platformContext(), alpha);
765 }
766
clearRect(const FloatRect & r)767 void GraphicsContext::clearRect(const FloatRect& r)
768 {
769 if (paintingDisabled())
770 return;
771 CGContextClearRect(platformContext(), r);
772 }
773
strokeRect(const FloatRect & r,float lineWidth)774 void GraphicsContext::strokeRect(const FloatRect& r, float lineWidth)
775 {
776 if (paintingDisabled())
777 return;
778
779 CGContextRef context = platformContext();
780 switch (m_common->state.strokeColorSpace) {
781 case SolidColorSpace:
782 if (strokeColor().alpha())
783 CGContextStrokeRectWithWidth(context, r, lineWidth);
784 break;
785 case PatternColorSpace:
786 applyStrokePattern();
787 CGContextStrokeRectWithWidth(context, r, lineWidth);
788 break;
789 case GradientColorSpace:
790 CGContextSaveGState(context);
791 setStrokeThickness(lineWidth);
792 CGContextAddRect(context, r);
793 CGContextReplacePathWithStrokedPath(context);
794 CGContextClip(context);
795 CGContextDrawShading(context, m_common->state.strokeGradient->platformGradient());
796 CGContextRestoreGState(context);
797 break;
798 }
799 }
800
setLineCap(LineCap cap)801 void GraphicsContext::setLineCap(LineCap cap)
802 {
803 if (paintingDisabled())
804 return;
805 switch (cap) {
806 case ButtCap:
807 CGContextSetLineCap(platformContext(), kCGLineCapButt);
808 break;
809 case RoundCap:
810 CGContextSetLineCap(platformContext(), kCGLineCapRound);
811 break;
812 case SquareCap:
813 CGContextSetLineCap(platformContext(), kCGLineCapSquare);
814 break;
815 }
816 }
817
setLineDash(const DashArray & dashes,float dashOffset)818 void GraphicsContext::setLineDash(const DashArray& dashes, float dashOffset)
819 {
820 CGContextSetLineDash(platformContext(), dashOffset, dashes.data(), dashes.size());
821 }
822
setLineJoin(LineJoin join)823 void GraphicsContext::setLineJoin(LineJoin join)
824 {
825 if (paintingDisabled())
826 return;
827 switch (join) {
828 case MiterJoin:
829 CGContextSetLineJoin(platformContext(), kCGLineJoinMiter);
830 break;
831 case RoundJoin:
832 CGContextSetLineJoin(platformContext(), kCGLineJoinRound);
833 break;
834 case BevelJoin:
835 CGContextSetLineJoin(platformContext(), kCGLineJoinBevel);
836 break;
837 }
838 }
839
beginPath()840 void GraphicsContext::beginPath()
841 {
842 CGContextBeginPath(platformContext());
843 }
844
addPath(const Path & path)845 void GraphicsContext::addPath(const Path& path)
846 {
847 CGContextAddPath(platformContext(), path.platformPath());
848 }
849
clip(const Path & path)850 void GraphicsContext::clip(const Path& path)
851 {
852 if (paintingDisabled())
853 return;
854 CGContextRef context = platformContext();
855 CGContextBeginPath(context);
856 CGContextAddPath(context, path.platformPath());
857 CGContextClip(context);
858 m_data->clip(path);
859 }
860
clipOut(const Path & path)861 void GraphicsContext::clipOut(const Path& path)
862 {
863 if (paintingDisabled())
864 return;
865
866 CGContextBeginPath(platformContext());
867 CGContextAddRect(platformContext(), CGContextGetClipBoundingBox(platformContext()));
868 CGContextAddPath(platformContext(), path.platformPath());
869 CGContextEOClip(platformContext());
870 }
871
scale(const FloatSize & size)872 void GraphicsContext::scale(const FloatSize& size)
873 {
874 if (paintingDisabled())
875 return;
876 CGContextScaleCTM(platformContext(), size.width(), size.height());
877 m_data->scale(size);
878 m_data->m_userToDeviceTransformKnownToBeIdentity = false;
879 }
880
rotate(float angle)881 void GraphicsContext::rotate(float angle)
882 {
883 if (paintingDisabled())
884 return;
885 CGContextRotateCTM(platformContext(), angle);
886 m_data->rotate(angle);
887 m_data->m_userToDeviceTransformKnownToBeIdentity = false;
888 }
889
translate(float x,float y)890 void GraphicsContext::translate(float x, float y)
891 {
892 if (paintingDisabled())
893 return;
894 CGContextTranslateCTM(platformContext(), x, y);
895 m_data->translate(x, y);
896 m_data->m_userToDeviceTransformKnownToBeIdentity = false;
897 }
898
concatCTM(const TransformationMatrix & transform)899 void GraphicsContext::concatCTM(const TransformationMatrix& transform)
900 {
901 if (paintingDisabled())
902 return;
903 CGContextConcatCTM(platformContext(), transform);
904 m_data->concatCTM(transform);
905 m_data->m_userToDeviceTransformKnownToBeIdentity = false;
906 }
907
getCTM() const908 TransformationMatrix GraphicsContext::getCTM() const
909 {
910 return CGContextGetCTM(platformContext());
911 }
912
roundToDevicePixels(const FloatRect & rect)913 FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& rect)
914 {
915 // It is not enough just to round to pixels in device space. The rotation part of the
916 // affine transform matrix to device space can mess with this conversion if we have a
917 // rotating image like the hands of the world clock widget. We just need the scale, so
918 // we get the affine transform matrix and extract the scale.
919
920 if (m_data->m_userToDeviceTransformKnownToBeIdentity)
921 return rect;
922
923 CGAffineTransform deviceMatrix = CGContextGetUserSpaceToDeviceSpaceTransform(platformContext());
924 if (CGAffineTransformIsIdentity(deviceMatrix)) {
925 m_data->m_userToDeviceTransformKnownToBeIdentity = true;
926 return rect;
927 }
928
929 float deviceScaleX = sqrtf(deviceMatrix.a * deviceMatrix.a + deviceMatrix.b * deviceMatrix.b);
930 float deviceScaleY = sqrtf(deviceMatrix.c * deviceMatrix.c + deviceMatrix.d * deviceMatrix.d);
931
932 CGPoint deviceOrigin = CGPointMake(rect.x() * deviceScaleX, rect.y() * deviceScaleY);
933 CGPoint deviceLowerRight = CGPointMake((rect.x() + rect.width()) * deviceScaleX,
934 (rect.y() + rect.height()) * deviceScaleY);
935
936 deviceOrigin.x = roundf(deviceOrigin.x);
937 deviceOrigin.y = roundf(deviceOrigin.y);
938 deviceLowerRight.x = roundf(deviceLowerRight.x);
939 deviceLowerRight.y = roundf(deviceLowerRight.y);
940
941 // Don't let the height or width round to 0 unless either was originally 0
942 if (deviceOrigin.y == deviceLowerRight.y && rect.height() != 0)
943 deviceLowerRight.y += 1;
944 if (deviceOrigin.x == deviceLowerRight.x && rect.width() != 0)
945 deviceLowerRight.x += 1;
946
947 FloatPoint roundedOrigin = FloatPoint(deviceOrigin.x / deviceScaleX, deviceOrigin.y / deviceScaleY);
948 FloatPoint roundedLowerRight = FloatPoint(deviceLowerRight.x / deviceScaleX, deviceLowerRight.y / deviceScaleY);
949 return FloatRect(roundedOrigin, roundedLowerRight - roundedOrigin);
950 }
951
drawLineForText(const IntPoint & point,int width,bool printing)952 void GraphicsContext::drawLineForText(const IntPoint& point, int width, bool printing)
953 {
954 if (paintingDisabled())
955 return;
956
957 if (width <= 0)
958 return;
959
960 float x = point.x();
961 float y = point.y();
962 float lineLength = width;
963
964 // Use a minimum thickness of 0.5 in user space.
965 // See http://bugs.webkit.org/show_bug.cgi?id=4255 for details of why 0.5 is the right minimum thickness to use.
966 float thickness = max(strokeThickness(), 0.5f);
967
968 bool restoreAntialiasMode = false;
969
970 if (!printing) {
971 // On screen, use a minimum thickness of 1.0 in user space (later rounded to an integral number in device space).
972 float adjustedThickness = max(thickness, 1.0f);
973
974 // FIXME: This should be done a better way.
975 // We try to round all parameters to integer boundaries in device space. If rounding pixels in device space
976 // makes our thickness more than double, then there must be a shrinking-scale factor and rounding to pixels
977 // in device space will make the underlines too thick.
978 CGRect lineRect = roundToDevicePixels(FloatRect(x, y, lineLength, adjustedThickness));
979 if (lineRect.size.height < thickness * 2.0) {
980 x = lineRect.origin.x;
981 y = lineRect.origin.y;
982 lineLength = lineRect.size.width;
983 thickness = lineRect.size.height;
984 if (shouldAntialias()) {
985 CGContextSetShouldAntialias(platformContext(), false);
986 restoreAntialiasMode = true;
987 }
988 }
989 }
990
991 if (fillColor() != strokeColor())
992 setCGFillColor(platformContext(), strokeColor());
993 CGContextFillRect(platformContext(), CGRectMake(x, y, lineLength, thickness));
994 if (fillColor() != strokeColor())
995 setCGFillColor(platformContext(), fillColor());
996
997 if (restoreAntialiasMode)
998 CGContextSetShouldAntialias(platformContext(), true);
999 }
1000
setURLForRect(const KURL & link,const IntRect & destRect)1001 void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
1002 {
1003 if (paintingDisabled())
1004 return;
1005
1006 CFURLRef urlRef = link.createCFURL();
1007 if (urlRef) {
1008 CGContextRef context = platformContext();
1009
1010 // Get the bounding box to handle clipping.
1011 CGRect box = CGContextGetClipBoundingBox(context);
1012
1013 IntRect intBox((int)box.origin.x, (int)box.origin.y, (int)box.size.width, (int)box.size.height);
1014 IntRect rect = destRect;
1015 rect.intersect(intBox);
1016
1017 CGPDFContextSetURLForRect(context, urlRef,
1018 CGRectApplyAffineTransform(rect, CGContextGetCTM(context)));
1019
1020 CFRelease(urlRef);
1021 }
1022 }
1023
setImageInterpolationQuality(InterpolationQuality mode)1024 void GraphicsContext::setImageInterpolationQuality(InterpolationQuality mode)
1025 {
1026 if (paintingDisabled())
1027 return;
1028
1029 CGInterpolationQuality quality = kCGInterpolationDefault;
1030 switch (mode) {
1031 case InterpolationDefault:
1032 quality = kCGInterpolationDefault;
1033 break;
1034 case InterpolationNone:
1035 quality = kCGInterpolationNone;
1036 break;
1037 case InterpolationLow:
1038 quality = kCGInterpolationLow;
1039 break;
1040
1041 // Fall through to InterpolationHigh if kCGInterpolationMedium is not available
1042 case InterpolationMedium:
1043 #if HAVE(CG_INTERPOLATION_MEDIUM)
1044 quality = kCGInterpolationMedium;
1045 break;
1046 #endif
1047 case InterpolationHigh:
1048 quality = kCGInterpolationHigh;
1049 break;
1050 }
1051 CGContextSetInterpolationQuality(platformContext(), quality);
1052 }
1053
imageInterpolationQuality() const1054 InterpolationQuality GraphicsContext::imageInterpolationQuality() const
1055 {
1056 if (paintingDisabled())
1057 return InterpolationDefault;
1058
1059 CGInterpolationQuality quality = CGContextGetInterpolationQuality(platformContext());
1060 switch (quality) {
1061 case kCGInterpolationDefault:
1062 return InterpolationDefault;
1063 case kCGInterpolationNone:
1064 return InterpolationNone;
1065 case kCGInterpolationLow:
1066 return InterpolationLow;
1067 #if HAVE(CG_INTERPOLATION_MEDIUM)
1068 case kCGInterpolationMedium:
1069 return InterpolationMedium;
1070 #endif
1071 case kCGInterpolationHigh:
1072 return InterpolationHigh;
1073 }
1074 return InterpolationDefault;
1075 }
1076
setPlatformTextDrawingMode(int mode)1077 void GraphicsContext::setPlatformTextDrawingMode(int mode)
1078 {
1079 if (paintingDisabled())
1080 return;
1081
1082 // Wow, wish CG had used bits here.
1083 CGContextRef context = platformContext();
1084 switch (mode) {
1085 case cTextInvisible: // Invisible
1086 CGContextSetTextDrawingMode(context, kCGTextInvisible);
1087 break;
1088 case cTextFill: // Fill
1089 CGContextSetTextDrawingMode(context, kCGTextFill);
1090 break;
1091 case cTextStroke: // Stroke
1092 CGContextSetTextDrawingMode(context, kCGTextStroke);
1093 break;
1094 case 3: // Fill | Stroke
1095 CGContextSetTextDrawingMode(context, kCGTextFillStroke);
1096 break;
1097 case cTextClip: // Clip
1098 CGContextSetTextDrawingMode(context, kCGTextClip);
1099 break;
1100 case 5: // Fill | Clip
1101 CGContextSetTextDrawingMode(context, kCGTextFillClip);
1102 break;
1103 case 6: // Stroke | Clip
1104 CGContextSetTextDrawingMode(context, kCGTextStrokeClip);
1105 break;
1106 case 7: // Fill | Stroke | Clip
1107 CGContextSetTextDrawingMode(context, kCGTextFillStrokeClip);
1108 break;
1109 default:
1110 break;
1111 }
1112 }
1113
setPlatformStrokeColor(const Color & color)1114 void GraphicsContext::setPlatformStrokeColor(const Color& color)
1115 {
1116 if (paintingDisabled())
1117 return;
1118 setCGStrokeColor(platformContext(), color);
1119 }
1120
setPlatformStrokeThickness(float thickness)1121 void GraphicsContext::setPlatformStrokeThickness(float thickness)
1122 {
1123 if (paintingDisabled())
1124 return;
1125 CGContextSetLineWidth(platformContext(), thickness);
1126 }
1127
setPlatformFillColor(const Color & color)1128 void GraphicsContext::setPlatformFillColor(const Color& color)
1129 {
1130 if (paintingDisabled())
1131 return;
1132 setCGFillColor(platformContext(), color);
1133 }
1134
setPlatformShouldAntialias(bool enable)1135 void GraphicsContext::setPlatformShouldAntialias(bool enable)
1136 {
1137 if (paintingDisabled())
1138 return;
1139 CGContextSetShouldAntialias(platformContext(), enable);
1140 }
1141
1142 #ifndef BUILDING_ON_TIGER // Tiger's setCompositeOperation() is defined in GraphicsContextMac.mm.
setCompositeOperation(CompositeOperator mode)1143 void GraphicsContext::setCompositeOperation(CompositeOperator mode)
1144 {
1145 if (paintingDisabled())
1146 return;
1147
1148 CGBlendMode target = kCGBlendModeNormal;
1149 switch (mode) {
1150 case CompositeClear:
1151 target = kCGBlendModeClear;
1152 break;
1153 case CompositeCopy:
1154 target = kCGBlendModeCopy;
1155 break;
1156 case CompositeSourceOver:
1157 //kCGBlendModeNormal
1158 break;
1159 case CompositeSourceIn:
1160 target = kCGBlendModeSourceIn;
1161 break;
1162 case CompositeSourceOut:
1163 target = kCGBlendModeSourceOut;
1164 break;
1165 case CompositeSourceAtop:
1166 target = kCGBlendModeSourceAtop;
1167 break;
1168 case CompositeDestinationOver:
1169 target = kCGBlendModeDestinationOver;
1170 break;
1171 case CompositeDestinationIn:
1172 target = kCGBlendModeDestinationIn;
1173 break;
1174 case CompositeDestinationOut:
1175 target = kCGBlendModeDestinationOut;
1176 break;
1177 case CompositeDestinationAtop:
1178 target = kCGBlendModeDestinationAtop;
1179 break;
1180 case CompositeXOR:
1181 target = kCGBlendModeXOR;
1182 break;
1183 case CompositePlusDarker:
1184 target = kCGBlendModePlusDarker;
1185 break;
1186 case CompositeHighlight:
1187 // currently unsupported
1188 break;
1189 case CompositePlusLighter:
1190 target = kCGBlendModePlusLighter;
1191 break;
1192 }
1193 CGContextSetBlendMode(platformContext(), target);
1194 }
1195 #endif
1196
1197 }
1198
1199