OSDN Git Service

Merge WebKit at r71558: Initial merge by git.
[android-x86/external-webkit.git] / WebCore / platform / graphics / qt / PathQt.cpp
1 /*
2  * Copyright (C) 2006 Zack Rusin   <zack@kde.org>
3  *               2006 Rob Buis     <buis@kde.org>
4  *               2009, 2010 Dirk Schulze <krit@webkit.org>
5  *
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
25  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "Path.h"
32
33 #include "AffineTransform.h"
34 #include "FloatRect.h"
35 #include "GraphicsContext.h"
36 #include "ImageBuffer.h"
37 #include "PlatformString.h"
38 #include "StrokeStyleApplier.h"
39 #include <QPainterPath>
40 #include <QTransform>
41 #include <QString>
42 #include <wtf/OwnPtr.h>
43
44 #define _USE_MATH_DEFINES
45 #include <math.h>
46
47 #ifndef M_PI
48 #   define M_PI 3.14159265358979323846
49 #endif
50
51 namespace WebCore {
52
53 Path::Path()
54 {
55 }
56
57 Path::~Path()
58 {
59 }
60
61 Path::Path(const Path& other)
62     : m_path(other.m_path)
63 {
64 }
65
66 Path& Path::operator=(const Path& other)
67 {
68     m_path = other.m_path;
69     return *this;
70 }
71
72 static inline bool areCollinear(const QPointF& a, const QPointF& b, const QPointF& c)
73 {
74     // Solved from comparing the slopes of a to b and b to c: (ay-by)/(ax-bx) == (cy-by)/(cx-bx)
75     return qFuzzyCompare((c.y() - b.y()) * (a.x() - b.x()), (a.y() - b.y()) * (c.x() - b.x()));
76 }
77
78 static inline bool withinRange(qreal p, qreal a, qreal b)
79 {
80     return (p >= a && p <= b) || (p >= b && p <= a);
81 }
82
83 // Check whether a point is on the border
84 static bool isPointOnPathBorder(const QPolygonF& border, const QPointF& p)
85 {
86     // null border doesn't contain points
87     if (border.isEmpty())
88         return false;
89
90     QPointF p1 = border.at(0);
91     QPointF p2;
92
93     for (int i = 1; i < border.size(); ++i) {
94         p2 = border.at(i);
95         if (areCollinear(p, p1, p2)
96                 // Once we know that the points are collinear we
97                 // only need to check one of the coordinates
98                 && (qAbs(p2.x() - p1.x()) > qAbs(p2.y() - p1.y()) ?
99                         withinRange(p.x(), p1.x(), p2.x()) :
100                         withinRange(p.y(), p1.y(), p2.y()))) {
101             return true;
102         }
103         p1 = p2;
104     }
105     return false;
106 }
107
108 bool Path::contains(const FloatPoint& point, WindRule rule) const
109 {
110     Qt::FillRule savedRule = m_path.fillRule();
111     const_cast<QPainterPath*>(&m_path)->setFillRule(rule == RULE_EVENODD ? Qt::OddEvenFill : Qt::WindingFill);
112
113     bool contains = m_path.contains(point);
114     
115     if (!contains) {
116         // check whether the point is on the border
117         contains = isPointOnPathBorder(m_path.toFillPolygon(), point);
118     }
119
120     const_cast<QPainterPath*>(&m_path)->setFillRule(savedRule);
121     return contains;
122 }
123
124 static GraphicsContext* scratchContext()
125 {
126     static QImage image(1, 1, QImage::Format_ARGB32_Premultiplied);
127     static QPainter painter(&image);
128     static GraphicsContext* context = new GraphicsContext(&painter);
129     return context;
130 }
131
132 bool Path::strokeContains(StrokeStyleApplier* applier, const FloatPoint& point) const
133 {
134     ASSERT(applier);
135
136     QPainterPathStroker stroke;
137     GraphicsContext* context = scratchContext();
138     applier->strokeStyle(context);
139
140     QPen pen = context->platformContext()->pen();
141     stroke.setWidth(pen.widthF());
142     stroke.setCapStyle(pen.capStyle());
143     stroke.setJoinStyle(pen.joinStyle());
144     stroke.setMiterLimit(pen.miterLimit());
145     stroke.setDashPattern(pen.dashPattern());
146     stroke.setDashOffset(pen.dashOffset());
147
148     return stroke.createStroke(m_path).contains(point);
149 }
150
151 void Path::translate(const FloatSize& size)
152 {
153     QTransform matrix;
154     matrix.translate(size.width(), size.height());
155     m_path = m_path * matrix;
156 }
157
158 FloatRect Path::boundingRect() const
159 {
160     return m_path.boundingRect();
161 }
162
163 FloatRect Path::strokeBoundingRect(StrokeStyleApplier* applier)
164 {
165     GraphicsContext* context = scratchContext();
166     QPainterPathStroker stroke;
167     if (applier) {
168         applier->strokeStyle(context);
169
170         QPen pen = context->platformContext()->pen();
171         stroke.setWidth(pen.widthF());
172         stroke.setCapStyle(pen.capStyle());
173         stroke.setJoinStyle(pen.joinStyle());
174         stroke.setMiterLimit(pen.miterLimit());
175         stroke.setDashPattern(pen.dashPattern());
176         stroke.setDashOffset(pen.dashOffset());
177     }
178     return stroke.createStroke(m_path).boundingRect();
179 }
180
181 void Path::moveTo(const FloatPoint& point)
182 {
183     m_path.moveTo(point);
184 }
185
186 void Path::addLineTo(const FloatPoint& p)
187 {
188     m_path.lineTo(p);
189 }
190
191 void Path::addQuadCurveTo(const FloatPoint& cp, const FloatPoint& p)
192 {
193     m_path.quadTo(cp, p);
194 }
195
196 void Path::addBezierCurveTo(const FloatPoint& cp1, const FloatPoint& cp2, const FloatPoint& p)
197 {
198     m_path.cubicTo(cp1, cp2, p);
199 }
200
201 void Path::addArcTo(const FloatPoint& p1, const FloatPoint& p2, float radius)
202 {
203     FloatPoint p0(m_path.currentPosition());
204
205     FloatPoint p1p0((p0.x() - p1.x()), (p0.y() - p1.y()));
206     FloatPoint p1p2((p2.x() - p1.x()), (p2.y() - p1.y()));
207     float p1p0_length = sqrtf(p1p0.x() * p1p0.x() + p1p0.y() * p1p0.y());
208     float p1p2_length = sqrtf(p1p2.x() * p1p2.x() + p1p2.y() * p1p2.y());
209
210     double cos_phi = (p1p0.x() * p1p2.x() + p1p0.y() * p1p2.y()) / (p1p0_length * p1p2_length);
211
212     // The points p0, p1, and p2 are on the same straight line (HTML5, 4.8.11.1.8)
213     // We could have used areCollinear() here, but since we're reusing
214     // the variables computed above later on we keep this logic.
215     if (qFuzzyCompare(qAbs(cos_phi), 1.0)) {
216         m_path.lineTo(p1);
217         return;
218     }
219
220     float tangent = radius / tan(acos(cos_phi) / 2);
221     float factor_p1p0 = tangent / p1p0_length;
222     FloatPoint t_p1p0((p1.x() + factor_p1p0 * p1p0.x()), (p1.y() + factor_p1p0 * p1p0.y()));
223
224     FloatPoint orth_p1p0(p1p0.y(), -p1p0.x());
225     float orth_p1p0_length = sqrt(orth_p1p0.x() * orth_p1p0.x() + orth_p1p0.y() * orth_p1p0.y());
226     float factor_ra = radius / orth_p1p0_length;
227
228     // angle between orth_p1p0 and p1p2 to get the right vector orthographic to p1p0
229     double cos_alpha = (orth_p1p0.x() * p1p2.x() + orth_p1p0.y() * p1p2.y()) / (orth_p1p0_length * p1p2_length);
230     if (cos_alpha < 0.f)
231         orth_p1p0 = FloatPoint(-orth_p1p0.x(), -orth_p1p0.y());
232
233     FloatPoint p((t_p1p0.x() + factor_ra * orth_p1p0.x()), (t_p1p0.y() + factor_ra * orth_p1p0.y()));
234
235     // calculate angles for addArc
236     orth_p1p0 = FloatPoint(-orth_p1p0.x(), -orth_p1p0.y());
237     float sa = acos(orth_p1p0.x() / orth_p1p0_length);
238     if (orth_p1p0.y() < 0.f)
239         sa = 2 * piDouble - sa;
240
241     // anticlockwise logic
242     bool anticlockwise = false;
243
244     float factor_p1p2 = tangent / p1p2_length;
245     FloatPoint t_p1p2((p1.x() + factor_p1p2 * p1p2.x()), (p1.y() + factor_p1p2 * p1p2.y()));
246     FloatPoint orth_p1p2((t_p1p2.x() - p.x()), (t_p1p2.y() - p.y()));
247     float orth_p1p2_length = sqrtf(orth_p1p2.x() * orth_p1p2.x() + orth_p1p2.y() * orth_p1p2.y());
248     float ea = acos(orth_p1p2.x() / orth_p1p2_length);
249     if (orth_p1p2.y() < 0)
250         ea = 2 * piDouble - ea;
251     if ((sa > ea) && ((sa - ea) < piDouble))
252         anticlockwise = true;
253     if ((sa < ea) && ((ea - sa) > piDouble))
254         anticlockwise = true;
255
256     m_path.lineTo(t_p1p0);
257
258     addArc(p, radius, sa, ea, anticlockwise);
259 }
260
261 void Path::closeSubpath()
262 {
263     m_path.closeSubpath();
264 }
265
266 #define DEGREES(t) ((t) * 180.0 / M_PI)
267 void Path::addArc(const FloatPoint& p, float r, float sar, float ear, bool anticlockwise)
268 {
269     qreal xc = p.x();
270     qreal yc = p.y();
271     qreal radius = r;
272
273
274     //### HACK
275     // In Qt we don't switch the coordinate system for degrees
276     // and still use the 0,0 as bottom left for degrees so we need
277     // to switch
278     sar = -sar;
279     ear = -ear;
280     anticlockwise = !anticlockwise;
281     //end hack
282
283     float sa = DEGREES(sar);
284     float ea = DEGREES(ear);
285
286     double span = 0;
287
288     double xs = xc - radius;
289     double ys = yc - radius;
290     double width  = radius*2;
291     double height = radius*2;
292
293     if ((!anticlockwise && (ea - sa >= 360)) || (anticlockwise && (sa - ea >= 360)))
294         // If the anticlockwise argument is false and endAngle-startAngle is equal to or greater than 2*PI, or, if the
295         // anticlockwise argument is true and startAngle-endAngle is equal to or greater than 2*PI, then the arc is the whole
296         // circumference of this circle.
297         span = 360;
298     else {
299         if (!anticlockwise && (ea < sa))
300             span += 360;
301         else if (anticlockwise && (sa < ea))
302             span -= 360;
303
304         // this is also due to switched coordinate system
305         // we would end up with a 0 span instead of 360
306         if (!(qFuzzyCompare(span + (ea - sa) + 1, 1.0)
307             && qFuzzyCompare(qAbs(span), 360.0))) {
308             // mod 360
309             span += (ea - sa) - (static_cast<int>((ea - sa) / 360)) * 360;
310         }
311     }
312
313     // If the path is empty, move to where the arc will start to avoid painting a line from (0,0)
314     // NOTE: QPainterPath::isEmpty() won't work here since it ignores a lone MoveToElement
315     if (!m_path.elementCount())
316         m_path.arcMoveTo(xs, ys, width, height, sa);
317     else if (!radius) {
318         m_path.lineTo(xc, yc);
319         return;
320     }
321
322     m_path.arcTo(xs, ys, width, height, sa, span);
323
324 }
325
326 void Path::addRect(const FloatRect& r)
327 {
328     m_path.addRect(r.x(), r.y(), r.width(), r.height());
329 }
330
331 void Path::addEllipse(const FloatRect& r)
332 {
333     m_path.addEllipse(r.x(), r.y(), r.width(), r.height());
334 }
335
336 void Path::clear()
337 {
338     if (!m_path.elementCount())
339         return;
340     m_path = QPainterPath();
341 }
342
343 bool Path::isEmpty() const
344 {
345     // Don't use QPainterPath::isEmpty(), as that also returns true if there's only
346     // one initial MoveTo element in the path.
347     return !m_path.elementCount();
348 }
349
350 bool Path::hasCurrentPoint() const
351 {
352     return !isEmpty();
353 }
354
355 FloatPoint Path::currentPoint() const 
356 {
357     return m_path.currentPosition();
358 }
359
360 void Path::apply(void* info, PathApplierFunction function) const
361 {
362     PathElement pelement;
363     FloatPoint points[3];
364     pelement.points = points;
365     for (int i = 0; i < m_path.elementCount(); ++i) {
366         const QPainterPath::Element& cur = m_path.elementAt(i);
367
368         switch (cur.type) {
369             case QPainterPath::MoveToElement:
370                 pelement.type = PathElementMoveToPoint;
371                 pelement.points[0] = QPointF(cur);
372                 function(info, &pelement);
373                 break;
374             case QPainterPath::LineToElement:
375                 pelement.type = PathElementAddLineToPoint;
376                 pelement.points[0] = QPointF(cur);
377                 function(info, &pelement);
378                 break;
379             case QPainterPath::CurveToElement:
380             {
381                 const QPainterPath::Element& c1 = m_path.elementAt(i + 1);
382                 const QPainterPath::Element& c2 = m_path.elementAt(i + 2);
383
384                 Q_ASSERT(c1.type == QPainterPath::CurveToDataElement);
385                 Q_ASSERT(c2.type == QPainterPath::CurveToDataElement);
386
387                 pelement.type = PathElementAddCurveToPoint;
388                 pelement.points[0] = QPointF(cur);
389                 pelement.points[1] = QPointF(c1);
390                 pelement.points[2] = QPointF(c2);
391                 function(info, &pelement);
392
393                 i += 2;
394                 break;
395             }
396             case QPainterPath::CurveToDataElement:
397                 Q_ASSERT(false);
398         }
399     }
400 }
401
402 void Path::transform(const AffineTransform& transform)
403 {
404     QTransform qTransform(transform);
405 #if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
406     // Workaround for http://bugreports.qt.nokia.com/browse/QTBUG-11264
407     // QTransform.map doesn't handle the MoveTo element because of the isEmpty issue
408     if (m_path.isEmpty() && m_path.elementCount()) {
409         QPointF point = qTransform.map(m_path.currentPosition());
410         moveTo(point);
411     } else 
412 #endif
413         m_path = qTransform.map(m_path);
414 }
415
416 float Path::length()
417 {
418     return m_path.length();
419 }
420
421 FloatPoint Path::pointAtLength(float length, bool& ok)
422 {
423     ok = (length >= 0 && length <= m_path.length());
424
425     qreal percent = m_path.percentAtLength(length);
426     QPointF point = m_path.pointAtPercent(percent);
427
428     return point;
429 }
430
431 float Path::normalAngleAtLength(float length, bool& ok)
432 {
433     ok = (length >= 0 && length <= m_path.length());
434
435     qreal percent = m_path.percentAtLength(length);
436     qreal angle = m_path.angleAtPercent(percent);
437
438     return angle;
439 }
440
441 }
442
443 // vim: ts=4 sw=4 et