Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qpainterpath.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qpainterpath.h"
7
8#include <qbitmap.h>
9#include <qdebug.h>
10#include <qiodevice.h>
11#include <qlist.h>
12#include <qpen.h>
13#include <qpolygon.h>
14#include <qtextlayout.h>
15#include <qvarlengtharray.h>
16#include <qmath.h>
17
18#include <private/qbezier_p.h>
19#include <private/qfontengine_p.h>
20#include <private/qnumeric_p.h>
21#include <private/qobject_p.h>
22#include <private/qpathclipper_p.h>
23#include <private/qstroker_p.h>
24#include <private/qtextengine_p.h>
25
26#include <cmath>
27
28#include <limits.h>
29
30#if 0
31#include <performance.h>
32#else
33#define PM_INIT
34#define PM_MEASURE(x)
35#define PM_DISPLAY
36#endif
37
39
40static inline bool isValidCoord(qreal c)
41{
42 if (sizeof(qreal) >= sizeof(double))
43 return qIsFinite(c) && fabs(c) < 1e128;
44 else
45 return qIsFinite(c) && fabsf(float(c)) < 1e16f;
46}
47
48static bool hasValidCoords(QPointF p)
49{
50 return isValidCoord(p.x()) && isValidCoord(p.y());
51}
52
53static bool hasValidCoords(QRectF r)
54{
55 return isValidCoord(r.x()) && isValidCoord(r.y()) && isValidCoord(r.width()) && isValidCoord(r.height());
56}
57
58// This value is used to determine the length of control point vectors
59// when approximating arc segments as curves. The factor is multiplied
60// with the radius of the circle.
61
62// #define QPP_DEBUG
63// #define QPP_STROKE_DEBUG
64//#define QPP_FILLPOLYGONS_DEBUG
65
66QPainterPath qt_stroke_dash(const QPainterPath &path, qreal *dashes, int dashCount);
67
68void qt_find_ellipse_coords(const QRectF &r, qreal angle, qreal length,
69 QPointF* startPoint, QPointF *endPoint)
70{
71 if (r.isNull()) {
72 if (startPoint)
73 *startPoint = QPointF();
74 if (endPoint)
75 *endPoint = QPointF();
76 return;
77 }
78
79 qreal w2 = r.width() / 2;
80 qreal h2 = r.height() / 2;
81
82 qreal angles[2] = { angle, angle + length };
83 QPointF *points[2] = { startPoint, endPoint };
84
85 for (int i = 0; i < 2; ++i) {
86 if (!points[i])
87 continue;
88
89 qreal theta = angles[i] - 360 * std::floor(angles[i] / 360);
90 qreal t = theta / 90;
91 // truncate
92 int quadrant = int(t);
93 t -= quadrant;
94
95 t = qt_t_for_arc_angle(90 * t);
96
97 // swap x and y?
98 if (quadrant & 1)
99 t = 1 - t;
100
101 qreal a, b, c, d;
102 QBezier::coefficients(t, a, b, c, d);
103 QPointF p(a + b + c*QT_PATH_KAPPA, d + c + b*QT_PATH_KAPPA);
104
105 // left quadrants
106 if (quadrant == 1 || quadrant == 2)
107 p.rx() = -p.x();
108
109 // top quadrants
110 if (quadrant == 0 || quadrant == 1)
111 p.ry() = -p.y();
112
113 *points[i] = r.center() + QPointF(w2 * p.x(), h2 * p.y());
114 }
115}
116
117#ifdef QPP_DEBUG
118static void qt_debug_path(const QPainterPath &path)
119{
120 const char *names[] = {
121 "MoveTo ",
122 "LineTo ",
123 "CurveTo ",
124 "CurveToData"
125 };
126
127 printf("\nQPainterPath: elementCount=%d\n", path.elementCount());
128 for (int i=0; i<path.elementCount(); ++i) {
129 const QPainterPath::Element &e = path.elementAt(i);
130 Q_ASSERT(e.type >= 0 && e.type <= QPainterPath::CurveToDataElement);
131 printf(" - %3d:: %s, (%.2f, %.2f)\n", i, names[e.type], e.x, e.y);
132 }
133}
134#endif
135
136/*!
137 \class QPainterPath
138 \ingroup painting
139 \inmodule QtGui
140
141 \reentrant
142
143 \brief The QPainterPath class provides a container for painting operations,
144 enabling graphical shapes to be constructed and reused.
145
146 A painter path is an object composed of a number of graphical
147 building blocks, such as rectangles, ellipses, lines, and curves.
148 Building blocks can be joined in closed subpaths, for example as a
149 rectangle or an ellipse. A closed path has coinciding start and
150 end points. Or they can exist independently as unclosed subpaths,
151 such as lines and curves.
152
153 A QPainterPath object can be used for filling, outlining, and
154 clipping. To generate fillable outlines for a given painter path,
155 use the QPainterPathStroker class. The main advantage of painter
156 paths over normal drawing operations is that complex shapes only
157 need to be created once; then they can be drawn many times using
158 only calls to the QPainter::drawPath() function.
159
160 QPainterPath provides a collection of functions that can be used
161 to obtain information about the path and its elements. In addition
162 it is possible to reverse the order of the elements using the
163 toReversed() function. There are also several functions to convert
164 this painter path object into a polygon representation.
165
166 \section1 Composing a QPainterPath
167
168 A QPainterPath object can be constructed as an empty path, with a
169 given start point, or as a copy of another QPainterPath object.
170 Once created, lines and curves can be added to the path using the
171 lineTo(), arcTo(), cubicTo() and quadTo() functions. The lines and
172 curves stretch from the currentPosition() to the position passed
173 as argument.
174
175 The currentPosition() of the QPainterPath object is always the end
176 position of the last subpath that was added (or the initial start
177 point). Use the moveTo() function to move the currentPosition()
178 without adding a component. The moveTo() function implicitly
179 starts a new subpath, and closes the previous one. Another way of
180 starting a new subpath is to call the closeSubpath() function
181 which closes the current path by adding a line from the
182 currentPosition() back to the path's start position. Note that the
183 new path will have (0, 0) as its initial currentPosition().
184
185 QPainterPath class also provides several convenience functions to
186 add closed subpaths to a painter path: addEllipse(), addPath(),
187 addRect(), addRegion() and addText(). The addPolygon() function
188 adds an \e unclosed subpath. In fact, these functions are all
189 collections of moveTo(), lineTo() and cubicTo() operations.
190
191 In addition, a path can be added to the current path using the
192 connectPath() function. But note that this function will connect
193 the last element of the current path to the first element of given
194 one by adding a line.
195
196 Below is a code snippet that shows how a QPainterPath object can
197 be used:
198
199 \table 70%
200 \row
201 \li \inlineimage qpainterpath-construction.png
202 {Path with rectangle and bezier curves}
203 \li
204 \snippet code/src_gui_painting_qpainterpath.cpp 0
205 \endtable
206
207 The painter path is initially empty when constructed. We first add
208 a rectangle, which is a closed subpath. Then we add two bezier
209 curves which together form a closed subpath even though they are
210 not closed individually. Finally we draw the entire path. The path
211 is filled using the default fill rule, Qt::OddEvenFill. Qt
212 provides two methods for filling paths:
213
214 \table
215 \header
216 \li Qt::OddEvenFill
217 \li Qt::WindingFill
218 \row
219 \li \inlineimage qt-fillrule-oddeven.png {Star with odd-even fill}
220 \li \inlineimage qt-fillrule-winding.png {Star with winding fill}
221 \endtable
222
223 See the Qt::FillRule documentation for the definition of the
224 rules. A painter path's currently set fill rule can be retrieved
225 using the fillRule() function, and altered using the setFillRule()
226 function.
227
228 \section1 Arcs and Ellipses
229
230 The angle arguments of \l{arcTo()}, \l{arcMoveTo()},
231 \l{QPainter::drawArc()}, \l{QPainter::drawPie()}, and
232 \l{QPainter::drawChord()} are \e{eccentric} angles. An eccentric
233 angle parameterizes the ellipse that fits into the bounding
234 rectangle; it does not measure the direction from the center of that
235 rectangle to the resulting point. In general the two coincide only
236 when the bounding rectangle is square. On a 400 by 100 rectangle, for
237 example, an angle of 45 degrees yields a point that lies roughly 14
238 degrees above the horizontal as seen from the center.
239
240 To place a point at a given direction from the center instead,
241 compute that point yourself and pass it to \l{moveTo()} or
242 \l{lineTo()}. Alternatively, keep using these functions and convert
243 the direction: on a bounding rectangle of the given \c width and
244 \c height, the direction \c theta, in radians, corresponds to the
245 eccentric angle
246 \c{qRadiansToDegrees(qAtan2(width * qSin(theta), height * qCos(theta)))}.
247
248 Because a painter path stores only lines and Bezier segments, Qt
249 approximates arcs and ellipses with cubic Bezier curves instead of
250 evaluating them trigonometrically. For a circle, the approximation
251 places points less than 0.1% of the radius away from their true
252 positions. Code that compares a point from \l{arcMoveTo()} against
253 one computed with \l{<QtMath>::}{qSin()} and \l{<QtMath>::}{qCos()}
254 must therefore allow for a tolerance instead of testing for
255 equality.
256
257 \section1 QPainterPath Information
258
259 The QPainterPath class provides a collection of functions that
260 returns information about the path and its elements.
261
262 The currentPosition() function returns the end point of the last
263 subpath that was added (or the initial start point). The
264 elementAt() function can be used to retrieve the various subpath
265 elements, the \e number of elements can be retrieved using the
266 elementCount() function, and the isEmpty() function tells whether
267 this QPainterPath object contains any elements at all.
268
269 The controlPointRect() function returns the rectangle containing
270 all the points and control points in this path. This function is
271 significantly faster to compute than the exact boundingRect()
272 which returns the bounding rectangle of this painter path with
273 floating point precision.
274
275 Finally, QPainterPath provides the contains() function which can
276 be used to determine whether a given point or rectangle is inside
277 the path, and the intersects() function which determines if any of
278 the points inside a given rectangle also are inside this path.
279
280 \section1 QPainterPath Conversion
281
282 For compatibility reasons, it might be required to simplify the
283 representation of a painter path: QPainterPath provides the
284 toFillPolygon(), toFillPolygons() and toSubpathPolygons()
285 functions which convert the painter path into a polygon. The
286 toFillPolygon() returns the painter path as one single polygon,
287 while the two latter functions return a list of polygons.
288
289 The toFillPolygons() and toSubpathPolygons() functions are
290 provided because it is usually faster to draw several small
291 polygons than to draw one large polygon, even though the total
292 number of points drawn is the same. The difference between the two
293 is the \e number of polygons they return: The toSubpathPolygons()
294 creates one polygon for each subpath regardless of intersecting
295 subpaths (i.e. overlapping bounding rectangles), while the
296 toFillPolygons() functions creates only one polygon for
297 overlapping subpaths.
298
299 The toFillPolygon() and toFillPolygons() functions first convert
300 all the subpaths to polygons, then uses a rewinding technique to
301 make sure that overlapping subpaths can be filled using the
302 correct fill rule. Note that rewinding inserts additional lines in
303 the polygon so the outline of the fill polygon does not match the
304 outline of the path.
305
306 \section1 Examples
307
308 Qt provides the \l {painting/painterpaths}{Painter Paths Example}
309 and the \l {painting/deform}{Vector Deformation example} which are
310 located in Qt's example directory.
311
312 The \l {painting/painterpaths}{Painter Paths Example} shows how
313 painter paths can be used to build complex shapes for rendering
314 and lets the user experiment with the filling and stroking. The
315 \l {painting/deform}{Vector Deformation Example} shows how to use
316 QPainterPath to draw text.
317
318 \table
319 \header
320 \li \l {painting/painterpaths}{Painter Paths Example}
321 \li \l {painting/deform}{Vector Deformation Example}
322 \row
323 \li \inlineimage qpainterpath-example.png {Painter Paths application}
324 \li \inlineimage qpainterpath-demo.png {Vector Deformation application}
325 \endtable
326
327 \sa QPainterPathStroker, QPainter, QRegion, {Painter Paths Example}
328*/
329
330/*!
331 \enum QPainterPath::ElementType
332
333 This enum describes the types of elements used to connect vertices
334 in subpaths.
335
336 Note that elements added as closed subpaths using the
337 addEllipse(), addPath(), addPolygon(), addRect(), addRegion() and
338 addText() convenience functions, is actually added to the path as
339 a collection of separate elements using the moveTo(), lineTo() and
340 cubicTo() functions.
341
342 \value MoveToElement A new subpath. See also moveTo().
343 \value LineToElement A line. See also lineTo().
344 \value CurveToElement A curve. See also cubicTo() and quadTo().
345 \value CurveToDataElement The extra data required to describe a curve in
346 a CurveToElement element.
347
348 \sa elementAt(), elementCount()
349*/
350
351/*!
352 \class QPainterPath::Element
353 \inmodule QtGui
354
355 \brief The QPainterPath::Element class specifies the position and
356 type of a subpath.
357
358 Once a QPainterPath object is constructed, subpaths like lines and
359 curves can be added to the path (creating
360 QPainterPath::LineToElement and QPainterPath::CurveToElement
361 components).
362
363 The lines and curves stretch from the currentPosition() to the
364 position passed as argument. The currentPosition() of the
365 QPainterPath object is always the end position of the last subpath
366 that was added (or the initial start point). The moveTo() function
367 can be used to move the currentPosition() without adding a line or
368 curve, creating a QPainterPath::MoveToElement component.
369
370 \sa QPainterPath
371*/
372
373/*!
374 \variable QPainterPath::Element::x
375 \brief the x coordinate of the element's position.
376
377 \sa {operator QPointF()}
378*/
379
380/*!
381 \variable QPainterPath::Element::y
382 \brief the y coordinate of the element's position.
383
384 \sa {operator QPointF()}
385*/
386
387/*!
388 \variable QPainterPath::Element::type
389 \brief the type of element
390
391 \sa isCurveTo(), isLineTo(), isMoveTo()
392*/
393
394/*!
395 \fn bool QPainterPath::Element::operator==(const Element &other) const
396 \since 4.2
397
398 Returns \c true if this element is equal to \a other;
399 otherwise returns \c false.
400
401 \sa operator!=()
402*/
403
404/*!
405 \fn bool QPainterPath::Element::operator!=(const Element &other) const
406 \since 4.2
407
408 Returns \c true if this element is not equal to \a other;
409 otherwise returns \c false.
410
411 \sa operator==()
412*/
413
414/*!
415 \fn bool QPainterPath::Element::isCurveTo () const
416
417 Returns \c true if the element is a curve, otherwise returns \c false.
418
419 \sa type, QPainterPath::CurveToElement
420*/
421
422/*!
423 \fn bool QPainterPath::Element::isLineTo () const
424
425 Returns \c true if the element is a line, otherwise returns \c false.
426
427 \sa type, QPainterPath::LineToElement
428*/
429
430/*!
431 \fn bool QPainterPath::Element::isMoveTo () const
432
433 Returns \c true if the element is moving the current position,
434 otherwise returns \c false.
435
436 \sa type, QPainterPath::MoveToElement
437*/
438
439/*!
440 \fn QPainterPath::Element::operator QPointF () const
441
442 Returns the element's position.
443
444 \sa x, y
445*/
446
447/*!
448 \fn void QPainterPath::addEllipse(qreal x, qreal y, qreal width, qreal height)
449 \overload
450
451 Creates an ellipse within the bounding rectangle defined by its top-left
452 corner at (\a x, \a y), \a width and \a height, and adds it to the
453 painter path as a closed subpath.
454*/
455
456/*!
457 \since 4.4
458
459 \fn void QPainterPath::addEllipse(const QPointF &center, qreal rx, qreal ry)
460 \overload
461
462 Creates an ellipse positioned at \a{center} with radii \a{rx} and \a{ry},
463 and adds it to the painter path as a closed subpath.
464*/
465
466/*!
467 \fn void QPainterPath::addText(qreal x, qreal y, const QFont &font, const QString &text)
468 \overload
469
470 Adds the given \a text to this path as a set of closed subpaths created
471 from the \a font supplied. The subpaths are positioned so that the left
472 end of the text's baseline lies at the point specified by (\a x, \a y).
473*/
474
475/*!
476 \since 6.13
477
478 Returns a (potentially empty) \l{QSpan}{span} of the painter path's
479 elements.
480
481 The return value is valid until the next call to a non-const operation on
482 this painter path (which might be destruction).
483
484 \sa elementCount(), elementAt(), isEmpty(), ElementType
485*/
486auto QPainterPath::elements() const noexcept -> QSpan<const Element>
487{
488 if (!d_ptr)
489 return {};
490 return d_ptr->elements;
491}
492
493/*!
494 \fn int QPainterPath::elementCount() const
495
496 Returns the number of path elements in the painter path.
497
498 \sa ElementType, elementAt(), isEmpty()
499 \sa elements()
500*/
501
502int QPainterPath::elementCount() const
503{
504 return d_ptr ? d_ptr->elements.size() : 0;
505}
506
507/*!
508 \fn QPainterPath::Element QPainterPath::elementAt(int index) const
509
510 Returns the element at the given \a index in the painter path.
511
512 \sa ElementType, elementCount(), isEmpty()
513 \sa elements()
514*/
515
516QPainterPath::Element QPainterPath::elementAt(int i) const
517{
518 Q_ASSERT(d_ptr);
519 Q_ASSERT(i >= 0 && i < elementCount());
520 return d_ptr->elements.at(i);
521}
522
523/*!
524 \fn void QPainterPath::setElementPositionAt(int index, qreal x, qreal y)
525 \since 4.2
526
527 Sets the x and y coordinate of the element at index \a index to \a
528 x and \a y.
529*/
530
531void QPainterPath::setElementPositionAt(int i, qreal x, qreal y)
532{
533 Q_ASSERT(d_ptr);
534 Q_ASSERT(i >= 0 && i < elementCount());
535 setDirty(true);
536 QPainterPath::Element &e = d_ptr->elements[i];
537 e.x = x;
538 e.y = y;
539}
540
541
542/*###
543 \fn QPainterPath &QPainterPath::operator +=(const QPainterPath &other)
544
545 Appends the \a other painter path to this painter path and returns a
546 reference to the result.
547*/
548
549/*!
550 Constructs an empty QPainterPath object.
551*/
552QPainterPath::QPainterPath() noexcept
553 : d_ptr(nullptr)
554{
555}
556
557/*!
558 \fn QPainterPath::QPainterPath(const QPainterPath &path)
559
560 Creates a QPainterPath object that is a copy of the given \a path.
561
562 \sa operator=()
563*/
564QPainterPath::QPainterPath(const QPainterPath &other)
565 : d_ptr(other.d_ptr ? new QPainterPathPrivate(*other.d_ptr) : nullptr)
566{
567}
568
569/*!
570 \fn QPainterPath::QPainterPath(QPainterPath &&other)
571 \since 6.10
572
573 Move-constructs a new painter path from \a other.
574
575 The moved-from object \a other is placed in the default-constructed state.
576*/
577
578/*!
579 Creates a QPainterPath object with the given \a startPoint as its
580 current position.
581*/
582
583QPainterPath::QPainterPath(const QPointF &startPoint)
584 : d_ptr(new QPainterPathPrivate(startPoint))
585{
586}
587
588/*!
589 \internal
590*/
591void QPainterPath::ensureData_helper()
592{
593 Q_ASSERT(d_ptr == nullptr);
594 QPainterPathPrivate *data = new QPainterPathPrivate;
595 data->elements.reserve(16);
596 QPainterPath::Element e = { 0, 0, QPainterPath::MoveToElement };
597 data->elements << e;
598 d_ptr = data;
599 Q_ASSERT(d_ptr != nullptr);
600}
601
602/*!
603 \fn QPainterPath &QPainterPath::operator=(const QPainterPath &path)
604
605 Assigns the given \a path to this painter path.
606
607 \sa QPainterPath()
608*/
609QPainterPath &QPainterPath::operator=(const QPainterPath &other)
610{
611 QPainterPath copy(other);
612 swap(copy);
613 return *this;
614}
615
616/*!
617 \fn QPainterPath &QPainterPath::operator=(QPainterPath &&other)
618
619 Move-assigns \a other to this QPainterPath instance.
620
621 \since 5.2
622*/
623
624/*!
625 \fn void QPainterPath::swap(QPainterPath &other)
626 \since 4.8
627 \memberswap{painter path}
628*/
629
630/*!
631 Destroys this QPainterPath object.
632*/
633QPainterPath::~QPainterPath()
634{
635 delete d_ptr;
636}
637
638/*!
639 Clears the path elements stored.
640
641 This allows the path to reuse previous memory allocations.
642
643 \sa reserve(), capacity()
644 \since 5.13
645*/
646void QPainterPath::clear()
647{
648 if (!d_ptr)
649 return;
650
651 setDirty(true);
652 d_func()->clear();
653 d_func()->elements.append( {0, 0, MoveToElement} );
654}
655
656/*!
657 Reserves a given amount of elements in QPainterPath's internal memory.
658
659 Attempts to allocate memory for at least \a size elements.
660
661 \sa clear(), capacity(), QList::reserve()
662 \since 5.13
663*/
664void QPainterPath::reserve(int size)
665{
666 Q_D(QPainterPath);
667 if ((!d && size > 0) || (d && d->elements.capacity() < size)) {
668 ensureData();
669 setDirty(true);
670 d_func()->elements.reserve(size);
671 }
672}
673
674/*!
675 Returns the number of elements allocated by the QPainterPath.
676
677 \sa clear(), reserve()
678 \since 5.13
679*/
680int QPainterPath::capacity() const
681{
682 Q_D(QPainterPath);
683 if (d)
684 return d->elements.capacity();
685
686 return 0;
687}
688
689/*!
690 Closes the current subpath by drawing a line to the beginning of
691 the subpath, automatically starting a new path. The current point
692 of the new path is (0, 0).
693
694 If the subpath does not contain any elements, this function does
695 nothing.
696
697 \sa moveTo(), {QPainterPath#Composing a QPainterPath}{Composing
698 a QPainterPath}
699 */
700void QPainterPath::closeSubpath()
701{
702#ifdef QPP_DEBUG
703 printf("QPainterPath::closeSubpath()\n");
704#endif
705 if (isEmpty())
706 return;
707 setDirty(true);
708
709 d_func()->close();
710}
711
712/*!
713 \fn void QPainterPath::moveTo(qreal x, qreal y)
714
715 \overload
716
717 Moves the current position to (\a{x}, \a{y}) and starts a new
718 subpath, implicitly closing the previous path.
719*/
720
721/*!
722 \fn void QPainterPath::moveTo(const QPointF &point)
723
724 Moves the current point to the given \a point, implicitly starting
725 a new subpath and closing the previous one.
726
727 \sa closeSubpath(), {QPainterPath#Composing a
728 QPainterPath}{Composing a QPainterPath}
729*/
730void QPainterPath::moveTo(const QPointF &p)
731{
732#ifdef QPP_DEBUG
733 printf("QPainterPath::moveTo() (%.2f,%.2f)\n", p.x(), p.y());
734#endif
735
736 if (!hasValidCoords(p)) {
737#ifndef QT_NO_DEBUG
738 qWarning("QPainterPath::moveTo: Adding point with invalid coordinates, ignoring call");
739#endif
740 return;
741 }
742
743 ensureData();
744 setDirty(true);
745
746 QPainterPathPrivate *d = d_func();
747 Q_ASSERT(!d->elements.isEmpty());
748
749 d->require_moveTo = false;
750
751 if (d->elements.constLast().type == MoveToElement) {
752 d->elements.last().x = p.x();
753 d->elements.last().y = p.y();
754 } else {
755 Element elm = { p.x(), p.y(), MoveToElement };
756 d->elements.append(elm);
757 }
758 d->cStart = d->elements.size() - 1;
759}
760
761/*!
762 \fn void QPainterPath::lineTo(qreal x, qreal y)
763
764 \overload
765
766 Draws a line from the current position to the point (\a{x},
767 \a{y}).
768*/
769
770/*!
771 \fn void QPainterPath::lineTo(const QPointF &endPoint)
772
773 Adds a straight line from the current position to the given \a
774 endPoint. After the line is drawn, the current position is updated
775 to be at the end point of the line.
776
777 \sa addPolygon(), addRect(), {QPainterPath#Composing a
778 QPainterPath}{Composing a QPainterPath}
779 */
780void QPainterPath::lineTo(const QPointF &p)
781{
782#ifdef QPP_DEBUG
783 printf("QPainterPath::lineTo() (%.2f,%.2f)\n", p.x(), p.y());
784#endif
785
786 if (!hasValidCoords(p)) {
787#ifndef QT_NO_DEBUG
788 qWarning("QPainterPath::lineTo: Adding point with invalid coordinates, ignoring call");
789#endif
790 return;
791 }
792
793 ensureData();
794 setDirty(true);
795
796 QPainterPathPrivate *d = d_func();
797 Q_ASSERT(!d->elements.isEmpty());
798 d->maybeMoveTo();
799 if (p == QPointF(d->elements.constLast()))
800 return;
801 Element elm = { p.x(), p.y(), LineToElement };
802 d->elements.append(elm);
803
804 d->convex = d->elements.size() == 3 || (d->elements.size() == 4 && d->isClosed());
805}
806
807/*!
808 \fn void QPainterPath::cubicTo(qreal c1X, qreal c1Y, qreal c2X,
809 qreal c2Y, qreal endPointX, qreal endPointY);
810
811 \overload
812
813 Adds a cubic Bezier curve between the current position and the end
814 point (\a{endPointX}, \a{endPointY}) with control points specified
815 by (\a{c1X}, \a{c1Y}) and (\a{c2X}, \a{c2Y}).
816*/
817
818/*!
819 \fn void QPainterPath::cubicTo(const QPointF &c1, const QPointF &c2, const QPointF &endPoint)
820
821 Adds a cubic Bezier curve between the current position and the
822 given \a endPoint using the control points specified by \a c1, and
823 \a c2.
824
825 After the curve is added, the current position is updated to be at
826 the end point of the curve.
827
828 \table 100%
829 \row
830 \li \inlineimage qpainterpath-cubicto.png
831 {Cubic bezier curve with control points c1 and c2}
832 \li
833 \snippet code/src_gui_painting_qpainterpath.cpp 1
834 \endtable
835
836 \sa quadTo(), {QPainterPath#Composing a QPainterPath}{Composing
837 a QPainterPath}
838*/
839void QPainterPath::cubicTo(const QPointF &c1, const QPointF &c2, const QPointF &e)
840{
841#ifdef QPP_DEBUG
842 printf("QPainterPath::cubicTo() (%.2f,%.2f), (%.2f,%.2f), (%.2f,%.2f)\n",
843 c1.x(), c1.y(), c2.x(), c2.y(), e.x(), e.y());
844#endif
845
846 if (!hasValidCoords(c1) || !hasValidCoords(c2) || !hasValidCoords(e)) {
847#ifndef QT_NO_DEBUG
848 qWarning("QPainterPath::cubicTo: Adding point with invalid coordinates, ignoring call");
849#endif
850 return;
851 }
852
853 ensureData();
854 setDirty(true);
855
856 QPainterPathPrivate *d = d_func();
857 Q_ASSERT(!d->elements.isEmpty());
858
859
860 // Abort on empty curve as a stroker cannot handle this and the
861 // curve is irrelevant anyway.
862 if (d->elements.constLast() == c1 && c1 == c2 && c2 == e)
863 return;
864
865 d->maybeMoveTo();
866
867 Element ce1 = { c1.x(), c1.y(), CurveToElement };
868 Element ce2 = { c2.x(), c2.y(), CurveToDataElement };
869 Element ee = { e.x(), e.y(), CurveToDataElement };
870 d->elements << ce1 << ce2 << ee;
871}
872
873/*!
874 \fn void QPainterPath::quadTo(qreal cx, qreal cy, qreal endPointX, qreal endPointY);
875
876 \overload
877
878 Adds a quadratic Bezier curve between the current point and the endpoint
879 (\a{endPointX}, \a{endPointY}) with the control point specified by
880 (\a{cx}, \a{cy}).
881*/
882
883/*!
884 \fn void QPainterPath::quadTo(const QPointF &c, const QPointF &endPoint)
885
886 Adds a quadratic Bezier curve between the current position and the
887 given \a endPoint with the control point specified by \a c.
888
889 After the curve is added, the current point is updated to be at
890 the end point of the curve.
891
892 \sa cubicTo(), {QPainterPath#Composing a QPainterPath}{Composing a
893 QPainterPath}
894*/
895void QPainterPath::quadTo(const QPointF &c, const QPointF &e)
896{
897#ifdef QPP_DEBUG
898 printf("QPainterPath::quadTo() (%.2f,%.2f), (%.2f,%.2f)\n",
899 c.x(), c.y(), e.x(), e.y());
900#endif
901
902 if (!hasValidCoords(c) || !hasValidCoords(e)) {
903#ifndef QT_NO_DEBUG
904 qWarning("QPainterPath::quadTo: Adding point with invalid coordinates, ignoring call");
905#endif
906 return;
907 }
908
909 ensureData();
910 setDirty(true);
911
912 Q_D(QPainterPath);
913 Q_ASSERT(!d->elements.isEmpty());
914 const QPainterPath::Element &elm = d->elements.at(elementCount()-1);
915 QPointF prev(elm.x, elm.y);
916
917 // Abort on empty curve as a stroker cannot handle this and the
918 // curve is irrelevant anyway.
919 if (prev == c && c == e)
920 return;
921
922 QPointF c1((prev.x() + 2*c.x()) / 3, (prev.y() + 2*c.y()) / 3);
923 QPointF c2((e.x() + 2*c.x()) / 3, (e.y() + 2*c.y()) / 3);
924 cubicTo(c1, c2, e);
925}
926
927/*!
928 \fn void QPainterPath::arcTo(qreal x, qreal y, qreal width, qreal
929 height, qreal startAngle, qreal sweepLength)
930
931 \overload
932
933 Creates an arc that occupies the rectangle QRectF(\a x, \a y, \a
934 width, \a height), beginning at the specified \a startAngle and
935 extending \a sweepLength degrees counter-clockwise.
936
937*/
938
939/*!
940 \fn void QPainterPath::arcTo(const QRectF &rectangle, qreal startAngle, qreal sweepLength)
941
942 Creates an arc that occupies the given \a rectangle, beginning at
943 the specified \a startAngle and extending \a sweepLength degrees
944 counter-clockwise.
945
946 Angles are specified in degrees. Clockwise arcs can be specified
947 using negative angles. If \a rectangle is not square, the angles are
948 eccentric angles and do not measure the direction from the center of
949 the rectangle, as described in \l{QPainterPath#Arcs and
950 Ellipses}{Arcs and Ellipses}.
951
952 Note that this function connects the starting point of the arc to
953 the current position if they are not already connected. After the
954 arc has been added, the current position is the last point in
955 arc. To draw a line back to the first point, use the
956 closeSubpath() function.
957
958 \table 100%
959 \row
960 \li \inlineimage qpainterpath-arcto.png
961 {Arc path with bounding rectangle and start angle}
962 \li
963 \snippet code/src_gui_painting_qpainterpath.cpp 2
964 \endtable
965
966 \sa arcMoveTo(), addEllipse(), QPainter::drawArc(), QPainter::drawPie(),
967 {QPainterPath#Composing a QPainterPath}{Composing a
968 QPainterPath}
969*/
970void QPainterPath::arcTo(const QRectF &rect, qreal startAngle, qreal sweepLength)
971{
972#ifdef QPP_DEBUG
973 printf("QPainterPath::arcTo() (%.2f, %.2f, %.2f, %.2f, angle=%.2f, sweep=%.2f\n",
974 rect.x(), rect.y(), rect.width(), rect.height(), startAngle, sweepLength);
975#endif
976
977 if (!hasValidCoords(rect) || !isValidCoord(startAngle) || !isValidCoord(sweepLength)) {
978#ifndef QT_NO_DEBUG
979 qWarning("QPainterPath::arcTo: Adding point with invalid coordinates, ignoring call");
980#endif
981 return;
982 }
983
984 if (rect.isNull())
985 return;
986
987 ensureData();
988 setDirty(true);
989
990 int point_count;
991 QPointF pts[15];
992 QPointF curve_start = qt_curves_for_arc(rect, startAngle, sweepLength, pts, &point_count);
993
994 lineTo(curve_start);
995 for (int i=0; i<point_count; i+=3) {
996 cubicTo(pts[i].x(), pts[i].y(),
997 pts[i+1].x(), pts[i+1].y(),
998 pts[i+2].x(), pts[i+2].y());
999 }
1000
1001}
1002
1003
1004/*!
1005 \fn void QPainterPath::arcMoveTo(qreal x, qreal y, qreal width, qreal height, qreal angle)
1006 \overload
1007 \since 4.2
1008
1009 Creates a move to that lies on the arc that occupies the
1010 QRectF(\a x, \a y, \a width, \a height) at \a angle.
1011*/
1012
1013
1014/*!
1015 \fn void QPainterPath::arcMoveTo(const QRectF &rectangle, qreal angle)
1016 \since 4.2
1017
1018 Creates a move to that lies on the arc that occupies the given \a
1019 rectangle at \a angle.
1020
1021 Angles are specified in degrees. Clockwise arcs can be specified
1022 using negative angles. If \a rectangle is not square, \a angle is an
1023 eccentric angle and does not measure the direction from the center of
1024 the rectangle, as described in \l{QPainterPath#Arcs and
1025 Ellipses}{Arcs and Ellipses}.
1026
1027 \sa moveTo(), arcTo(), {QPainterPath#Arcs and Ellipses}{Arcs and
1028 Ellipses}
1029*/
1030
1031void QPainterPath::arcMoveTo(const QRectF &rect, qreal angle)
1032{
1033 if (!hasValidCoords(rect) || !isValidCoord(angle)) {
1034#ifndef QT_NO_DEBUG
1035 qWarning("QPainterPath::arcMoveTo: Adding point with invalid coordinates, ignoring call");
1036#endif
1037 return;
1038 }
1039
1040 if (rect.isNull())
1041 return;
1042
1043 QPointF pt;
1044 qt_find_ellipse_coords(rect, angle, 0, &pt, nullptr);
1045 moveTo(pt);
1046}
1047
1048
1049
1050/*!
1051 \fn QPointF QPainterPath::currentPosition() const
1052
1053 Returns the current position of the path.
1054*/
1055QPointF QPainterPath::currentPosition() const
1056{
1057 return !d_ptr || d_func()->elements.isEmpty()
1058 ? QPointF()
1059 : QPointF(d_func()->elements.constLast().x, d_func()->elements.constLast().y);
1060}
1061
1062
1063/*!
1064 \fn void QPainterPath::addRect(qreal x, qreal y, qreal width, qreal height)
1065
1066 \overload
1067
1068 Adds a rectangle at position (\a{x}, \a{y}), with the given \a
1069 width and \a height, as a closed subpath.
1070*/
1071
1072/*!
1073 \fn void QPainterPath::addRect(const QRectF &rectangle)
1074
1075 Adds the given \a rectangle to this path as a closed subpath.
1076
1077 The \a rectangle is added as a clockwise set of lines. The painter
1078 path's current position after the \a rectangle has been added is
1079 at the top-left corner of the rectangle.
1080
1081 \table 100%
1082 \row
1083 \li \inlineimage qpainterpath-addrectangle.png
1084 {Rectangle with currentPosition marker}
1085 \li
1086 \snippet code/src_gui_painting_qpainterpath.cpp 3
1087 \endtable
1088
1089 \sa addRegion(), lineTo(), {QPainterPath#Composing a
1090 QPainterPath}{Composing a QPainterPath}
1091*/
1092void QPainterPath::addRect(const QRectF &r)
1093{
1094 if (!hasValidCoords(r)) {
1095#ifndef QT_NO_DEBUG
1096 qWarning("QPainterPath::addRect: Adding point with invalid coordinates, ignoring call");
1097#endif
1098 return;
1099 }
1100
1101 if (r.isNull())
1102 return;
1103
1104 ensureData();
1105 setDirty(true);
1106
1107 bool first = d_func()->elements.size() < 2;
1108
1109 moveTo(r.x(), r.y());
1110
1111 Element l1 = { r.x() + r.width(), r.y(), LineToElement };
1112 Element l2 = { r.x() + r.width(), r.y() + r.height(), LineToElement };
1113 Element l3 = { r.x(), r.y() + r.height(), LineToElement };
1114 Element l4 = { r.x(), r.y(), LineToElement };
1115
1116 d_func()->elements << l1 << l2 << l3 << l4;
1117 d_func()->require_moveTo = true;
1118 d_func()->convex = first;
1119}
1120
1121/*!
1122 Adds the given \a polygon to the path as an (unclosed) subpath.
1123
1124 Note that the current position after the polygon has been added,
1125 is the last point in \a polygon. To draw a line back to the first
1126 point, use the closeSubpath() function.
1127
1128 \table 100%
1129 \row
1130 \li \inlineimage qpainterpath-addpolygon.png
1131 {Polygon with labeled point coordinates}
1132 \li
1133 \snippet code/src_gui_painting_qpainterpath.cpp 4
1134 \endtable
1135
1136 \sa lineTo(), {QPainterPath#Composing a QPainterPath}{Composing
1137 a QPainterPath}
1138*/
1139void QPainterPath::addPolygon(const QPolygonF &polygon)
1140{
1141 if (polygon.isEmpty())
1142 return;
1143
1144 ensureData();
1145 setDirty(true);
1146
1147 moveTo(polygon.constFirst());
1148 for (int i=1; i<polygon.size(); ++i) {
1149 Element elm = { polygon.at(i).x(), polygon.at(i).y(), LineToElement };
1150 d_func()->elements << elm;
1151 }
1152}
1153
1154/*!
1155 \fn void QPainterPath::addEllipse(const QRectF &boundingRectangle)
1156
1157 Creates an ellipse within the specified \a boundingRectangle
1158 and adds it to the painter path as a closed subpath.
1159
1160 The ellipse is composed of a clockwise curve, starting and
1161 finishing at zero degrees (the 3 o'clock position). The curve is a
1162 cubic Bezier approximation of the ellipse, not an exact
1163 representation of it, as described in \l{QPainterPath#Arcs and
1164 Ellipses}{Arcs and Ellipses}.
1165
1166 \table 100%
1167 \row
1168 \li \inlineimage qpainterpath-addellipse.png
1169 {Ellipse with bounding rectangle}
1170 \li
1171 \snippet code/src_gui_painting_qpainterpath.cpp 5
1172 \endtable
1173
1174 \sa arcTo(), QPainter::drawEllipse(), {QPainterPath#Composing a
1175 QPainterPath}{Composing a QPainterPath}
1176*/
1177void QPainterPath::addEllipse(const QRectF &boundingRect)
1178{
1179 if (!hasValidCoords(boundingRect)) {
1180#ifndef QT_NO_DEBUG
1181 qWarning("QPainterPath::addEllipse: Adding point with invalid coordinates, ignoring call");
1182#endif
1183 return;
1184 }
1185
1186 if (boundingRect.isNull())
1187 return;
1188
1189 ensureData();
1190 setDirty(true);
1191
1192 bool first = d_func()->elements.size() < 2;
1193
1194 QPointF pts[12];
1195 int point_count;
1196 QPointF start = qt_curves_for_arc(boundingRect, 0, -360, pts, &point_count);
1197
1198 moveTo(start);
1199 cubicTo(pts[0], pts[1], pts[2]); // 0 -> 270
1200 cubicTo(pts[3], pts[4], pts[5]); // 270 -> 180
1201 cubicTo(pts[6], pts[7], pts[8]); // 180 -> 90
1202 cubicTo(pts[9], pts[10], pts[11]); // 90 - >0
1203 d_func()->require_moveTo = true;
1204
1205 d_func()->convex = first;
1206}
1207
1208/*!
1209 \fn void QPainterPath::addText(const QPointF &point, const QFont &font, const QString &text)
1210
1211 Adds the given \a text to this path as a set of closed subpaths
1212 created from the \a font supplied. The subpaths are positioned so
1213 that the left end of the text's baseline lies at the specified \a
1214 point.
1215
1216 Some fonts may yield overlapping subpaths and will require the
1217 \c Qt::WindingFill fill rule for correct rendering.
1218
1219 \table 100%
1220 \row
1221 \li \inlineimage qpainterpath-addtext.png {Qt text with baseline position}
1222 \li
1223 \snippet code/src_gui_painting_qpainterpath.cpp 6
1224 \endtable
1225
1226 \sa QPainter::drawText(), {QPainterPath#Composing a
1227 QPainterPath}{Composing a QPainterPath}, setFillRule()
1228*/
1229void QPainterPath::addText(const QPointF &point, const QFont &f, const QString &text)
1230{
1231 if (text.isEmpty())
1232 return;
1233
1234 ensureData();
1235 setDirty(true);
1236
1237 QTextLayout layout(text, f);
1238 layout.setCacheEnabled(true);
1239
1240 QTextOption opt = layout.textOption();
1241 opt.setUseDesignMetrics(true);
1242 layout.setTextOption(opt);
1243
1244 QTextEngine *eng = layout.engine();
1245 layout.beginLayout();
1246 QTextLine line = layout.createLine();
1247 Q_UNUSED(line);
1248 layout.endLayout();
1249 const QScriptLine &sl = eng->lines[0];
1250 if (!sl.length || !eng->layoutData)
1251 return;
1252
1253 int nItems = eng->layoutData->items.size();
1254
1255 qreal x(point.x());
1256 qreal y(point.y());
1257
1258 QVarLengthArray<int> visualOrder(nItems);
1259 QVarLengthArray<uchar> levels(nItems);
1260 for (int i = 0; i < nItems; ++i)
1261 levels[i] = eng->layoutData->items.at(i).analysis.bidiLevel;
1262 QTextEngine::bidiReorder(nItems, levels.data(), visualOrder.data());
1263
1264 for (int i = 0; i < nItems; ++i) {
1265 int item = visualOrder[i];
1266 const QScriptItem &si = eng->layoutData->items.at(item);
1267
1268 if (si.analysis.flags < QScriptAnalysis::TabOrObject) {
1269 QGlyphLayout glyphs = eng->shapedGlyphs(&si);
1270 QFontEngine *fe = eng->fontEngine(si);
1271 Q_ASSERT(fe);
1272 fe->addOutlineToPath(x, y, glyphs, this,
1273 si.analysis.bidiLevel % 2
1274 ? QTextItem::RenderFlags(QTextItem::RightToLeft)
1275 : QTextItem::RenderFlags{});
1276
1277 const qreal lw = fe->lineThickness().toReal();
1278 if (f.d->underline) {
1279 qreal pos = fe->underlinePosition().toReal();
1280 addRect(x, y + pos, si.width.toReal(), lw);
1281 }
1282 if (f.d->overline) {
1283 qreal pos = fe->ascent().toReal() + 1;
1284 addRect(x, y - pos, si.width.toReal(), lw);
1285 }
1286 if (f.d->strikeOut) {
1287 qreal pos = fe->ascent().toReal() / 3;
1288 addRect(x, y - pos, si.width.toReal(), lw);
1289 }
1290 }
1291 x += si.width.toReal();
1292 }
1293}
1294
1295/*!
1296 \fn void QPainterPath::addPath(const QPainterPath &path)
1297
1298 Adds the given \a path to \e this path as a closed subpath.
1299
1300 \sa connectPath(), {QPainterPath#Composing a
1301 QPainterPath}{Composing a QPainterPath}
1302*/
1303void QPainterPath::addPath(const QPainterPath &other)
1304{
1305 if (other.isEmpty())
1306 return;
1307
1308 ensureData();
1309 setDirty(true);
1310
1311 QPainterPathPrivate *d = d_func();
1312 // Remove last moveto so we don't get multiple moveto's
1313 if (d->elements.constLast().type == MoveToElement)
1314 d->elements.remove(d->elements.size()-1);
1315
1316 // Locate where our own current subpath will start after the other path is added.
1317 int cStart = d->elements.size() + other.d_func()->cStart;
1318 d->elements += other.d_func()->elements;
1319 d->cStart = cStart;
1320
1321 d->require_moveTo = other.d_func()->isClosed();
1322}
1323
1324
1325/*!
1326 \fn void QPainterPath::connectPath(const QPainterPath &path)
1327
1328 Connects the given \a path to \e this path by adding a line from the
1329 last element of this path to the first element of the given path.
1330
1331 \sa addPath(), {QPainterPath#Composing a QPainterPath}{Composing
1332 a QPainterPath}
1333*/
1334void QPainterPath::connectPath(const QPainterPath &other)
1335{
1336 if (other.isEmpty())
1337 return;
1338
1339 ensureData();
1340 setDirty(true);
1341
1342 QPainterPathPrivate *d = d_func();
1343 // Remove last moveto so we don't get multiple moveto's
1344 if (d->elements.constLast().type == MoveToElement)
1345 d->elements.remove(d->elements.size()-1);
1346
1347 // Locate where our own current subpath will start after the other path is added.
1348 int cStart = d->elements.size() + other.d_func()->cStart;
1349 int first = d->elements.size();
1350 d->elements += other.d_func()->elements;
1351
1352 if (first != 0)
1353 d->elements[first].type = LineToElement;
1354
1355 // avoid duplicate points
1356 if (first > 0 && QPointF(d->elements.at(first)) == QPointF(d->elements.at(first - 1))) {
1357 d->elements.remove(first--);
1358 --cStart;
1359 }
1360
1361 if (cStart != first)
1362 d->cStart = cStart;
1363}
1364
1365/*!
1366 Adds the given \a region to the path by adding each rectangle in
1367 the region as a separate closed subpath.
1368
1369 \sa addRect(), {QPainterPath#Composing a QPainterPath}{Composing
1370 a QPainterPath}
1371*/
1372void QPainterPath::addRegion(const QRegion &region)
1373{
1374 ensureData();
1375 setDirty(true);
1376
1377 for (const QRect &rect : region)
1378 addRect(rect);
1379}
1380
1381
1382/*!
1383 Returns the painter path's currently set fill rule.
1384
1385 \sa setFillRule()
1386*/
1387Qt::FillRule QPainterPath::fillRule() const
1388{
1389 return d_func() && d_func()->hasWindingFill ? Qt::WindingFill : Qt::OddEvenFill;
1390}
1391
1392/*!
1393 \fn void QPainterPath::setFillRule(Qt::FillRule fillRule)
1394
1395 Sets the fill rule of the painter path to the given \a
1396 fillRule. Qt provides two methods for filling paths:
1397
1398 \table
1399 \header
1400 \li Qt::OddEvenFill (default)
1401 \li Qt::WindingFill
1402 \row
1403 \li \inlineimage qt-fillrule-oddeven.png {Star with odd-even fill}
1404 \li \inlineimage qt-fillrule-winding.png {Star with winding fill}
1405 \endtable
1406
1407 \sa fillRule()
1408*/
1409void QPainterPath::setFillRule(Qt::FillRule fillRule)
1410{
1411 ensureData();
1412 const bool isWindingRequested = (fillRule == Qt::WindingFill);
1413 if (d_func()->hasWindingFill == isWindingRequested)
1414 return;
1415 setDirty(true);
1416
1417 d_func()->hasWindingFill = isWindingRequested;
1418}
1419
1420#define QT_BEZIER_A(bezier, coord) 3 * (-bezier.coord##1
1421 + 3*bezier.coord##2
1422 - 3*bezier.coord##3
1423 +bezier.coord##4)
1424
1425#define QT_BEZIER_B(bezier, coord) 6 * (bezier.coord##1
1426 - 2*bezier.coord##2
1427 + bezier.coord##3)
1428
1429#define QT_BEZIER_C(bezier, coord) 3 * (- bezier.coord##1
1430 + bezier.coord##2)
1431
1432#define QT_BEZIER_CHECK_T(bezier, t)
1433 if (t >= 0 && t <= 1) {
1434 QPointF p(b.pointAt(t));
1435 if (p.x() < minx) minx = p.x();
1436 else if (p.x() > maxx) maxx = p.x();
1437 if (p.y() < miny) miny = p.y();
1438 else if (p.y() > maxy) maxy = p.y();
1439 }
1440
1441
1442static QRectF qt_painterpath_bezier_extrema(const QBezier &b)
1443{
1444 qreal minx, miny, maxx, maxy;
1445
1446 // initialize with end points
1447 if (b.x1 < b.x4) {
1448 minx = b.x1;
1449 maxx = b.x4;
1450 } else {
1451 minx = b.x4;
1452 maxx = b.x1;
1453 }
1454 if (b.y1 < b.y4) {
1455 miny = b.y1;
1456 maxy = b.y4;
1457 } else {
1458 miny = b.y4;
1459 maxy = b.y1;
1460 }
1461
1462 // Update for the X extrema
1463 {
1464 qreal ax = QT_BEZIER_A(b, x);
1465 qreal bx = QT_BEZIER_B(b, x);
1466 qreal cx = QT_BEZIER_C(b, x);
1467 // specialcase quadratic curves to avoid div by zero
1468 if (qFuzzyIsNull(ax)) {
1469
1470 // linear curves are covered by initialization.
1471 if (!qFuzzyIsNull(bx)) {
1472 qreal t = -cx / bx;
1473 QT_BEZIER_CHECK_T(b, t);
1474 }
1475
1476 } else {
1477 const qreal tx = bx * bx - 4 * ax * cx;
1478
1479 if (tx >= 0) {
1480 qreal temp = qSqrt(tx);
1481 qreal rcp = 1 / (2 * ax);
1482 qreal t1 = (-bx + temp) * rcp;
1483 QT_BEZIER_CHECK_T(b, t1);
1484
1485 qreal t2 = (-bx - temp) * rcp;
1486 QT_BEZIER_CHECK_T(b, t2);
1487 }
1488 }
1489 }
1490
1491 // Update for the Y extrema
1492 {
1493 qreal ay = QT_BEZIER_A(b, y);
1494 qreal by = QT_BEZIER_B(b, y);
1495 qreal cy = QT_BEZIER_C(b, y);
1496
1497 // specialcase quadratic curves to avoid div by zero
1498 if (qFuzzyIsNull(ay)) {
1499
1500 // linear curves are covered by initialization.
1501 if (!qFuzzyIsNull(by)) {
1502 qreal t = -cy / by;
1503 QT_BEZIER_CHECK_T(b, t);
1504 }
1505
1506 } else {
1507 const qreal ty = by * by - 4 * ay * cy;
1508
1509 if (ty > 0) {
1510 qreal temp = qSqrt(ty);
1511 qreal rcp = 1 / (2 * ay);
1512 qreal t1 = (-by + temp) * rcp;
1513 QT_BEZIER_CHECK_T(b, t1);
1514
1515 qreal t2 = (-by - temp) * rcp;
1516 QT_BEZIER_CHECK_T(b, t2);
1517 }
1518 }
1519 }
1520 return QRectF(minx, miny, maxx - minx, maxy - miny);
1521}
1522
1523/*!
1524 Returns the bounding rectangle of this painter path as a rectangle with
1525 floating point precision.
1526
1527 \sa controlPointRect()
1528*/
1529QRectF QPainterPath::boundingRect() const
1530{
1531 if (!d_ptr)
1532 return QRectF();
1533 QPainterPathPrivate *d = d_func();
1534
1535 if (d->dirtyBounds)
1536 computeBoundingRect();
1537 return d->bounds;
1538}
1539
1540/*!
1541 Returns the rectangle containing all the points and control points
1542 in this path.
1543
1544 This function is significantly faster to compute than the exact
1545 boundingRect(), and the returned rectangle is always a superset of
1546 the rectangle returned by boundingRect().
1547
1548 \sa boundingRect()
1549*/
1550QRectF QPainterPath::controlPointRect() const
1551{
1552 if (!d_ptr)
1553 return QRectF();
1554 QPainterPathPrivate *d = d_func();
1555
1556 if (d->dirtyControlBounds)
1557 computeControlPointRect();
1558 return d->controlBounds;
1559}
1560
1561
1562/*!
1563 \fn bool QPainterPath::isEmpty() const
1564
1565 Returns \c true if either there are no elements in this path, or if the only
1566 element is a MoveToElement; otherwise returns \c false.
1567
1568 \sa elementCount()
1569*/
1570
1571bool QPainterPath::isEmpty() const
1572{
1573 return !d_ptr || (d_ptr->elements.size() == 1 && d_ptr->elements.constFirst().type == MoveToElement);
1574}
1575
1576/*!
1577 Creates and returns a reversed copy of the path.
1578
1579 It is the order of the elements that is reversed: If a
1580 QPainterPath is composed by calling the moveTo(), lineTo() and
1581 cubicTo() functions in the specified order, the reversed copy is
1582 composed by calling cubicTo(), lineTo() and moveTo().
1583*/
1584QPainterPath QPainterPath::toReversed() const
1585{
1586 Q_D(const QPainterPath);
1587 QPainterPath rev;
1588
1589 if (isEmpty()) {
1590 rev = *this;
1591 return rev;
1592 }
1593
1594 rev.moveTo(d->elements.at(d->elements.size()-1).x, d->elements.at(d->elements.size()-1).y);
1595
1596 for (int i=d->elements.size()-1; i>=1; --i) {
1597 const QPainterPath::Element &elm = d->elements.at(i);
1598 const QPainterPath::Element &prev = d->elements.at(i-1);
1599 switch (elm.type) {
1600 case LineToElement:
1601 rev.lineTo(prev.x, prev.y);
1602 break;
1603 case MoveToElement:
1604 rev.moveTo(prev.x, prev.y);
1605 break;
1606 case CurveToDataElement:
1607 {
1608 Q_ASSERT(i>=3);
1609 const QPainterPath::Element &cp1 = d->elements.at(i-2);
1610 const QPainterPath::Element &sp = d->elements.at(i-3);
1611 Q_ASSERT(prev.type == CurveToDataElement);
1612 Q_ASSERT(cp1.type == CurveToElement);
1613 rev.cubicTo(prev.x, prev.y, cp1.x, cp1.y, sp.x, sp.y);
1614 i -= 2;
1615 break;
1616 }
1617 default:
1618 Q_ASSERT(!"qt_reversed_path");
1619 break;
1620 }
1621 }
1622 //qt_debug_path(rev);
1623 return rev;
1624}
1625
1626/*!
1627 Converts the path into a list of polygons using the QTransform
1628 \a matrix, and returns the list.
1629
1630 This function creates one polygon for each subpath regardless of
1631 intersecting subpaths (i.e. overlapping bounding rectangles). To
1632 make sure that such overlapping subpaths are filled correctly, use
1633 the toFillPolygons() function instead.
1634
1635 \sa toFillPolygons(), toFillPolygon(), {QPainterPath#QPainterPath
1636 Conversion}{QPainterPath Conversion}
1637*/
1638QList<QPolygonF> QPainterPath::toSubpathPolygons(const QTransform &matrix) const
1639{
1640
1641 Q_D(const QPainterPath);
1642 QList<QPolygonF> flatCurves;
1643 if (isEmpty())
1644 return flatCurves;
1645
1646 QPolygonF current;
1647 for (int i=0; i<elementCount(); ++i) {
1648 const QPainterPath::Element &e = d->elements.at(i);
1649 switch (e.type) {
1650 case QPainterPath::MoveToElement:
1651 if (current.size() > 1)
1652 flatCurves += current;
1653 current.clear();
1654 current.reserve(16);
1655 current += QPointF(e.x, e.y) * matrix;
1656 break;
1657 case QPainterPath::LineToElement:
1658 current += QPointF(e.x, e.y) * matrix;
1659 break;
1660 case QPainterPath::CurveToElement: {
1661 Q_ASSERT(d->elements.at(i+1).type == QPainterPath::CurveToDataElement);
1662 Q_ASSERT(d->elements.at(i+2).type == QPainterPath::CurveToDataElement);
1663 QBezier bezier = QBezier::fromPoints(QPointF(d->elements.at(i-1).x, d->elements.at(i-1).y) * matrix,
1664 QPointF(e.x, e.y) * matrix,
1665 QPointF(d->elements.at(i+1).x, d->elements.at(i+1).y) * matrix,
1666 QPointF(d->elements.at(i+2).x, d->elements.at(i+2).y) * matrix);
1667 bezier.addToPolygon(&current);
1668 i+=2;
1669 break;
1670 }
1671 case QPainterPath::CurveToDataElement:
1672 Q_ASSERT(!"QPainterPath::toSubpathPolygons(), bad element type");
1673 break;
1674 }
1675 }
1676
1677 if (current.size()>1)
1678 flatCurves += current;
1679
1680 return flatCurves;
1681}
1682
1683/*!
1684 Converts the path into a list of polygons using the
1685 QTransform \a matrix, and returns the list.
1686
1687 The function differs from the toFillPolygon() function in that it
1688 creates several polygons. It is provided because it is usually
1689 faster to draw several small polygons than to draw one large
1690 polygon, even though the total number of points drawn is the same.
1691
1692 The toFillPolygons() function differs from the toSubpathPolygons()
1693 function in that it create only polygon for subpaths that have
1694 overlapping bounding rectangles.
1695
1696 Like the toFillPolygon() function, this function uses a rewinding
1697 technique to make sure that overlapping subpaths can be filled
1698 using the correct fill rule. Note that rewinding inserts addition
1699 lines in the polygons so the outline of the fill polygon does not
1700 match the outline of the path.
1701
1702 \sa toSubpathPolygons(), toFillPolygon(),
1703 {QPainterPath#QPainterPath Conversion}{QPainterPath Conversion}
1704*/
1705QList<QPolygonF> QPainterPath::toFillPolygons(const QTransform &matrix) const
1706{
1707
1708 QList<QPolygonF> polys;
1709
1710 QList<QPolygonF> subpaths = toSubpathPolygons(matrix);
1711 int count = subpaths.size();
1712
1713 if (count == 0)
1714 return polys;
1715
1716 QList<QRectF> bounds;
1717 bounds.reserve(count);
1718 for (int i=0; i<count; ++i)
1719 bounds += subpaths.at(i).boundingRect();
1720
1721#ifdef QPP_FILLPOLYGONS_DEBUG
1722 printf("QPainterPath::toFillPolygons, subpathCount=%d\n", count);
1723 for (int i=0; i<bounds.size(); ++i)
1724 qDebug() << " bounds" << i << bounds.at(i);
1725#endif
1726
1727 QList< QList<int> > isects;
1728 isects.resize(count);
1729
1730 // find all intersections
1731 for (int j=0; j<count; ++j) {
1732 if (subpaths.at(j).size() <= 2)
1733 continue;
1734 QRectF cbounds = bounds.at(j);
1735 for (int i=0; i<count; ++i) {
1736 if (cbounds.intersects(bounds.at(i))) {
1737 isects[j] << i;
1738 }
1739 }
1740 }
1741
1742#ifdef QPP_FILLPOLYGONS_DEBUG
1743 printf("Intersections before flattening:\n");
1744 for (int i = 0; i < count; ++i) {
1745 printf("%d: ", i);
1746 for (int j = 0; j < isects[i].size(); ++j) {
1747 printf("%d ", isects[i][j]);
1748 }
1749 printf("\n");
1750 }
1751#endif
1752
1753 // flatten the sets of intersections
1754 for (int i=0; i<count; ++i) {
1755 const QList<int> &current_isects = isects.at(i);
1756 for (int j=0; j<current_isects.size(); ++j) {
1757 int isect_j = current_isects.at(j);
1758 if (isect_j == i)
1759 continue;
1760 const QList<int> &isects_j = isects.at(isect_j);
1761 for (int k = 0, size = isects_j.size(); k < size; ++k) {
1762 int isect_k = isects_j.at(k);
1763 if (isect_k != i && !isects.at(i).contains(isect_k)) {
1764 isects[i] += isect_k;
1765 }
1766 }
1767 isects[isect_j].clear();
1768 }
1769 }
1770
1771#ifdef QPP_FILLPOLYGONS_DEBUG
1772 printf("Intersections after flattening:\n");
1773 for (int i = 0; i < count; ++i) {
1774 printf("%d: ", i);
1775 for (int j = 0; j < isects[i].size(); ++j) {
1776 printf("%d ", isects[i][j]);
1777 }
1778 printf("\n");
1779 }
1780#endif
1781
1782 // Join the intersected subpaths as rewinded polygons
1783 for (int i=0; i<count; ++i) {
1784 const QList<int> &subpath_list = isects.at(i);
1785 if (!subpath_list.isEmpty()) {
1786 QPolygonF buildUp;
1787 for (int j=0; j<subpath_list.size(); ++j) {
1788 const QPolygonF &subpath = subpaths.at(subpath_list.at(j));
1789 buildUp += subpath;
1790 if (!subpath.isClosed())
1791 buildUp += subpath.first();
1792 if (!buildUp.isClosed())
1793 buildUp += buildUp.constFirst();
1794 }
1795 polys += buildUp;
1796 }
1797 }
1798
1799 return polys;
1800}
1801
1802//same as qt_polygon_isect_line in qpolygon.cpp
1803static void qt_painterpath_isect_line(const QPointF &p1,
1804 const QPointF &p2,
1805 const QPointF &pos,
1806 int *winding)
1807{
1808 qreal x1 = p1.x();
1809 qreal y1 = p1.y();
1810 qreal x2 = p2.x();
1811 qreal y2 = p2.y();
1812 qreal y = pos.y();
1813
1814 int dir = 1;
1815
1816 if (QtPrivate::fuzzyCompare(y1, y2)) {
1817 // ignore horizontal lines according to scan conversion rule
1818 return;
1819 } else if (y2 < y1) {
1820 qreal x_tmp = x2; x2 = x1; x1 = x_tmp;
1821 qreal y_tmp = y2; y2 = y1; y1 = y_tmp;
1822 dir = -1;
1823 }
1824
1825 if (y >= y1 && y < y2) {
1826 qreal x = x1 + ((x2 - x1) / (y2 - y1)) * (y - y1);
1827
1828 // count up the winding number if we're
1829 if (x<=pos.x()) {
1830 (*winding) += dir;
1831 }
1832 }
1833}
1834
1835static void qt_painterpath_isect_curve(const QBezier &bezier, const QPointF &pt,
1836 int *winding, int depth = 0)
1837{
1838 qreal y = pt.y();
1839 qreal x = pt.x();
1840 QRectF bounds = bezier.bounds();
1841
1842 // potential intersection, divide and try again...
1843 // Please note that a sideeffect of the bottom exclusion is that
1844 // horizontal lines are dropped, but this is correct according to
1845 // scan conversion rules.
1846 if (y >= bounds.y() && y < bounds.y() + bounds.height()) {
1847
1848 // hit lower limit... This is a rough threshold, but its a
1849 // tradeoff between speed and precision.
1850 const qreal lower_bound = qreal(.001);
1851 if (depth == 32 || (bounds.width() < lower_bound && bounds.height() < lower_bound)) {
1852 // We make the assumption here that the curve starts to
1853 // approximate a line after while (i.e. that it doesn't
1854 // change direction drastically during its slope)
1855 if (bezier.pt1().x() <= x) {
1856 (*winding) += (bezier.pt4().y() > bezier.pt1().y() ? 1 : -1);
1857 }
1858 return;
1859 }
1860
1861 // split curve and try again...
1862 const auto halves = bezier.split();
1863 qt_painterpath_isect_curve(halves.first, pt, winding, depth + 1);
1864 qt_painterpath_isect_curve(halves.second, pt, winding, depth + 1);
1865 }
1866}
1867
1868/*!
1869 \fn bool QPainterPath::contains(const QPointF &point) const
1870
1871 Returns \c true if the given \a point is inside the path, otherwise
1872 returns \c false.
1873
1874 \sa intersects()
1875*/
1876bool QPainterPath::contains(const QPointF &pt) const
1877{
1878 if (isEmpty() || !controlPointRect().contains(pt))
1879 return false;
1880
1881 QPainterPathPrivate *d = d_func();
1882
1883 int winding_number = 0;
1884
1885 QPointF last_pt;
1886 QPointF last_start;
1887 for (int i=0; i<d->elements.size(); ++i) {
1888 const Element &e = d->elements.at(i);
1889
1890 switch (e.type) {
1891
1892 case MoveToElement:
1893 if (i > 0) // implicitly close all paths.
1894 qt_painterpath_isect_line(last_pt, last_start, pt, &winding_number);
1895 last_start = last_pt = e;
1896 break;
1897
1898 case LineToElement:
1899 qt_painterpath_isect_line(last_pt, e, pt, &winding_number);
1900 last_pt = e;
1901 break;
1902
1903 case CurveToElement:
1904 {
1905 const QPainterPath::Element &cp2 = d->elements.at(++i);
1906 const QPainterPath::Element &ep = d->elements.at(++i);
1907 qt_painterpath_isect_curve(QBezier::fromPoints(last_pt, e, cp2, ep),
1908 pt, &winding_number);
1909 last_pt = ep;
1910
1911 }
1912 break;
1913
1914 default:
1915 break;
1916 }
1917 }
1918
1919 // implicitly close last subpath
1920 if (last_pt != last_start)
1921 qt_painterpath_isect_line(last_pt, last_start, pt, &winding_number);
1922
1923 return (d->hasWindingFill
1924 ? (winding_number != 0)
1925 : ((winding_number % 2) != 0));
1926}
1927
1929
1930static bool qt_painterpath_isect_line_rect(qreal x1, qreal y1, qreal x2, qreal y2,
1931 const QRectF &rect)
1932{
1933 qreal left = rect.left();
1934 qreal right = rect.right();
1935 qreal top = rect.top();
1936 qreal bottom = rect.bottom();
1937
1938 // clip the lines, after cohen-sutherland, see e.g. http://www.nondot.org/~sabre/graphpro/line6.html
1939 int p1 = ((x1 < left) << Left)
1940 | ((x1 > right) << Right)
1941 | ((y1 < top) << Top)
1942 | ((y1 > bottom) << Bottom);
1943 int p2 = ((x2 < left) << Left)
1944 | ((x2 > right) << Right)
1945 | ((y2 < top) << Top)
1946 | ((y2 > bottom) << Bottom);
1947
1948 if (p1 & p2)
1949 // completely inside
1950 return false;
1951
1952 if (p1 | p2) {
1953 qreal dx = x2 - x1;
1954 qreal dy = y2 - y1;
1955
1956 // clip x coordinates
1957 if (x1 < left) {
1958 y1 += dy/dx * (left - x1);
1959 x1 = left;
1960 } else if (x1 > right) {
1961 y1 -= dy/dx * (x1 - right);
1962 x1 = right;
1963 }
1964 if (x2 < left) {
1965 y2 += dy/dx * (left - x2);
1966 x2 = left;
1967 } else if (x2 > right) {
1968 y2 -= dy/dx * (x2 - right);
1969 x2 = right;
1970 }
1971
1972 p1 = ((y1 < top) << Top)
1973 | ((y1 > bottom) << Bottom);
1974 p2 = ((y2 < top) << Top)
1975 | ((y2 > bottom) << Bottom);
1976
1977 if (p1 & p2)
1978 return false;
1979
1980 // clip y coordinates
1981 if (y1 < top) {
1982 x1 += dx/dy * (top - y1);
1983 y1 = top;
1984 } else if (y1 > bottom) {
1985 x1 -= dx/dy * (y1 - bottom);
1986 y1 = bottom;
1987 }
1988 if (y2 < top) {
1989 x2 += dx/dy * (top - y2);
1990 y2 = top;
1991 } else if (y2 > bottom) {
1992 x2 -= dx/dy * (y2 - bottom);
1993 y2 = bottom;
1994 }
1995
1996 p1 = ((x1 < left) << Left)
1997 | ((x1 > right) << Right);
1998 p2 = ((x2 < left) << Left)
1999 | ((x2 > right) << Right);
2000
2001 if (p1 & p2)
2002 return false;
2003
2004 return true;
2005 }
2006 return false;
2007}
2008
2009static bool qt_isect_curve_horizontal(const QBezier &bezier, qreal y, qreal x1, qreal x2, int depth = 0)
2010{
2011 QRectF bounds = bezier.bounds();
2012
2013 if (y >= bounds.top() && y < bounds.bottom()
2014 && bounds.right() >= x1 && bounds.left() < x2) {
2015 const qreal lower_bound = qreal(.01);
2016 if (depth == 32 || (bounds.width() < lower_bound && bounds.height() < lower_bound))
2017 return true;
2018
2019 const auto halves = bezier.split();
2020 if (qt_isect_curve_horizontal(halves.first, y, x1, x2, depth + 1)
2021 || qt_isect_curve_horizontal(halves.second, y, x1, x2, depth + 1))
2022 return true;
2023 }
2024 return false;
2025}
2026
2027static bool qt_isect_curve_vertical(const QBezier &bezier, qreal x, qreal y1, qreal y2, int depth = 0)
2028{
2029 QRectF bounds = bezier.bounds();
2030
2031 if (x >= bounds.left() && x < bounds.right()
2032 && bounds.bottom() >= y1 && bounds.top() < y2) {
2033 const qreal lower_bound = qreal(.01);
2034 if (depth == 32 || (bounds.width() < lower_bound && bounds.height() < lower_bound))
2035 return true;
2036
2037 const auto halves = bezier.split();
2038 if (qt_isect_curve_vertical(halves.first, x, y1, y2, depth + 1)
2039 || qt_isect_curve_vertical(halves.second, x, y1, y2, depth + 1))
2040 return true;
2041 }
2042 return false;
2043}
2044
2045static bool pointOnEdge(const QRectF &rect, const QPointF &point)
2046{
2047 if ((point.x() == rect.left() || point.x() == rect.right()) &&
2048 (point.y() >= rect.top() && point.y() <= rect.bottom()))
2049 return true;
2050 if ((point.y() == rect.top() || point.y() == rect.bottom()) &&
2051 (point.x() >= rect.left() && point.x() <= rect.right()))
2052 return true;
2053 return false;
2054}
2055
2056/*
2057 Returns \c true if any lines or curves cross the four edges in of rect
2058*/
2059static bool qt_painterpath_check_crossing(const QPainterPath *path, const QRectF &rect)
2060{
2061 QPointF last_pt;
2062 QPointF last_start;
2063 enum { OnRect, InsideRect, OutsideRect} edgeStatus = OnRect;
2064 for (int i=0; i<path->elementCount(); ++i) {
2065 const QPainterPath::Element &e = path->elementAt(i);
2066
2067 switch (e.type) {
2068
2069 case QPainterPath::MoveToElement:
2070 if (i > 0
2071 && qFuzzyCompare(last_pt, last_start)
2072 && qt_painterpath_isect_line_rect(last_pt.x(), last_pt.y(),
2073 last_start.x(), last_start.y(), rect))
2074 return true;
2075 last_start = last_pt = e;
2076 break;
2077
2078 case QPainterPath::LineToElement:
2079 if (qt_painterpath_isect_line_rect(last_pt.x(), last_pt.y(), e.x, e.y, rect))
2080 return true;
2081 last_pt = e;
2082 break;
2083
2084 case QPainterPath::CurveToElement:
2085 {
2086 QPointF cp2 = path->elementAt(++i);
2087 QPointF ep = path->elementAt(++i);
2088 QBezier bezier = QBezier::fromPoints(last_pt, e, cp2, ep);
2089 if (qt_isect_curve_horizontal(bezier, rect.top(), rect.left(), rect.right())
2090 || qt_isect_curve_horizontal(bezier, rect.bottom(), rect.left(), rect.right())
2091 || qt_isect_curve_vertical(bezier, rect.left(), rect.top(), rect.bottom())
2092 || qt_isect_curve_vertical(bezier, rect.right(), rect.top(), rect.bottom()))
2093 return true;
2094 last_pt = ep;
2095 }
2096 break;
2097
2098 default:
2099 break;
2100 }
2101 // Handle crossing the edges of the rect at the end-points of individual sub-paths.
2102 // A point on on the edge itself is considered neither inside nor outside for this purpose.
2103 if (!pointOnEdge(rect, last_pt)) {
2104 bool contained = rect.contains(last_pt);
2105 switch (edgeStatus) {
2106 case OutsideRect:
2107 if (contained)
2108 return true;
2109 break;
2110 case InsideRect:
2111 if (!contained)
2112 return true;
2113 break;
2114 case OnRect:
2115 edgeStatus = contained ? InsideRect : OutsideRect;
2116 break;
2117 }
2118 } else {
2119 if (last_pt == last_start)
2120 edgeStatus = OnRect;
2121 }
2122 }
2123
2124 // implicitly close last subpath
2125 if (last_pt != last_start
2126 && qt_painterpath_isect_line_rect(last_pt.x(), last_pt.y(),
2127 last_start.x(), last_start.y(), rect))
2128 return true;
2129
2130 return false;
2131}
2132
2133/*!
2134 \fn bool QPainterPath::intersects(const QRectF &rectangle) const
2135
2136 Returns \c true if any point in the given \a rectangle intersects the
2137 path; otherwise returns \c false.
2138
2139 There is an intersection if any of the lines making up the
2140 rectangle crosses a part of the path or if any part of the
2141 rectangle overlaps with any area enclosed by the path. This
2142 function respects the current fillRule to determine what is
2143 considered inside the path.
2144
2145 \sa contains()
2146*/
2147bool QPainterPath::intersects(const QRectF &rect) const
2148{
2149 if (elementCount() == 1 && rect.contains(elementAt(0)))
2150 return true;
2151
2152 if (isEmpty())
2153 return false;
2154
2155 QRectF cp = controlPointRect();
2156 QRectF rn = rect.normalized();
2157
2158 // QRectF::intersects returns false if one of the rects is a null rect
2159 // which would happen for a painter path consisting of a vertical or
2160 // horizontal line
2161 if (qMax(rn.left(), cp.left()) > qMin(rn.right(), cp.right())
2162 || qMax(rn.top(), cp.top()) > qMin(rn.bottom(), cp.bottom()))
2163 return false;
2164
2165 // If any path element cross the rect its bound to be an intersection
2166 if (qt_painterpath_check_crossing(this, rect))
2167 return true;
2168
2169 if (contains(rect.center()))
2170 return true;
2171
2172 Q_D(QPainterPath);
2173
2174 // Check if the rectangle surrounds any subpath...
2175 for (int i=0; i<d->elements.size(); ++i) {
2176 const Element &e = d->elements.at(i);
2177 if (e.type == QPainterPath::MoveToElement && rect.contains(e))
2178 return true;
2179 }
2180
2181 return false;
2182}
2183
2184/*!
2185 Translates all elements in the path by (\a{dx}, \a{dy}).
2186
2187 \since 4.6
2188 \sa translated()
2189*/
2190void QPainterPath::translate(qreal dx, qreal dy)
2191{
2192 if (!d_ptr || (dx == 0 && dy == 0))
2193 return;
2194
2195 int elementsLeft = d_ptr->elements.size();
2196 if (elementsLeft <= 0)
2197 return;
2198
2199 setDirty(true);
2200 QPainterPath::Element *element = d_func()->elements.data();
2201 Q_ASSERT(element);
2202 while (elementsLeft--) {
2203 element->x += dx;
2204 element->y += dy;
2205 ++element;
2206 }
2207}
2208
2209/*!
2210 \fn void QPainterPath::translate(const QPointF &offset)
2211 \overload
2212 \since 4.6
2213
2214 Translates all elements in the path by the given \a offset.
2215
2216 \sa translated()
2217*/
2218
2219/*!
2220 Returns a copy of the path that is translated by (\a{dx}, \a{dy}).
2221
2222 \since 4.6
2223 \sa translate()
2224*/
2225QPainterPath QPainterPath::translated(qreal dx, qreal dy) const
2226{
2227 QPainterPath copy(*this);
2228 copy.translate(dx, dy);
2229 return copy;
2230}
2231
2232/*!
2233 \fn QPainterPath QPainterPath::translated(const QPointF &offset) const;
2234 \overload
2235 \since 4.6
2236
2237 Returns a copy of the path that is translated by the given \a offset.
2238
2239 \sa translate()
2240*/
2241
2242/*!
2243 \fn bool QPainterPath::contains(const QRectF &rectangle) const
2244
2245 Returns \c true if the given \a rectangle is inside the path,
2246 otherwise returns \c false.
2247*/
2248bool QPainterPath::contains(const QRectF &rect) const
2249{
2250 Q_D(QPainterPath);
2251
2252 // the path is empty or the control point rect doesn't completely
2253 // cover the rectangle we abort stratight away.
2254 if (isEmpty() || !controlPointRect().contains(rect))
2255 return false;
2256
2257 // if there are intersections, chances are that the rect is not
2258 // contained, except if we have winding rule, in which case it
2259 // still might.
2260 if (qt_painterpath_check_crossing(this, rect)) {
2261 if (fillRule() == Qt::OddEvenFill) {
2262 return false;
2263 } else {
2264 // Do some wague sampling in the winding case. This is not
2265 // precise but it should mostly be good enough.
2266 if (!contains(rect.topLeft()) ||
2267 !contains(rect.topRight()) ||
2268 !contains(rect.bottomRight()) ||
2269 !contains(rect.bottomLeft()))
2270 return false;
2271 }
2272 }
2273
2274 // If there exists a point inside that is not part of the path its
2275 // because: rectangle lies completely outside path or a subpath
2276 // excludes parts of the rectangle. Both cases mean that the rect
2277 // is not contained
2278 if (!contains(rect.center()))
2279 return false;
2280
2281 // If there are any subpaths inside this rectangle we need to
2282 // check if they are still contained as a result of the fill
2283 // rule. This can only be the case for WindingFill though. For
2284 // OddEvenFill the rect will never be contained if it surrounds a
2285 // subpath. (the case where two subpaths are completely identical
2286 // can be argued but we choose to neglect it).
2287 for (int i=0; i<d->elements.size(); ++i) {
2288 const Element &e = d->elements.at(i);
2289 if (e.type == QPainterPath::MoveToElement && rect.contains(e)) {
2290 if (fillRule() == Qt::OddEvenFill)
2291 return false;
2292
2293 bool stop = false;
2294 for (; !stop && i<d->elements.size(); ++i) {
2295 const Element &el = d->elements.at(i);
2296 switch (el.type) {
2297 case MoveToElement:
2298 stop = true;
2299 break;
2300 case LineToElement:
2301 if (!contains(el))
2302 return false;
2303 break;
2304 case CurveToElement:
2305 if (!contains(d->elements.at(i+2)))
2306 return false;
2307 i += 2;
2308 break;
2309 default:
2310 break;
2311 }
2312 }
2313
2314 // compensate for the last ++i in the inner for
2315 --i;
2316 }
2317 }
2318
2319 return true;
2320}
2321
2322static inline bool epsilonCompare(const QPointF &a, const QPointF &b, const QSizeF &epsilon)
2323{
2324 return qAbs(a.x() - b.x()) <= epsilon.width()
2325 && qAbs(a.y() - b.y()) <= epsilon.height();
2326}
2327
2328/*!
2329 Returns \c true if this painterpath is equal to the given \a path.
2330
2331 Note that comparing paths may involve a per element comparison
2332 which can be slow for complex paths.
2333
2334 \sa operator!=()
2335*/
2336
2337bool QPainterPath::operator==(const QPainterPath &path) const
2338{
2339 QPainterPathPrivate *d = d_func();
2340 QPainterPathPrivate *other_d = path.d_func();
2341 if (other_d == d) {
2342 return true;
2343 } else if (!d || !other_d) {
2344 if (!other_d && isEmpty() && elementAt(0) == QPointF() && !d->hasWindingFill)
2345 return true;
2346 if (!d && path.isEmpty() && path.elementAt(0) == QPointF() && !other_d->hasWindingFill)
2347 return true;
2348 return false;
2349 }
2350 else if (d->hasWindingFill != other_d->hasWindingFill)
2351 return false;
2352 else if (d->elements.size() != other_d->elements.size())
2353 return false;
2354
2355 const qreal qt_epsilon = sizeof(qreal) == sizeof(double) ? 1e-12 : qreal(1e-5);
2356
2357 QSizeF epsilon = boundingRect().size();
2358 epsilon.rwidth() *= qt_epsilon;
2359 epsilon.rheight() *= qt_epsilon;
2360
2361 for (int i = 0; i < d->elements.size(); ++i)
2362 if (d->elements.at(i).type != other_d->elements.at(i).type
2363 || !epsilonCompare(d->elements.at(i), other_d->elements.at(i), epsilon))
2364 return false;
2365
2366 return true;
2367}
2368
2369/*!
2370 Returns \c true if this painter path differs from the given \a path.
2371
2372 Note that comparing paths may involve a per element comparison
2373 which can be slow for complex paths.
2374
2375 \sa operator==()
2376*/
2377
2378bool QPainterPath::operator!=(const QPainterPath &path) const
2379{
2380 return !(*this==path);
2381}
2382
2383/*!
2384 \since 4.5
2385
2386 Returns the intersection of this path and the \a other path.
2387
2388 \sa intersected(), operator&=(), united(), operator|()
2389*/
2390QPainterPath QPainterPath::operator&(const QPainterPath &other) const
2391{
2392 return intersected(other);
2393}
2394
2395/*!
2396 \since 4.5
2397
2398 Returns the union of this path and the \a other path.
2399
2400 \sa united(), operator|=(), intersected(), operator&()
2401*/
2402QPainterPath QPainterPath::operator|(const QPainterPath &other) const
2403{
2404 return united(other);
2405}
2406
2407/*!
2408 \since 4.5
2409
2410 Returns the union of this path and the \a other path. This function is equivalent
2411 to operator|().
2412
2413 \sa united(), operator+=(), operator-()
2414*/
2415QPainterPath QPainterPath::operator+(const QPainterPath &other) const
2416{
2417 return united(other);
2418}
2419
2420/*!
2421 \since 4.5
2422
2423 Subtracts the \a other path from a copy of this path, and returns the copy.
2424
2425 \sa subtracted(), operator-=(), operator+()
2426*/
2427QPainterPath QPainterPath::operator-(const QPainterPath &other) const
2428{
2429 return subtracted(other);
2430}
2431
2432/*!
2433 \since 4.5
2434
2435 Intersects this path with \a other and returns a reference to this path.
2436
2437 \sa intersected(), operator&(), operator|=()
2438*/
2439QPainterPath &QPainterPath::operator&=(const QPainterPath &other)
2440{
2441 return *this = (*this & other);
2442}
2443
2444/*!
2445 \since 4.5
2446
2447 Unites this path with \a other and returns a reference to this path.
2448
2449 \sa united(), operator|(), operator&=()
2450*/
2451QPainterPath &QPainterPath::operator|=(const QPainterPath &other)
2452{
2453 return *this = (*this | other);
2454}
2455
2456/*!
2457 \since 4.5
2458
2459 Unites this path with \a other, and returns a reference to this path. This
2460 is equivalent to operator|=().
2461
2462 \sa united(), operator+(), operator-=()
2463*/
2464QPainterPath &QPainterPath::operator+=(const QPainterPath &other)
2465{
2466 return *this = (*this + other);
2467}
2468
2469/*!
2470 \since 4.5
2471
2472 Subtracts \a other from this path, and returns a reference to this
2473 path.
2474
2475 \sa subtracted(), operator-(), operator+=()
2476*/
2477QPainterPath &QPainterPath::operator-=(const QPainterPath &other)
2478{
2479 return *this = (*this - other);
2480}
2481
2482#ifndef QT_NO_DATASTREAM
2483/*!
2484 \fn QDataStream &operator<<(QDataStream &stream, const QPainterPath &path)
2485 \relates QPainterPath
2486
2487 Writes the given painter \a path to the given \a stream, and
2488 returns a reference to the \a stream.
2489
2490 \sa {Serializing Qt Data Types}
2491*/
2492QDataStream &operator<<(QDataStream &s, const QPainterPath &p)
2493{
2494 if (p.isEmpty()) {
2495 s << 0;
2496 return s;
2497 }
2498
2499 s << p.elementCount();
2500 for (int i=0; i < p.d_func()->elements.size(); ++i) {
2501 const QPainterPath::Element &e = p.d_func()->elements.at(i);
2502 s << int(e.type);
2503 s << double(e.x) << double(e.y);
2504 }
2505 s << p.d_func()->cStart;
2506 s << int(p.fillRule());
2507 return s;
2508}
2509
2510/*!
2511 \fn QDataStream &operator>>(QDataStream &stream, QPainterPath &path)
2512 \relates QPainterPath
2513
2514 Reads a painter path from the given \a stream into the specified \a path,
2515 and returns a reference to the \a stream.
2516
2517 The data is validated: if it contains an element of unknown type or with
2518 non-finite coordinates, a curve without its two data elements, a path
2519 that does not start with a move, or an invalid fill rule, \a path is
2520 reset to an empty path and the stream's status is set to
2521 QDataStream::ReadCorruptData. Consecutive move elements are folded into
2522 the last one, as QPainterPath::moveTo() does.
2523
2524 \sa {Serializing Qt Data Types}
2525*/
2526QDataStream &operator>>(QDataStream &s, QPainterPath &p)
2527{
2528 bool errorDetected = false;
2529 int size;
2530 s >> size;
2531
2532 if (size == 0) {
2533 p = {};
2534 return s;
2535 }
2536 if (size < 0) {
2537 p = {};
2538 s.setStatus(QDataStream::ReadCorruptData);
2539 return s;
2540 }
2541
2542 p.ensureData(); // in case if p.d_func() == 0
2543 p.setDirty(true);
2544 QList<QPainterPath::Element> &elements = p.d_func()->elements;
2545 elements.clear();
2546 bool folded = false;
2547 int curveDataPending = 0; // CurveToData elements still owed by the last CurveTo
2548 for (int i=0; i<size; ++i) {
2549 int type;
2550 double x, y;
2551 s >> type;
2552 s >> x;
2553 s >> y;
2554 if (type < QPainterPath::MoveToElement || type > QPainterPath::CurveToDataElement) {
2555#ifndef QT_NO_DEBUG
2556 qWarning("QDataStream::operator>>: Invalid QPainterPath element type read, skipping it");
2557#endif
2558 errorDetected = true;
2559 continue;
2560 }
2561 if (!isValidCoord(qreal(x)) || !isValidCoord(qreal(y))) {
2562#ifndef QT_NO_DEBUG
2563 qWarning("QDataStream::operator>>: Invalid QPainterPath coordinates read, skipping it");
2564#endif
2565 errorDetected = true;
2566 continue;
2567 }
2568 QPainterPath::Element elm = { qreal(x), qreal(y), QPainterPath::ElementType(type) };
2569 // Enforce the structure that the QPainterPath API guarantees: the path starts
2570 // with a MoveTo, a CurveTo is followed by exactly two CurveToData elements, and
2571 // a MoveTo directly after a MoveTo replaces it (see QPainterPath::moveTo())
2572 if (curveDataPending > 0) {
2573 if (elm.type != QPainterPath::CurveToDataElement) {
2574 errorDetected = true;
2575 continue;
2576 }
2577 --curveDataPending;
2578 } else if (elm.type == QPainterPath::CurveToDataElement
2579 || (elements.isEmpty() && elm.type != QPainterPath::MoveToElement)) {
2580 errorDetected = true;
2581 continue;
2582 } else if (elm.type == QPainterPath::CurveToElement) {
2583 curveDataPending = 2;
2584 } else if (elm.type == QPainterPath::MoveToElement && !elements.isEmpty()
2585 && elements.last().type == QPainterPath::MoveToElement) {
2586 elements.last() = elm;
2587 folded = true;
2588 continue;
2589 }
2590 elements.append(elm);
2591 }
2592 if (curveDataPending > 0)
2593 errorDetected = true;
2594 int cStart;
2595 s >> cStart;
2596 int fillRule;
2597 s >> fillRule;
2598 if (fillRule != Qt::OddEvenFill && fillRule != Qt::WindingFill)
2599 errorDetected = true;
2600 if (errorDetected || elements.isEmpty()) {
2601#ifndef QT_NO_DEBUG
2602 qWarning("QDataStream::operator>>: Invalid QPainterPath read, resetting it");
2603#endif
2604 p = QPainterPath(); // Better than to return path with possibly corrupt datastructure, which would likely cause crash
2605 s.setStatus(QDataStream::ReadCorruptData);
2606 return s;
2607 }
2608 p.d_func()->hasWindingFill = (Qt::FillRule(fillRule) == Qt::WindingFill);
2609 // cStart is the index of the MoveTo starting the current subpath; folding
2610 // shifts indices, and an out-of-range value would be dereferenced by
2611 // closeSubpath(), so recompute it unless the streamed one is consistent
2612 if (folded || cStart < 0 || cStart >= elements.size()
2613 || elements.at(cStart).type != QPainterPath::MoveToElement) {
2614 cStart = elements.size() - 1;
2615 while (elements.at(cStart).type != QPainterPath::MoveToElement)
2616 --cStart;
2617 }
2618 p.d_func()->cStart = cStart;
2619 return s;
2620}
2621#endif // QT_NO_DATASTREAM
2622
2623
2624/*******************************************************************************
2625 * class QPainterPathStroker
2626 */
2627
2628void qt_path_stroke_move_to(qfixed x, qfixed y, void *data)
2629{
2630 ((QPainterPath *) data)->moveTo(qt_fixed_to_real(x), qt_fixed_to_real(y));
2631}
2632
2633void qt_path_stroke_line_to(qfixed x, qfixed y, void *data)
2634{
2635 ((QPainterPath *) data)->lineTo(qt_fixed_to_real(x), qt_fixed_to_real(y));
2636}
2637
2638void qt_path_stroke_cubic_to(qfixed c1x, qfixed c1y,
2639 qfixed c2x, qfixed c2y,
2640 qfixed ex, qfixed ey,
2641 void *data)
2642{
2643 ((QPainterPath *) data)->cubicTo(qt_fixed_to_real(c1x), qt_fixed_to_real(c1y),
2644 qt_fixed_to_real(c2x), qt_fixed_to_real(c2y),
2645 qt_fixed_to_real(ex), qt_fixed_to_real(ey));
2646}
2647
2648/*!
2649 \since 4.1
2650 \class QPainterPathStroker
2651 \ingroup painting
2652 \inmodule QtGui
2653
2654 \brief The QPainterPathStroker class is used to generate fillable
2655 outlines for a given painter path.
2656
2657 By calling the createStroke() function, passing a given
2658 QPainterPath as argument, a new painter path representing the
2659 outline of the given path is created. The newly created painter
2660 path can then be filled to draw the original painter path's
2661 outline.
2662
2663 You can control the various design aspects (width, cap styles,
2664 join styles and dash pattern) of the outlining using the following
2665 functions:
2666
2667 \list
2668 \li setWidth()
2669 \li setCapStyle()
2670 \li setJoinStyle()
2671 \li setDashPattern()
2672 \endlist
2673
2674 The setDashPattern() function accepts both a Qt::PenStyle object
2675 and a list representation of the pattern as argument.
2676
2677 In addition you can specify a curve's threshold, controlling the
2678 granularity with which a curve is drawn, using the
2679 setCurveThreshold() function. The default threshold is a well
2680 adjusted value (0.25), and normally you should not need to modify
2681 it. However, you can make the curve's appearance smoother by
2682 decreasing its value.
2683
2684 You can also control the miter limit for the generated outline
2685 using the setMiterLimit() function. The miter limit describes how
2686 far from each join the miter join can extend. The limit is
2687 specified in the units of width so the pixelwise miter limit will
2688 be \c {miterlimit * width}. This value is only used if the join
2689 style is Qt::MiterJoin.
2690
2691 The painter path generated by the createStroke() function should
2692 only be used for outlining the given painter path. Otherwise it
2693 may cause unexpected behavior. Generated outlines also require the
2694 Qt::WindingFill rule which is set by default.
2695
2696 \sa QPen, QBrush
2697*/
2698
2700 : dashOffset(0)
2701{
2702 stroker.setMoveToHook(qt_path_stroke_move_to);
2703 stroker.setLineToHook(qt_path_stroke_line_to);
2704 stroker.setCubicToHook(qt_path_stroke_cubic_to);
2705}
2706
2707/*!
2708 Creates a new stroker.
2709 */
2710QPainterPathStroker::QPainterPathStroker()
2711 : d_ptr(new QPainterPathStrokerPrivate)
2712{
2713}
2714
2715/*!
2716 Creates a new stroker based on \a pen.
2717
2718 \since 5.3
2719 */
2720QPainterPathStroker::QPainterPathStroker(const QPen &pen)
2721 : d_ptr(new QPainterPathStrokerPrivate)
2722{
2723 setWidth(pen.widthF());
2724 setCapStyle(pen.capStyle());
2725 setJoinStyle(pen.joinStyle());
2726 setMiterLimit(pen.miterLimit());
2727 setDashOffset(pen.dashOffset());
2728
2729 if (pen.style() == Qt::CustomDashLine)
2730 setDashPattern(pen.dashPattern());
2731 else
2732 setDashPattern(pen.style());
2733}
2734
2735/*!
2736 Destroys the stroker.
2737*/
2738QPainterPathStroker::~QPainterPathStroker()
2739{
2740}
2741
2742
2743/*!
2744 Generates a new path that is a fillable area representing the
2745 outline of the given \a path.
2746
2747 The various design aspects of the outline are based on the
2748 stroker's properties: width(), capStyle(), joinStyle(),
2749 dashPattern(), curveThreshold() and miterLimit().
2750
2751 The generated path should only be used for outlining the given
2752 painter path. Otherwise it may cause unexpected
2753 behavior. Generated outlines also require the Qt::WindingFill rule
2754 which is set by default.
2755*/
2756QPainterPath QPainterPathStroker::createStroke(const QPainterPath &path) const
2757{
2758 QPainterPathStrokerPrivate *d = const_cast<QPainterPathStrokerPrivate *>(d_func());
2759 QPainterPath stroke;
2760 if (path.isEmpty())
2761 return path;
2762 if (d->dashPattern.isEmpty()) {
2763 d->stroker.strokePath(path, &stroke, QTransform());
2764 } else {
2765 QDashStroker dashStroker(&d->stroker);
2766 dashStroker.setDashPattern(d->dashPattern);
2767 dashStroker.setDashOffset(d->dashOffset);
2768 dashStroker.setClipRect(d->stroker.clipRect());
2769 if (d->stroker.curveThresholdExplicitlySet())
2770 dashStroker.setCurveThreshold(d->stroker.curveThreshold());
2771 dashStroker.strokePath(path, &stroke, QTransform());
2772 }
2773 stroke.setFillRule(Qt::WindingFill);
2774 return stroke;
2775}
2776
2777/*!
2778 Sets the width of the generated outline painter path to \a width.
2779
2780 The generated outlines will extend approximately 50% of \a width
2781 to each side of the given input path's original outline.
2782*/
2783void QPainterPathStroker::setWidth(qreal width)
2784{
2785 Q_D(QPainterPathStroker);
2786 if (width <= 0)
2787 width = 1;
2788 d->stroker.setStrokeWidth(qt_real_to_fixed(width));
2789}
2790
2791/*!
2792 Returns the width of the generated outlines.
2793*/
2794qreal QPainterPathStroker::width() const
2795{
2796 return qt_fixed_to_real(d_func()->stroker.strokeWidth());
2797}
2798
2799
2800/*!
2801 Sets the cap style of the generated outlines to \a style. If a
2802 dash pattern is set, each segment of the pattern is subject to the
2803 cap \a style.
2804*/
2805void QPainterPathStroker::setCapStyle(Qt::PenCapStyle style)
2806{
2807 d_func()->stroker.setCapStyle(style);
2808}
2809
2810
2811/*!
2812 Returns the cap style of the generated outlines.
2813*/
2814Qt::PenCapStyle QPainterPathStroker::capStyle() const
2815{
2816 return d_func()->stroker.capStyle();
2817}
2818
2819/*!
2820 Sets the join style of the generated outlines to \a style.
2821*/
2822void QPainterPathStroker::setJoinStyle(Qt::PenJoinStyle style)
2823{
2824 d_func()->stroker.setJoinStyle(style);
2825}
2826
2827/*!
2828 Returns the join style of the generated outlines.
2829*/
2830Qt::PenJoinStyle QPainterPathStroker::joinStyle() const
2831{
2832 return d_func()->stroker.joinStyle();
2833}
2834
2835/*!
2836 Sets the miter limit of the generated outlines to \a limit.
2837
2838 The miter limit describes how far from each join the miter join
2839 can extend. The limit is specified in units of the currently set
2840 width. So the pixelwise miter limit will be \c { miterlimit *
2841 width}.
2842
2843 This value is only used if the join style is Qt::MiterJoin.
2844*/
2845void QPainterPathStroker::setMiterLimit(qreal limit)
2846{
2847 d_func()->stroker.setMiterLimit(qt_real_to_fixed(limit));
2848}
2849
2850/*!
2851 Returns the miter limit for the generated outlines.
2852*/
2853qreal QPainterPathStroker::miterLimit() const
2854{
2855 return qt_fixed_to_real(d_func()->stroker.miterLimit());
2856}
2857
2858
2859/*!
2860 Specifies the curve flattening \a threshold, controlling the
2861 granularity with which the generated outlines' curve is drawn.
2862
2863 The default threshold is a well adjusted value (0.25), and
2864 normally you should not need to modify it. However, you can make
2865 the curve's appearance smoother by decreasing its value.
2866*/
2867void QPainterPathStroker::setCurveThreshold(qreal threshold)
2868{
2869 d_func()->stroker.setCurveThreshold(qt_real_to_fixed(threshold));
2870}
2871
2872/*!
2873 Returns the curve flattening threshold for the generated
2874 outlines.
2875*/
2876qreal QPainterPathStroker::curveThreshold() const
2877{
2878 return qt_fixed_to_real(d_func()->stroker.curveThreshold());
2879}
2880
2881/*!
2882 Sets the dash pattern for the generated outlines to \a style.
2883*/
2884void QPainterPathStroker::setDashPattern(Qt::PenStyle style)
2885{
2886 d_func()->dashPattern = QDashStroker::patternForStyle(style);
2887}
2888
2889/*!
2890 \overload
2891
2892 Sets the dash pattern for the generated outlines to \a
2893 dashPattern. This function makes it possible to specify custom
2894 dash patterns.
2895
2896 Each element in the list contains the lengths of the dashes and spaces
2897 in the stroke, beginning with the first dash in the first element, the
2898 first space in the second element, and alternating between dashes and
2899 spaces for each following pair of elements.
2900
2901 The list can contain an odd number of elements, in which case the last
2902 element will be extended by the length of the first element when the
2903 pattern repeats.
2904*/
2905void QPainterPathStroker::setDashPattern(const QList<qreal> &dashPattern)
2906{
2907 d_func()->dashPattern.clear();
2908 for (int i=0; i<dashPattern.size(); ++i)
2909 d_func()->dashPattern << qt_real_to_fixed(dashPattern.at(i));
2910}
2911
2912/*!
2913 Returns the dash pattern for the generated outlines.
2914*/
2915QList<qreal> QPainterPathStroker::dashPattern() const
2916{
2917 return d_func()->dashPattern;
2918}
2919
2920/*!
2921 Returns the dash offset for the generated outlines.
2922 */
2923qreal QPainterPathStroker::dashOffset() const
2924{
2925 return d_func()->dashOffset;
2926}
2927
2928/*!
2929 Sets the dash offset for the generated outlines to \a offset.
2930
2931 See the documentation for QPen::setDashOffset() for a description of the
2932 dash offset.
2933 */
2934void QPainterPathStroker::setDashOffset(qreal offset)
2935{
2936 d_func()->dashOffset = offset;
2937}
2938
2939/*!
2940 Converts the path into a polygon using the QTransform
2941 \a matrix, and returns the polygon.
2942
2943 The polygon is created by first converting all subpaths to
2944 polygons, then using a rewinding technique to make sure that
2945 overlapping subpaths can be filled using the correct fill rule.
2946
2947 Note that rewinding inserts addition lines in the polygon so
2948 the outline of the fill polygon does not match the outline of
2949 the path.
2950
2951 \sa toSubpathPolygons(), toFillPolygons(),
2952 {QPainterPath#QPainterPath Conversion}{QPainterPath Conversion}
2953*/
2954QPolygonF QPainterPath::toFillPolygon(const QTransform &matrix) const
2955{
2956 const QList<QPolygonF> flats = toSubpathPolygons(matrix);
2957 QPolygonF polygon;
2958 if (flats.isEmpty())
2959 return polygon;
2960 QPointF first = flats.first().first();
2961 for (int i=0; i<flats.size(); ++i) {
2962 polygon += flats.at(i);
2963 if (!flats.at(i).isClosed())
2964 polygon += flats.at(i).first();
2965 if (i > 0)
2966 polygon += first;
2967 }
2968 return polygon;
2969}
2970
2971/*!
2972 Returns true if caching is enabled; otherwise returns false.
2973
2974 \since 6.10
2975 \sa setCachingEnabled()
2976*/
2977bool QPainterPath::isCachingEnabled() const
2978{
2979 Q_D(QPainterPath);
2980 return d && d->cacheEnabled;
2981}
2982
2983/*!
2984 Enables or disables length caching according to the value of \a enabled.
2985
2986 Enabling caching speeds up repeated calls to the member functions involving path length
2987 and percentage values, such as length(), percentAtLength(), pointAtPercent() etc., at the cost
2988 of some extra memory usage for storage of intermediate calculations. By default it is disabled.
2989
2990 Disabling caching will release any allocated cache memory.
2991
2992 \since 6.10
2993 \sa isCachingEnabled(), length(), percentAtLength(), pointAtPercent(), trimmed()
2994*/
2995void QPainterPath::setCachingEnabled(bool enabled)
2996{
2997 ensureData();
2998 if (d_func()->cacheEnabled == enabled)
2999 return;
3000 setDirty(true);
3001 QPainterPathPrivate *d = d_func();
3002 d->cacheEnabled = enabled;
3003 if (!enabled) {
3004 d->m_runLengths.clear();
3005 d->m_runLengths.squeeze();
3006 }
3007}
3008
3009//derivative of the equation
3010static inline qreal slopeAt(qreal t, qreal a, qreal b, qreal c, qreal d)
3011{
3012 return 3*t*t*(d - 3*c + 3*b - a) + 6*t*(c - 2*b + a) + 3*(b - a);
3013}
3014
3015/*!
3016 Returns the length of the current path.
3017*/
3018qreal QPainterPath::length() const
3019{
3020 Q_D(QPainterPath);
3021 if (isEmpty())
3022 return 0;
3023 if (d->cacheEnabled) {
3024 if (d->dirtyRunLengths)
3025 d->computeRunLengths();
3026 return d->m_runLengths.last();
3027 }
3028
3029 qreal len = 0;
3030 for (int i=1; i<d->elements.size(); ++i) {
3031 const Element &e = d->elements.at(i);
3032
3033 switch (e.type) {
3034 case MoveToElement:
3035 break;
3036 case LineToElement:
3037 {
3038 len += QLineF(d->elements.at(i-1), e).length();
3039 break;
3040 }
3041 case CurveToElement:
3042 {
3043 QBezier b = QBezier::fromPoints(d->elements.at(i-1),
3044 e,
3045 d->elements.at(i+1),
3046 d->elements.at(i+2));
3047 len += b.length();
3048 i += 2;
3049 break;
3050 }
3051 default:
3052 break;
3053 }
3054 }
3055 return len;
3056}
3057
3058/*!
3059 Returns percentage of the whole path at the specified length \a len.
3060
3061 Note that similarly to other percent methods, the percentage measurement
3062 is not linear with regards to the length, if curves are present
3063 in the path. When curves are present the percentage argument is mapped
3064 to the t parameter of the Bezier equations.
3065*/
3066qreal QPainterPath::percentAtLength(qreal len) const
3067{
3068 Q_D(QPainterPath);
3069 if (isEmpty() || len <= 0)
3070 return 0;
3071
3072 qreal totalLength = length();
3073 if (len > totalLength)
3074 return 1;
3075
3076 Q_ASSERT(totalLength != 0);
3077
3078 if (d->cacheEnabled) {
3079 const int ei = qMax(d->elementAtT(len / totalLength), 1); // Skip initial MoveTo
3080 qreal res = 0;
3081 const QPainterPath::Element &e = d->elements[ei];
3082 switch (e.type) {
3083 case QPainterPath::LineToElement:
3084 res = len / totalLength;
3085 break;
3086 case CurveToElement:
3087 {
3088 QBezier b = QBezier::fromPoints(d->elements.at(ei-1),
3089 e,
3090 d->elements.at(ei+1),
3091 d->elements.at(ei+2));
3092 qreal prevLen = d->m_runLengths[ei - 1];
3093 qreal blen = d->m_runLengths[ei] - prevLen;
3094 qreal elemRes = b.tAtLength(len - prevLen);
3095 res = (elemRes * blen + prevLen) / totalLength;
3096 break;
3097 }
3098 default:
3099 Q_UNREACHABLE();
3100 }
3101 return res;
3102 }
3103
3104 qreal curLen = 0;
3105 for (int i=1; i<d->elements.size(); ++i) {
3106 const Element &e = d->elements.at(i);
3107
3108 switch (e.type) {
3109 case MoveToElement:
3110 break;
3111 case LineToElement:
3112 {
3113 QLineF line(d->elements.at(i-1), e);
3114 qreal llen = line.length();
3115 curLen += llen;
3116 if (curLen >= len) {
3117 return len/totalLength ;
3118 }
3119
3120 break;
3121 }
3122 case CurveToElement:
3123 {
3124 QBezier b = QBezier::fromPoints(d->elements.at(i-1),
3125 e,
3126 d->elements.at(i+1),
3127 d->elements.at(i+2));
3128 qreal blen = b.length();
3129 qreal prevLen = curLen;
3130 curLen += blen;
3131
3132 if (curLen >= len) {
3133 qreal res = b.tAtLength(len - prevLen);
3134 return (res * blen + prevLen)/totalLength;
3135 }
3136
3137 i += 2;
3138 break;
3139 }
3140 default:
3141 break;
3142 }
3143 }
3144
3145 return 0;
3146}
3147
3148static inline QBezier uncached_bezierAtT(const QPainterPath &path, qreal t, qreal *startingLength,
3149 qreal *bezierLength)
3150{
3151 *startingLength = 0;
3152 if (t > 1)
3153 return QBezier();
3154
3155 qreal curLen = 0;
3156 qreal totalLength = path.length();
3157
3158 const int lastElement = path.elementCount() - 1;
3159 for (int i=0; i <= lastElement; ++i) {
3160 const QPainterPath::Element &e = path.elementAt(i);
3161
3162 switch (e.type) {
3163 case QPainterPath::MoveToElement:
3164 break;
3165 case QPainterPath::LineToElement:
3166 {
3167 QLineF line(path.elementAt(i-1), e);
3168 qreal llen = line.length();
3169 curLen += llen;
3170 if (i == lastElement || curLen/totalLength >= t) {
3171 *bezierLength = llen;
3172 QPointF a = path.elementAt(i-1);
3173 QPointF delta = e - a;
3174 return QBezier::fromPoints(a, a + delta / 3, a + 2 * delta / 3, e);
3175 }
3176 break;
3177 }
3178 case QPainterPath::CurveToElement:
3179 {
3180 QBezier b = QBezier::fromPoints(path.elementAt(i-1),
3181 e,
3182 path.elementAt(i+1),
3183 path.elementAt(i+2));
3184 qreal blen = b.length();
3185 curLen += blen;
3186
3187 if (i + 2 == lastElement || curLen/totalLength >= t) {
3188 *bezierLength = blen;
3189 return b;
3190 }
3191
3192 i += 2;
3193 break;
3194 }
3195 default:
3196 break;
3197 }
3198 *startingLength = curLen;
3199 }
3200 return QBezier();
3201}
3202
3203QBezier QPainterPathPrivate::bezierAtT(const QPainterPath &path, qreal t, qreal *startingLength,
3204 qreal *bezierLength) const
3205{
3206 Q_ASSERT(t >= 0 && t <= 1);
3207 QPainterPathPrivate *d = path.d_func();
3208 if (!path.isEmpty() && d->cacheEnabled) {
3209 const int ei = qMax(d->elementAtT(t), 1); // Avoid the initial MoveTo element
3210 const qreal prevRunLength = d->m_runLengths[ei - 1];
3211 *startingLength = prevRunLength;
3212 *bezierLength = d->m_runLengths[ei] - prevRunLength;
3213 const QPointF prev = d->elements[ei - 1];
3214 const QPainterPath::Element &e = d->elements[ei];
3215 switch (e.type) {
3216 case QPainterPath::LineToElement:
3217 {
3218 QPointF delta = (e - prev) / 3;
3219 return QBezier::fromPoints(prev, prev + delta, prev + 2 * delta, e);
3220 }
3221 case QPainterPath::CurveToElement:
3222 return QBezier::fromPoints(prev, e, elements[ei + 1], elements[ei + 2]);
3223 break;
3224 default:
3225 Q_UNREACHABLE();
3226 }
3227 }
3228
3229 return uncached_bezierAtT(path, t, startingLength, bezierLength);
3230}
3231
3232/*!
3233 Returns the point at at the percentage \a t of the current path.
3234 The argument \a t has to be between 0 and 1.
3235
3236 Note that similarly to other percent methods, the percentage measurement
3237 is not linear with regards to the length, if curves are present
3238 in the path. When curves are present the percentage argument is mapped
3239 to the t parameter of the Bezier equations.
3240*/
3241QPointF QPainterPath::pointAtPercent(qreal t) const
3242{
3243 if (t < 0 || t > 1) {
3244 qWarning("QPainterPath::pointAtPercent accepts only values between 0 and 1");
3245 return QPointF();
3246 }
3247
3248 if (!d_ptr || d_ptr->elements.size() == 0)
3249 return QPointF();
3250
3251 if (d_ptr->elements.size() == 1)
3252 return d_ptr->elements.at(0);
3253
3254 qreal totalLength = length();
3255 qreal curLen = 0;
3256 qreal bezierLen = 0;
3257 QBezier b = d_ptr->bezierAtT(*this, t, &curLen, &bezierLen);
3258 Q_ASSERT(bezierLen != 0);
3259 qreal realT = (totalLength * t - curLen) / bezierLen;
3260
3261 return b.pointAt(qBound(qreal(0), realT, qreal(1)));
3262}
3263
3264/*!
3265 Returns the angle of the path tangent at the percentage \a t.
3266 The argument \a t has to be between 0 and 1.
3267
3268 Positive values for the angles mean counter-clockwise while negative values
3269 mean the clockwise direction. Zero degrees is at the 3 o'clock position.
3270
3271 Note that similarly to the other percent methods, the percentage measurement
3272 is not linear with regards to the length if curves are present
3273 in the path. When curves are present the percentage argument is mapped
3274 to the t parameter of the Bezier equations.
3275*/
3276qreal QPainterPath::angleAtPercent(qreal t) const
3277{
3278 if (t < 0 || t > 1) {
3279 qWarning("QPainterPath::angleAtPercent accepts only values between 0 and 1");
3280 return 0;
3281 }
3282
3283 if (isEmpty())
3284 return 0;
3285
3286 qreal totalLength = length();
3287 qreal curLen = 0;
3288 qreal bezierLen = 0;
3289 QBezier bez = d_ptr->bezierAtT(*this, t, &curLen, &bezierLen);
3290 Q_ASSERT(bezierLen != 0);
3291 qreal realT = (totalLength * t - curLen) / bezierLen;
3292
3293 qreal m1 = slopeAt(realT, bez.x1, bez.x2, bez.x3, bez.x4);
3294 qreal m2 = slopeAt(realT, bez.y1, bez.y2, bez.y3, bez.y4);
3295
3296 return QLineF(0, 0, m1, m2).angle();
3297}
3298
3299
3300/*!
3301 Returns the slope of the path at the percentage \a t. The
3302 argument \a t has to be between 0 and 1.
3303
3304 Note that similarly to other percent methods, the percentage measurement
3305 is not linear with regards to the length, if curves are present
3306 in the path. When curves are present the percentage argument is mapped
3307 to the t parameter of the Bezier equations.
3308*/
3309qreal QPainterPath::slopeAtPercent(qreal t) const
3310{
3311 if (t < 0 || t > 1) {
3312 qWarning("QPainterPath::slopeAtPercent accepts only values between 0 and 1");
3313 return 0;
3314 }
3315
3316 if (isEmpty())
3317 return 0;
3318
3319 qreal totalLength = length();
3320 qreal curLen = 0;
3321 qreal bezierLen = 0;
3322 QBezier bez = d_ptr->bezierAtT(*this, t, &curLen, &bezierLen);
3323 Q_ASSERT(bezierLen != 0);
3324 qreal realT = (totalLength * t - curLen) / bezierLen;
3325
3326 qreal m1 = slopeAt(realT, bez.x1, bez.x2, bez.x3, bez.x4);
3327 qreal m2 = slopeAt(realT, bez.y1, bez.y2, bez.y3, bez.y4);
3328 //tangent line
3329 qreal slope = 0;
3330
3331 if (m1)
3332 slope = m2/m1;
3333 else {
3334 if (std::numeric_limits<qreal>::has_infinity) {
3335 slope = (m2 < 0) ? -std::numeric_limits<qreal>::infinity()
3336 : std::numeric_limits<qreal>::infinity();
3337 } else {
3338 if (sizeof(qreal) == sizeof(double)) {
3339 return 1.79769313486231570e+308;
3340 } else {
3341 return ((qreal)3.40282346638528860e+38);
3342 }
3343 }
3344 }
3345
3346 return slope;
3347}
3348
3349/*!
3350 \since 6.10
3351
3352 Returns the section of the path between the length fractions \a fromFraction and \a toFraction.
3353 The effective range of the fractions are from 0, denoting the start point of the path, to 1,
3354 denoting its end point. The fractions are linear with respect to path length, in contrast to the
3355 percentage \e t values.
3356
3357 The value of \a offset will be added to the fraction values. If that causes an over- or underflow
3358 of the [0, 1] range, the values will be wrapped around, as will the resulting path. The effective
3359 range of the offset is between -1 and 1.
3360
3361 Repeated calls to this function can be optimized by {enabling caching}{setCachingEnabled()}.
3362
3363 \sa length(), percentAtLength(), setCachingEnabled()
3364*/
3365
3366QPainterPath QPainterPath::trimmed(qreal fromFraction, qreal toFraction, qreal offset) const
3367{
3368 if (isEmpty())
3369 return *this;
3370
3371 // We need length caching enabled for the calculations.
3372 if (!isCachingEnabled()) {
3373 QPainterPath copy(*this);
3374 copy.setCachingEnabled(true);
3375 return copy.trimmed(fromFraction, toFraction, offset);
3376 }
3377
3378 qreal f1 = qBound(qreal(0), fromFraction, qreal(1));
3379 qreal f2 = qBound(qreal(0), toFraction, qreal(1));
3380 if (qFuzzyIsNull(f1 - f2)) // ie. f1 == f2 (even if one of them is 0.0)
3381 return QPainterPath();
3382 if (f1 > f2)
3383 qSwap(f1, f2);
3384 if (qFuzzyCompare(f2 - f1, qreal(1))) // Shortcut for no trimming
3385 return *this;
3386
3387 QPainterPath res;
3388 res.setFillRule(fillRule());
3389
3390 if (offset) {
3391 qreal dummy;
3392 offset = std::modf(offset, &dummy); // Use only the fractional part of offset, range <-1, 1>
3393
3394 qreal of1 = f1 + offset;
3395 qreal of2 = f2 + offset;
3396 if (offset < 0) {
3397 f1 = of1 < 0 ? of1 + 1 : of1;
3398 f2 = of2 + 1 > 1 ? of2 : of2 + 1;
3399 } else if (offset > 0) {
3400 f1 = of1 - 1 < 0 ? of1 : of1 - 1;
3401 f2 = of2 > 1 ? of2 - 1 : of2;
3402 }
3403 }
3404 const bool wrapping = (f1 > f2);
3405 //qDebug() << "ADJ:" << f1 << f2 << wrapping << "(" << of1 << of2 << ")";
3406
3407 QPainterPathPrivate *d = d_func();
3408 if (d->dirtyRunLengths)
3409 d->computeRunLengths();
3410 const qreal totalLength = d->m_runLengths.last();
3411 if (qFuzzyIsNull(totalLength))
3412 return res;
3413
3414 const qreal l1 = f1 * totalLength;
3415 const qreal l2 = f2 * totalLength;
3416 const int e1 = d->elementAtLength(l1);
3417 const bool mustTrimE1 = !QtPrivate::fuzzyCompare(d->m_runLengths.at(e1), l1);
3418 const int e2 = d->elementAtLength(l2);
3419 const bool mustTrimE2 = !QtPrivate::fuzzyCompare(d->m_runLengths.at(e2), l2);
3420
3421 //qDebug() << "Trim [" << f1 << f2 << "] e1:" << e1 << mustTrimE1 << "e2:" << e2 << mustTrimE2 << "wrapping:" << wrapping;
3422 if (e1 == e2 && !wrapping && mustTrimE1 && mustTrimE2) {
3423 // Entire result is one element, clipped in both ends
3424 d->appendSliceOfElement(&res, e1, l1, l2);
3425 } else {
3426 // Add partial start element (or just its end point, being the start of the next)
3427 if (mustTrimE1)
3428 d->appendEndOfElement(&res, e1, l1);
3429 else
3430 res.moveTo(d->endPointOfElement(e1));
3431
3432 // Add whole elements between start and end
3433 int firstWholeElement = e1 + 1;
3434 int lastWholeElement = (mustTrimE2 ? e2 - 1 : e2);
3435 if (!wrapping) {
3436 d->appendElementRange(&res, firstWholeElement, lastWholeElement);
3437 } else {
3438 int lastIndex = d->elements.size() - 1;
3439 d->appendElementRange(&res, firstWholeElement, lastIndex);
3440 bool isClosed = (QPointF(d->elements.at(0)) == QPointF(d->elements.at(lastIndex)));
3441 // If closed we can skip the initial moveto
3442 d->appendElementRange(&res, (isClosed ? 1 : 0), lastWholeElement);
3443 }
3444
3445 // Partial end element
3446 if (mustTrimE2)
3447 d->appendStartOfElement(&res, e2, l2);
3448 }
3449
3450 return res;
3451}
3452
3453void QPainterPathPrivate::appendTrimmedElement(QPainterPath *to, int elemIdx, int trimFlags,
3454 qreal startLen, qreal endLen)
3455{
3456 Q_ASSERT(cacheEnabled);
3457 Q_ASSERT(!dirtyRunLengths);
3458
3459 if (elemIdx <= 0 || elemIdx >= elements.size())
3460 return;
3461
3462 const qreal prevLen = m_runLengths.at(elemIdx - 1);
3463 const qreal elemLen = m_runLengths.at(elemIdx) - prevLen;
3464 const qreal len1 = startLen - prevLen;
3465 const qreal len2 = endLen - prevLen;
3466 if (qFuzzyIsNull(elemLen))
3467 return;
3468
3469 const QPointF pp = elements.at(elemIdx - 1);
3470 const QPainterPath::Element e = elements.at(elemIdx);
3471 if (e.isLineTo()) {
3472 QLineF l(pp, e);
3473 QPointF p1 = (trimFlags & TrimStart) ? l.pointAt(len1 / elemLen) : pp;
3474 QPointF p2 = (trimFlags & TrimEnd) ? l.pointAt(len2 / elemLen) : e;
3475 if (to->isEmpty())
3476 to->moveTo(p1);
3477 to->lineTo(p2);
3478 } else if (e.isCurveTo()) {
3479 Q_ASSERT(elemIdx < elements.size() - 2);
3480 QBezier b = QBezier::fromPoints(pp, e, elements.at(elemIdx + 1), elements.at(elemIdx + 2));
3481 qreal t1 = (trimFlags & TrimStart) ? b.tAtLength(len1) : 0.0; // or simply len1/elemLen to trim by t instead of len
3482 qreal t2 = (trimFlags & TrimEnd) ? b.tAtLength(len2) : 1.0;
3483 QBezier c = b.getSubRange(t1, t2);
3484 if (to->isEmpty())
3485 to->moveTo(c.pt1());
3486 to->cubicTo(c.pt2(), c.pt3(), c.pt4());
3487 } else {
3488 Q_UNREACHABLE();
3489 }
3490}
3491
3492void QPainterPathPrivate::appendElementRange(QPainterPath *to, int first, int last)
3493{
3494 if (first < 0 || first >= elements.size() || last < 0 || last >= elements.size())
3495 return;
3496
3497 // (Could optimize by direct copy of elements, but must ensure correct state flags)
3498 for (int i = first; i <= last; i++) {
3499 const QPainterPath::Element &e = elements.at(i);
3500 switch (e.type) {
3501 case QPainterPath::MoveToElement:
3502 to->moveTo(e);
3503 break;
3504 case QPainterPath::LineToElement:
3505 to->lineTo(e);
3506 break;
3507 case QPainterPath::CurveToElement:
3508 Q_ASSERT(i < elements.size() - 2);
3509 to->cubicTo(e, elements.at(i + 1), elements.at(i + 2));
3510 i += 2;
3511 break;
3512 default:
3513 // 'first' may point to CurveToData element, just skip it
3514 break;
3515 }
3516 }
3517}
3518
3519
3520/*!
3521 \since 4.4
3522
3523 Adds the given rectangle \a rect with rounded corners to the path.
3524
3525 The \a xRadius and \a yRadius arguments specify the radii of
3526 the ellipses defining the corners of the rounded rectangle.
3527 When \a mode is Qt::RelativeSize, \a xRadius and
3528 \a yRadius are specified in percentage of half the rectangle's
3529 width and height respectively, and should be in the range 0.0 to 100.0.
3530
3531 \sa addRect()
3532*/
3533void QPainterPath::addRoundedRect(const QRectF &rect, qreal xRadius, qreal yRadius,
3534 Qt::SizeMode mode)
3535{
3536 QRectF r = rect.normalized();
3537
3538 if (r.isNull())
3539 return;
3540
3541 if (mode == Qt::AbsoluteSize) {
3542 qreal w = r.width() / 2;
3543 qreal h = r.height() / 2;
3544
3545 if (w == 0) {
3546 xRadius = 0;
3547 } else {
3548 xRadius = 100 * qMin(xRadius, w) / w;
3549 }
3550 if (h == 0) {
3551 yRadius = 0;
3552 } else {
3553 yRadius = 100 * qMin(yRadius, h) / h;
3554 }
3555 } else {
3556 if (xRadius > 100) // fix ranges
3557 xRadius = 100;
3558
3559 if (yRadius > 100)
3560 yRadius = 100;
3561 }
3562
3563 if (xRadius <= 0 || yRadius <= 0) { // add normal rectangle
3564 addRect(r);
3565 return;
3566 }
3567
3568 qreal x = r.x();
3569 qreal y = r.y();
3570 qreal w = r.width();
3571 qreal h = r.height();
3572 qreal rxx2 = w*xRadius/100;
3573 qreal ryy2 = h*yRadius/100;
3574
3575 ensureData();
3576 setDirty(true);
3577
3578 bool first = d_func()->elements.size() < 2;
3579
3580 arcMoveTo(x, y, rxx2, ryy2, 180);
3581 arcTo(x, y, rxx2, ryy2, 180, -90);
3582 arcTo(x+w-rxx2, y, rxx2, ryy2, 90, -90);
3583 arcTo(x+w-rxx2, y+h-ryy2, rxx2, ryy2, 0, -90);
3584 arcTo(x, y+h-ryy2, rxx2, ryy2, 270, -90);
3585 closeSubpath();
3586
3587 d_func()->require_moveTo = true;
3588 d_func()->convex = first;
3589}
3590
3591/*!
3592 \fn void QPainterPath::addRoundedRect(qreal x, qreal y, qreal w, qreal h, qreal xRadius, qreal yRadius, Qt::SizeMode mode = Qt::AbsoluteSize);
3593 \since 4.4
3594 \overload
3595
3596 Adds the given rectangle \a x, \a y, \a w, \a h with rounded corners to the path.
3597 */
3598
3599/*!
3600 \since 4.3
3601
3602 Returns a path which is the union of this path's fill area and \a p's fill area.
3603
3604 Set operations on paths will treat the paths as areas. Non-closed
3605 paths will be treated as implicitly closed.
3606 Bezier curves may be flattened to line segments due to numerical instability of
3607 doing bezier curve intersections.
3608
3609 \sa intersected(), subtracted()
3610*/
3611QPainterPath QPainterPath::united(const QPainterPath &p) const
3612{
3613 if (isEmpty() || p.isEmpty())
3614 return isEmpty() ? p : *this;
3615 QPathClipper clipper(*this, p);
3616 return clipper.clip(QPathClipper::BoolOr);
3617}
3618
3619/*!
3620 \since 4.3
3621
3622 Returns a path which is the intersection of this path's fill area and \a p's fill area.
3623 Bezier curves may be flattened to line segments due to numerical instability of
3624 doing bezier curve intersections.
3625*/
3626QPainterPath QPainterPath::intersected(const QPainterPath &p) const
3627{
3628 if (isEmpty() || p.isEmpty())
3629 return QPainterPath();
3630 QPathClipper clipper(*this, p);
3631 return clipper.clip(QPathClipper::BoolAnd);
3632}
3633
3634/*!
3635 \since 4.3
3636
3637 Returns a path which is \a p's fill area subtracted from this path's fill area.
3638
3639 Set operations on paths will treat the paths as areas. Non-closed
3640 paths will be treated as implicitly closed.
3641 Bezier curves may be flattened to line segments due to numerical instability of
3642 doing bezier curve intersections.
3643*/
3644QPainterPath QPainterPath::subtracted(const QPainterPath &p) const
3645{
3646 if (isEmpty() || p.isEmpty())
3647 return *this;
3648 QPathClipper clipper(*this, p);
3649 return clipper.clip(QPathClipper::BoolSub);
3650}
3651
3652/*!
3653 \since 4.4
3654
3655 Returns a simplified version of this path. This implies merging all subpaths that intersect,
3656 and returning a path containing no intersecting edges. Consecutive parallel lines will also
3657 be merged. The simplified path will always use the default fill rule, Qt::OddEvenFill.
3658 Bezier curves may be flattened to line segments due to numerical instability of
3659 doing bezier curve intersections.
3660*/
3661QPainterPath QPainterPath::simplified() const
3662{
3663 if (isEmpty())
3664 return *this;
3665 QPathClipper clipper(*this, QPainterPath());
3666 return clipper.clip(QPathClipper::Simplify);
3667}
3668
3669/*!
3670 \since 4.3
3671
3672 Returns \c true if the current path intersects at any point the given path \a p.
3673 Also returns \c true if the current path contains or is contained by any part of \a p.
3674
3675 Set operations on paths will treat the paths as areas. Non-closed
3676 paths will be treated as implicitly closed.
3677
3678 \sa contains()
3679 */
3680bool QPainterPath::intersects(const QPainterPath &p) const
3681{
3682 if (p.elementCount() == 1)
3683 return contains(p.elementAt(0));
3684 if (isEmpty() || p.isEmpty())
3685 return false;
3686 QPathClipper clipper(*this, p);
3687 return clipper.intersect();
3688}
3689
3690/*!
3691 \since 4.3
3692
3693 Returns \c true if the given path \a p is contained within
3694 the current path. Returns \c false if any edges of the current path and
3695 \a p intersect.
3696
3697 Set operations on paths will treat the paths as areas. Non-closed
3698 paths will be treated as implicitly closed.
3699
3700 \sa intersects()
3701 */
3702bool QPainterPath::contains(const QPainterPath &p) const
3703{
3704 if (p.elementCount() == 1)
3705 return contains(p.elementAt(0));
3706 if (isEmpty() || p.isEmpty())
3707 return false;
3708 QPathClipper clipper(*this, p);
3709 return clipper.contains();
3710}
3711
3712void QPainterPath::setDirty(bool dirty)
3713{
3714 d_func()->pathConverter.reset();
3715 d_func()->dirtyBounds = dirty;
3716 d_func()->dirtyControlBounds = dirty;
3717 d_func()->dirtyRunLengths = dirty;
3718 d_func()->convex = false;
3719}
3720
3721void QPainterPath::computeBoundingRect() const
3722{
3723 QPainterPathPrivate *d = d_func();
3724 d->dirtyBounds = false;
3725 if (!d_ptr) {
3726 d->bounds = QRect();
3727 return;
3728 }
3729
3730 qreal minx, maxx, miny, maxy;
3731 minx = maxx = d->elements.at(0).x;
3732 miny = maxy = d->elements.at(0).y;
3733 for (int i=1; i<d->elements.size(); ++i) {
3734 const Element &e = d->elements.at(i);
3735
3736 switch (e.type) {
3737 case MoveToElement:
3738 case LineToElement:
3739 if (e.x > maxx) maxx = e.x;
3740 else if (e.x < minx) minx = e.x;
3741 if (e.y > maxy) maxy = e.y;
3742 else if (e.y < miny) miny = e.y;
3743 break;
3744 case CurveToElement:
3745 {
3746 QBezier b = QBezier::fromPoints(d->elements.at(i-1),
3747 e,
3748 d->elements.at(i+1),
3749 d->elements.at(i+2));
3750 QRectF r = qt_painterpath_bezier_extrema(b);
3751 qreal right = r.right();
3752 qreal bottom = r.bottom();
3753 if (r.x() < minx) minx = r.x();
3754 if (right > maxx) maxx = right;
3755 if (r.y() < miny) miny = r.y();
3756 if (bottom > maxy) maxy = bottom;
3757 i += 2;
3758 }
3759 break;
3760 default:
3761 break;
3762 }
3763 }
3764 d->bounds = QRectF(minx, miny, maxx - minx, maxy - miny);
3765}
3766
3767
3768void QPainterPath::computeControlPointRect() const
3769{
3770 QPainterPathPrivate *d = d_func();
3771 d->dirtyControlBounds = false;
3772 if (!d_ptr) {
3773 d->controlBounds = QRect();
3774 return;
3775 }
3776
3777 qreal minx, maxx, miny, maxy;
3778 minx = maxx = d->elements.at(0).x;
3779 miny = maxy = d->elements.at(0).y;
3780 for (int i=1; i<d->elements.size(); ++i) {
3781 const Element &e = d->elements.at(i);
3782 if (e.x > maxx) maxx = e.x;
3783 else if (e.x < minx) minx = e.x;
3784 if (e.y > maxy) maxy = e.y;
3785 else if (e.y < miny) miny = e.y;
3786 }
3787 d->controlBounds = QRectF(minx, miny, maxx - minx, maxy - miny);
3788}
3789
3791{
3792 Q_ASSERT(!elements.isEmpty());
3793
3794 m_runLengths.clear();
3795 const int numElems = elements.size();
3796 m_runLengths.reserve(numElems);
3797
3798 QPointF runPt = elements[0];
3799 qreal runLen = 0.0;
3800 for (int i = 0; i < numElems; i++) {
3801 QPainterPath::Element e = elements[i];
3802 switch (e.type) {
3803 case QPainterPath::LineToElement:
3804 runLen += QLineF(runPt, e).length();
3805 runPt = e;
3806 break;
3807 case QPainterPath::CurveToElement: {
3808 Q_ASSERT(i < numElems - 2);
3809 QPainterPath::Element ee = elements[i + 2];
3810 runLen += QBezier::fromPoints(runPt, e, elements[i + 1], ee).length();
3811 runPt = ee;
3812 break;
3813 }
3814 case QPainterPath::MoveToElement:
3815 runPt = e;
3816 break;
3817 case QPainterPath::CurveToDataElement:
3818 break;
3819 }
3820 m_runLengths.append(runLen);
3821 }
3822 Q_ASSERT(m_runLengths.size() == elements.size());
3823
3824 dirtyRunLengths = false;
3825}
3826
3827#ifndef QT_NO_DEBUG_STREAM
3828QDebug operator<<(QDebug s, const QPainterPath &p)
3829{
3830 QDebugStateSaver saver(s);
3831 s.nospace() << "QPainterPath: Element count=" << p.elementCount() << Qt::endl;
3832 const char *types[] = {"MoveTo", "LineTo", "CurveTo", "CurveToData"};
3833 for (int i=0; i<p.elementCount(); ++i) {
3834 s.nospace() << " -> " << types[p.elementAt(i).type] << "(x=" << p.elementAt(i).x << ", y=" << p.elementAt(i).y << ')' << Qt::endl;
3835 }
3836 return s;
3837}
3838#endif
3839
3840QT_END_NAMESPACE
QBezier bezierAtT(const QPainterPath &path, qreal t, qreal *startingLength, qreal *bezierLength) const
Combined button and popup list for selecting options.
QDebug operator<<(QDebug dbg, const QFileInfo &fi)
static bool hasValidCoords(QRectF r)
static qreal slopeAt(qreal t, qreal a, qreal b, qreal c, qreal d)
void qt_path_stroke_move_to(qfixed x, qfixed y, void *data)
static bool qt_painterpath_check_crossing(const QPainterPath *path, const QRectF &rect)
static QBezier uncached_bezierAtT(const QPainterPath &path, qreal t, qreal *startingLength, qreal *bezierLength)
static bool qt_isect_curve_horizontal(const QBezier &bezier, qreal y, qreal x1, qreal x2, int depth=0)
static void qt_painterpath_isect_line(const QPointF &p1, const QPointF &p2, const QPointF &pos, int *winding)
static QRectF qt_painterpath_bezier_extrema(const QBezier &b)
#define QT_BEZIER_CHECK_T(bezier, t)
PainterDirections
@ Right
@ Top
@ Bottom
@ Left
static bool qt_painterpath_isect_line_rect(qreal x1, qreal y1, qreal x2, qreal y2, const QRectF &rect)
#define QT_BEZIER_C(bezier, coord)
void qt_find_ellipse_coords(const QRectF &r, qreal angle, qreal length, QPointF *startPoint, QPointF *endPoint)
void qt_path_stroke_cubic_to(qfixed c1x, qfixed c1y, qfixed c2x, qfixed c2y, qfixed ex, qfixed ey, void *data)
#define QT_BEZIER_A(bezier, coord)
static bool epsilonCompare(const QPointF &a, const QPointF &b, const QSizeF &epsilon)
#define QT_BEZIER_B(bezier, coord)
static QT_BEGIN_NAMESPACE bool isValidCoord(qreal c)
static void qt_painterpath_isect_curve(const QBezier &bezier, const QPointF &pt, int *winding, int depth=0)
static bool qt_isect_curve_vertical(const QBezier &bezier, qreal x, qreal y1, qreal y2, int depth=0)
static bool pointOnEdge(const QRectF &rect, const QPointF &point)
QPainterPath qt_stroke_dash(const QPainterPath &path, qreal *dashes, int dashCount)
static bool hasValidCoords(QPointF p)
void qt_path_stroke_line_to(qfixed x, qfixed y, void *data)
QDataStream & operator<<(QDataStream &stream, const QImage &image)
[0]
Definition qimage.cpp:4064
QDataStream & operator>>(QDataStream &stream, QImage &image)
Definition qimage.cpp:4090