2 * Copyright (C) 2006 Dirk Mueller <mueller@kde.org>
3 * Copyright (C) 2006 Zack Rusin <zack@kde.org>
4 * Copyright (C) 2006 George Staikos <staikos@kde.org>
5 * Copyright (C) 2006 Simon Hausmann <hausmann@kde.org>
6 * Copyright (C) 2006 Allan Sandfeld Jensen <sandfeld@kde.org>
7 * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
21 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
24 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
28 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #include "AffineTransform.h"
38 #include "GraphicsContext.h"
45 #include <QPainterPath>
46 #include <QPaintDevice>
49 #define M_PI 3.14159265358979323846
52 #define notImplemented() do { fprintf(stderr, "FIXME: UNIMPLEMENTED: %s:%d\n", __FILE__, __LINE__); } while(0)
56 static inline QPainter::CompositionMode toQtCompositionMode(CompositeOperator op)
60 return QPainter::CompositionMode_Clear;
62 return QPainter::CompositionMode_Source;
63 case CompositeSourceOver:
64 return QPainter::CompositionMode_SourceOver;
65 case CompositeSourceIn:
66 return QPainter::CompositionMode_SourceIn;
67 case CompositeSourceOut:
68 return QPainter::CompositionMode_SourceOut;
69 case CompositeSourceAtop:
70 return QPainter::CompositionMode_SourceAtop;
71 case CompositeDestinationOver:
72 return QPainter::CompositionMode_DestinationOver;
73 case CompositeDestinationIn:
74 return QPainter::CompositionMode_DestinationIn;
75 case CompositeDestinationOut:
76 return QPainter::CompositionMode_DestinationOut;
77 case CompositeDestinationAtop:
78 return QPainter::CompositionMode_DestinationAtop;
80 return QPainter::CompositionMode_Xor;
81 case CompositePlusDarker:
82 return QPainter::CompositionMode_SourceOver;
83 case CompositeHighlight:
84 return QPainter::CompositionMode_SourceOver;
85 case CompositePlusLighter:
86 return QPainter::CompositionMode_SourceOver;
89 return QPainter::CompositionMode_SourceOver;
92 static inline Qt::PenCapStyle toQtLineCap(LineCap lc)
100 return Qt::SquareCap;
106 static inline Qt::PenJoinStyle toQtLineJoin(LineJoin lj)
110 return Qt::SvgMiterJoin;
112 return Qt::RoundJoin;
114 return Qt::BevelJoin;
117 return Qt::MiterJoin;
120 static Qt::PenStyle toQPenStyle(Pen::PenStyle style)
127 return Qt::SolidLine;
136 qWarning("couldn't recognize the pen style");
140 static inline QPen penToQPen(const Pen& pen)
142 return QPen(QColor(pen.color()), pen.width(), toQPenStyle(pen.style()));
145 struct TransparencyLayer
147 TransparencyLayer(const QPainter& p, int width, int height)
149 pixmap = QPixmap(width, height);
151 painter = new QPainter(&pixmap);
152 painter->setPen(p.pen());
153 painter->setBrush(p.brush());
154 painter->setMatrix(p.matrix());
155 painter->setOpacity(p.opacity());
156 painter->setFont(p.font());
157 painter->setCompositionMode(p.compositionMode());
158 painter->setClipPath(p.clipPath());
185 bool isNull() { return !x && !y && !blur; }
194 class GraphicsContextPlatformPrivate
197 GraphicsContextPlatformPrivate(QPainter* painter);
198 ~GraphicsContextPlatformPrivate();
202 if (layers.isEmpty()) {
208 return *layers.top().painter;
211 QPaintDevice* device;
213 QStack<TransparencyLayer> layers;
216 IntRect focusRingClip;
219 // Only used by SVG for now.
220 QPainterPath currentPath;
227 GraphicsContextPlatformPrivate::GraphicsContextPlatformPrivate(QPainter* p)
228 : device(p->device())
233 // FIXME: Maybe only enable in SVG mode?
234 painter->setRenderHint(QPainter::Antialiasing);
237 GraphicsContextPlatformPrivate::~GraphicsContextPlatformPrivate()
241 GraphicsContext::GraphicsContext(PlatformGraphicsContext* context)
242 : m_common(createGraphicsContextPrivate())
243 , m_data(new GraphicsContextPlatformPrivate(context))
245 setPaintingDisabled(!context);
248 GraphicsContext::~GraphicsContext()
250 while(!m_data->layers.isEmpty())
251 endTransparencyLayer();
253 destroyGraphicsContextPrivate(m_common);
257 PlatformGraphicsContext* GraphicsContext::platformContext() const
262 void GraphicsContext::savePlatformState()
267 void GraphicsContext::restorePlatformState()
269 m_data->p().restore();
272 /* FIXME: DISABLED WHILE MERGING BACK FROM UNITY
273 void GraphicsContext::drawTextShadow(const TextRun& run, const IntPoint& point, const TextStyle& style)
275 if (paintingDisabled())
278 if (m_data->shadow.isNull())
281 TextShadow* shadow = &m_data->shadow;
283 if (shadow->blur <= 0) {
285 setPen(shadow->color);
286 font().drawText(this, run, style, IntPoint(point.x() + shadow->x, point.y() + shadow->y));
289 const int thickness = shadow->blur;
290 // FIXME: OPTIMIZE: limit the area to only the actually painted area + 2*thickness
291 const int w = m_data->p().device()->width();
292 const int h = m_data->p().device()->height();
293 const QRgb color = qRgb(255, 255, 255);
294 const QRgb bgColor = qRgb(0, 0, 0);
295 QImage image(QSize(w, h), QImage::Format_ARGB32);
302 m_data->redirect = &p;
303 font().drawText(this, run, style, IntPoint(point.x() + shadow->x, point.y() + shadow->y));
304 m_data->redirect = 0;
308 int md = thickness * thickness; // max-dist^2
310 // blur map/precalculated shadow-decay
311 float* bmap = (float*) alloca(sizeof(float) * (md + 1));
312 for (int n = 0; n <= md; n++) {
314 f = n / (float) (md + 1);
319 float factor = 0.0; // maximal potential opacity-sum
320 for (int n = -thickness; n <= thickness; n++) {
321 for (int m = -thickness; m <= thickness; m++) {
322 int d = n * n + m * m;
329 float* amap = (float*) alloca(sizeof(float) * (h * w));
330 memset(amap, 0, h * w * (sizeof(float)));
332 for (int j = thickness; j<h-thickness; j++) {
333 for (int i = thickness; i<w-thickness; i++) {
334 QRgb col = image.pixel(i,j);
338 float g = qAlpha(col);
341 for (int n = -thickness; n <= thickness; n++) {
342 for (int m = -thickness; m <= thickness; m++) {
343 int d = n * n + m * m;
348 amap[(i + m) + (j + n) * w] += (g * f);
354 QImage res(QSize(w,h),QImage::Format_ARGB32);
355 int r = shadow->color.red();
356 int g = shadow->color.green();
357 int b = shadow->color.blue();
358 int a1 = shadow->color.alpha();
360 // arbitratry factor adjustment to make shadows more solid.
361 factor = 1.333 / factor;
363 for (int j = 0; j < h; j++) {
364 for (int i = 0; i < w; i++) {
365 int a = (int) (amap[i + j * w] * factor * a1);
369 res.setPixel(i,j, qRgba(r, g, b, a));
373 m_data->p().drawImage(0, 0, res, 0, 0, -1, -1, Qt::DiffuseAlphaDither | Qt::ColorOnly | Qt::PreferDither);
378 // Draws a filled rectangle with a stroked border.
379 void GraphicsContext::drawRect(const IntRect& rect)
381 if (paintingDisabled())
384 m_data->p().drawRect(rect);
387 // FIXME: Now that this is refactored, it should be shared by all contexts.
388 static void adjustLineToPixelBounderies(FloatPoint& p1, FloatPoint& p2, float strokeWidth,
389 const Pen::PenStyle& penStyle)
391 // For odd widths, we add in 0.5 to the appropriate x/y so that the float arithmetic
392 // works out. For example, with a border width of 3, KHTML will pass us (y1+y2)/2, e.g.,
393 // (50+53)/2 = 103/2 = 51 when we want 51.5. It is always true that an even width gave
394 // us a perfect position, but an odd width gave us a position that is off by exactly 0.5.
395 if (penStyle == Pen::DotLine || penStyle == Pen::DashLine) {
396 if (p1.x() == p2.x()) {
397 p1.setY(p1.y() + strokeWidth);
398 p2.setY(p2.y() - strokeWidth);
400 p1.setX(p1.x() + strokeWidth);
401 p2.setX(p2.x() - strokeWidth);
405 if (((int) strokeWidth) % 2) {
406 if (p1.x() == p2.x()) {
407 // We're a vertical line. Adjust our x.
408 p1.setX(p1.x() + 0.5);
409 p2.setX(p2.x() + 0.5);
411 // We're a horizontal line. Adjust our y.
412 p1.setY(p1.y() + 0.5);
413 p2.setY(p2.y() + 0.5);
418 // This is only used to draw borders.
419 void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
421 if (paintingDisabled())
424 FloatPoint p1 = point1;
425 FloatPoint p2 = point2;
427 adjustLineToPixelBounderies(p1, p2, pen().width(), pen().style());
428 m_data->p().drawLine(p1, p2);
431 // This method is only used to draw the little circles used in lists.
432 void GraphicsContext::drawEllipse(const IntRect& rect)
434 if (paintingDisabled())
437 m_data->p().drawEllipse(rect);
440 void GraphicsContext::drawArc(const IntRect& rect, float thickness,
441 int startAngle, int angleSpan)
443 if (paintingDisabled())
446 const QPen oldPen = m_data->p().pen();
448 nPen.setWidthF(thickness);
449 m_data->p().setPen(nPen);
450 m_data->p().drawArc(rect, startAngle, angleSpan);
451 m_data->p().setPen(oldPen);
454 void GraphicsContext::drawConvexPolygon(size_t npoints, const FloatPoint* points, bool shouldAntialias)
456 if (paintingDisabled())
462 QPolygonF polygon(npoints);
464 for (size_t i = 0; i < npoints; i++)
465 polygon[i] = points[i];
468 m_data->p().setRenderHint(QPainter::Antialiasing, shouldAntialias);
469 m_data->p().drawConvexPolygon(polygon);
470 m_data->p().restore();
473 void GraphicsContext::fillRect(const IntRect& rect, const Color& c)
475 if (paintingDisabled())
478 m_data->p().fillRect(rect, QColor(c));
481 void GraphicsContext::fillRect(const FloatRect& rect, const Color& c)
483 if (paintingDisabled())
486 m_data->p().fillRect(rect, QColor(c));
489 void GraphicsContext::beginPath()
491 m_data->currentPath = QPainterPath();
494 void GraphicsContext::addPath(const Path& path)
496 m_data->currentPath = *(path.platformPath());
499 void GraphicsContext::setFillRule(WindRule rule)
501 m_data->currentPath.setFillRule(rule == RULE_EVENODD ? Qt::OddEvenFill : Qt::WindingFill);
504 PlatformPath* GraphicsContext::currentPath()
506 return &m_data->currentPath;
509 void GraphicsContext::clip(const IntRect& rect)
511 if (paintingDisabled())
515 path.addRect(QRectF(rect));
516 m_data->p().setClipPath(path, Qt::UniteClip);
519 void GraphicsContext::drawFocusRing(const Color& color)
521 if (paintingDisabled())
527 void GraphicsContext::setFocusRingClip(const IntRect& rect)
529 if (paintingDisabled())
532 m_data->focusRingClip = rect;
535 void GraphicsContext::clearFocusRingClip()
537 if (paintingDisabled())
540 m_data->focusRingClip = IntRect();
543 void GraphicsContext::drawLineForText(const IntPoint& point, int yOffset,
544 int width, bool printing)
546 if (paintingDisabled())
549 IntPoint origin = point + IntSize(0, yOffset + 1);
550 IntPoint endPoint = origin + IntSize(width, 0);
551 drawLine(origin, endPoint);
554 void GraphicsContext::drawLineForMisspellingOrBadGrammar(const IntPoint&,
555 int width, bool grammar)
557 if (paintingDisabled())
563 FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& frect)
566 rect = m_data->p().deviceMatrix().mapRect(rect);
568 QRect result = rect.toRect(); //round it
569 return FloatRect(QRectF(result));
572 void GraphicsContext::setShadow(const IntSize& pos, int blur, const Color &color)
574 if (paintingDisabled())
577 m_data->shadow.x = pos.width();
578 m_data->shadow.y = pos.height();
579 m_data->shadow.blur = blur;
580 m_data->shadow.color = color;
583 void GraphicsContext::clearShadow()
585 if (paintingDisabled())
588 m_data->shadow = TextShadow();
591 void GraphicsContext::beginTransparencyLayer(float opacity)
593 if (paintingDisabled())
596 TransparencyLayer layer(m_data->p(),
597 m_data->device->width(),
598 m_data->device->height());
600 layer.opacity = opacity;
601 m_data->layers.push(layer);
604 void GraphicsContext::endTransparencyLayer()
606 if (paintingDisabled())
609 TransparencyLayer layer = m_data->layers.pop();
610 layer.painter->end();
613 m_data->p().setOpacity(layer.opacity);
614 m_data->p().drawPixmap(0, 0, layer.pixmap);
615 m_data->p().restore();
621 void GraphicsContext::clearRect(const FloatRect& rect)
623 if (paintingDisabled())
626 m_data->p().eraseRect(rect);
629 void GraphicsContext::strokeRect(const FloatRect& rect, float width)
631 if (paintingDisabled())
636 QPen nPen = m_data->p().pen();
637 nPen.setWidthF(width);
638 m_data->p().strokePath(path, nPen);
641 void GraphicsContext::setLineWidth(float width)
643 if (paintingDisabled())
646 QPen nPen = m_data->p().pen();
647 nPen.setWidthF(width);
648 m_data->p().setPen(nPen);
651 void GraphicsContext::setLineCap(LineCap lc)
653 if (paintingDisabled())
656 QPen nPen = m_data->p().pen();
657 nPen.setCapStyle(toQtLineCap(lc));
658 m_data->p().setPen(nPen);
661 void GraphicsContext::setLineJoin(LineJoin lj)
663 if (paintingDisabled())
666 QPen nPen = m_data->p().pen();
667 nPen.setJoinStyle(toQtLineJoin(lj));
668 m_data->p().setPen(nPen);
671 void GraphicsContext::setMiterLimit(float limit)
673 if (paintingDisabled())
676 QPen nPen = m_data->p().pen();
677 nPen.setMiterLimit(limit);
678 m_data->p().setPen(nPen);
681 void GraphicsContext::setAlpha(float opacity)
683 if (paintingDisabled())
686 m_data->p().setOpacity(opacity);
689 void GraphicsContext::setCompositeOperation(CompositeOperator op)
691 if (paintingDisabled())
694 m_data->p().setCompositionMode(toQtCompositionMode(op));
697 void GraphicsContext::clip(const Path& path)
699 if (paintingDisabled())
702 m_data->p().setClipPath(*path.platformPath());
705 void GraphicsContext::translate(float x, float y)
707 if (paintingDisabled())
710 m_data->p().translate(x, y);
713 IntPoint GraphicsContext::origin()
715 return IntPoint(qRound(m_data->p().matrix().dx()),
716 qRound(m_data->p().matrix().dy()));
719 void GraphicsContext::rotate(float radians)
721 if (paintingDisabled())
724 m_data->p().rotate(radians);
727 void GraphicsContext::scale(const FloatSize& s)
729 if (paintingDisabled())
732 m_data->p().scale(s.width(), s.height());
735 void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect,
738 if (paintingDisabled())
745 path.addEllipse(QRectF(rect.x(), rect.y(), rect.width(), rect.height()));
747 // Add inner ellipse.
748 path.addEllipse(QRectF(rect.x() + thickness, rect.y() + thickness,
749 rect.width() - (thickness * 2), rect.height() - (thickness * 2)));
751 path.setFillRule(Qt::OddEvenFill);
752 m_data->p().setClipPath(path, Qt::IntersectClip);
755 void GraphicsContext::addRoundedRectClip(const IntRect& rect, const IntSize& topLeft,
756 const IntSize& topRight, const IntSize& bottomLeft,
757 const IntSize& bottomRight)
759 if (paintingDisabled())
762 // Need sufficient width and height to contain these curves. Sanity check our top/bottom
763 // values and our width/height values to make sure the curves can all fit.
764 int requiredWidth = qMax(topLeft.width() + topRight.width(), bottomLeft.width() + bottomRight.width());
765 if (requiredWidth > rect.width())
768 int requiredHeight = qMax(topLeft.height() + bottomLeft.height(), topRight.height() + bottomRight.height());
769 if (requiredHeight > rect.height())
775 // OK, the curves can fit.
778 // Add the four ellipses to the path. Technically this really isn't good enough, since we could end up
779 // not clipping the other 3/4 of the ellipse we don't care about. We're relying on the fact that for
780 // normal use cases these ellipses won't overlap one another (or when they do the curvature of one will
781 // be subsumed by the other).
782 path.addEllipse(QRectF(rect.x(), rect.y(), topLeft.width() * 2, topLeft.height() * 2));
783 path.addEllipse(QRectF(rect.right() - topRight.width() * 2, rect.y(),
784 topRight.width() * 2, topRight.height() * 2));
785 path.addEllipse(QRectF(rect.x(), rect.bottom() - bottomLeft.height() * 2,
786 bottomLeft.width() * 2, bottomLeft.height() * 2));
787 path.addEllipse(QRectF(rect.right() - bottomRight.width() * 2,
788 rect.bottom() - bottomRight.height() * 2,
789 bottomRight.width() * 2, bottomRight.height() * 2));
791 int topLeftRightHeightMax = qMax(topLeft.height(), topRight.height());
792 int bottomLeftRightHeightMax = qMax(bottomLeft.height(), bottomRight.height());
794 int topBottomLeftWidthMax = qMax(topLeft.width(), bottomLeft.width());
795 int topBottomRightWidthMax = qMax(topRight.width(), bottomRight.width());
797 // Now add five rects (one for each edge rect in between the rounded corners and one for the interior).
798 path.addRect(QRectF(rect.x() + topLeft.width(),
800 rect.width() - topLeft.width() - topRight.width(),
801 topLeftRightHeightMax));
803 path.addRect(QRectF(rect.x() + bottomLeft.width(), rect.bottom() - bottomLeftRightHeightMax,
804 rect.width() - bottomLeft.width() - bottomRight.width(), bottomLeftRightHeightMax));
806 path.addRect(QRectF(rect.x(),
807 rect.y() + topLeft.height(),
808 topBottomLeftWidthMax,
809 rect.height() - topLeft.height() - bottomLeft.height()));
811 path.addRect(QRectF(rect.right() - topBottomRightWidthMax,
812 rect.y() + topRight.height(),
813 topBottomRightWidthMax,
814 rect.height() - topRight.height() - bottomRight.height()));
816 path.addRect(QRectF(rect.x() + topBottomLeftWidthMax,
817 rect.y() + topLeftRightHeightMax,
818 rect.width() - topBottomLeftWidthMax - topBottomRightWidthMax,
819 rect.height() - topLeftRightHeightMax - bottomLeftRightHeightMax));
821 path.setFillRule(Qt::WindingFill);
822 m_data->p().setClipPath(path, Qt::IntersectClip);
825 void GraphicsContext::concatCTM(const AffineTransform& transform)
827 if (paintingDisabled())
830 m_data->p().setMatrix(transform, true);
833 void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
838 void GraphicsContext::setPlatformFont(const Font& aFont)
840 m_data->p().setFont(aFont);
843 void GraphicsContext::setPlatformPen(const Pen& pen)
845 m_data->p().setPen(penToQPen(pen));
848 void GraphicsContext::setPlatformFillColor(const Color& color)
850 m_data->p().setBrush(QBrush(color));
853 GraphicsContext* contextForImage(SVGResourceImage*)