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
qregion.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 "qregion.h"
6#include "qpainterpath.h"
7#include "qpolygon.h"
8#include "qbuffer.h"
9#include "qdatastream.h"
10#include "qvariant.h"
12#include "qimage.h"
13#include "qbitmap.h"
14#include "qtransform.h"
15
16#include <algorithm>
17#include <memory>
18#include <private/qdebug_p.h>
19
20#ifdef Q_OS_WIN
21# include <qt_windows.h>
22#endif
23
25
26/*!
27 \class QRegion
28 \brief The QRegion class specifies a clip region for a painter.
29
30 \inmodule QtGui
31 \ingroup painting
32 \ingroup shared
33
34 QRegion is used with QPainter::setClipRegion() to limit the paint
35 area to what needs to be painted. There is also a QWidget::repaint()
36 function that takes a QRegion parameter. QRegion is the best tool for
37 minimizing the amount of screen area to be updated by a repaint.
38
39 This class is not suitable for constructing shapes for rendering, especially
40 as outlines. Use QPainterPath to create paths and shapes for use with
41 QPainter.
42
43 QRegion is an \l{implicitly shared} class.
44
45 \section1 Creating and Using Regions
46
47 A region can be created from a rectangle, an ellipse, a polygon or
48 a bitmap. Complex regions may be created by combining simple
49 regions using united(), intersected(), subtracted(), or xored() (exclusive
50 or). You can move a region using translate().
51
52 You can test whether a region isEmpty() or if it
53 contains() a QPoint or QRect. The bounding rectangle can be found
54 with boundingRect().
55
56 Iteration over the region (with begin(), end(), or
57 ranged-for loops) gives a decomposition of the region into
58 rectangles.
59
60 Example of using complex regions:
61 \snippet code/src_gui_painting_qregion.cpp 0
62
63 \sa QPainter::setClipRegion(), QPainter::setClipRect(), QPainterPath
64*/
65
66
67/*!
68 \enum QRegion::RegionType
69
70 Specifies the shape of the region to be created.
71
72 \value Rectangle the region covers the entire rectangle.
73 \value Ellipse the region is an ellipse inside the rectangle.
74*/
75
76/*!
77 \fn void QRegion::translate(const QPoint &point)
78
79 \overload
80
81 Translates the region \a{point}\e{.x()} along the x axis and
82 \a{point}\e{.y()} along the y axis, relative to the current
83 position. Positive values move the region to the right and down.
84
85 Translates to the given \a point.
86*/
87
88/*****************************************************************************
89 QRegion member functions
90 *****************************************************************************/
91
92/*!
93 \fn QRegion::QRegion()
94
95 Constructs an empty region.
96
97 \sa isEmpty()
98*/
99
100/*!
101 \fn QRegion::QRegion(const QRect &r, RegionType t)
102 \overload
103
104 Create a region based on the rectangle \a r with region type \a t.
105
106 If the rectangle is invalid a null region will be created.
107
108 \sa QRegion::RegionType
109*/
110
111/*!
112 \fn QRegion::QRegion(const QPolygon &a, Qt::FillRule fillRule)
113
114 Constructs a polygon region from the point array \a a with the fill rule
115 specified by \a fillRule.
116
117 If \a fillRule is \l{Qt::WindingFill}, the polygon region is defined
118 using the winding algorithm; if it is \l{Qt::OddEvenFill}, the odd-even fill
119 algorithm is used.
120
121 \warning This constructor can be used to create complex regions that will
122 slow down painting when used.
123*/
124
125/*!
126 \fn QRegion::QRegion(const QRegion &r)
127
128 Constructs a new region which is equal to region \a r.
129*/
130
131/*!
132 \fn QRegion::QRegion(QRegion &&other)
133 \since 5.7
134
135 Move-constructs a new region from region \a other.
136 After the call, \a other is null.
137
138 \sa isNull()
139*/
140
141/*!
142 \fn QRegion::QRegion(const QBitmap &bm)
143
144 Constructs a region from the bitmap \a bm.
145
146 The resulting region consists of the pixels in bitmap \a bm that
147 are Qt::color1, as if each pixel was a 1 by 1 rectangle.
148
149 This constructor may create complex regions that will slow down
150 painting when used. Note that drawing masked pixmaps can be done
151 much faster using QPixmap::setMask().
152*/
153
154/*!
155 Constructs a rectangular or elliptic region.
156
157 If \a t is \c Rectangle, the region is the filled rectangle (\a x,
158 \a y, \a w, \a h). If \a t is \c Ellipse, the region is the filled
159 ellipse with center at (\a x + \a w / 2, \a y + \a h / 2) and size
160 (\a w ,\a h).
161*/
162QRegion::QRegion(int x, int y, int w, int h, RegionType t)
163{
164 QRegion tmp(QRect(x, y, w, h), t);
165 tmp.d->ref.ref();
166 d = tmp.d;
167}
168
169/*!
170 \fn QRegion::~QRegion()
171 \internal
172
173 Destroys the region.
174*/
175
176void QRegion::detach()
177{
178 if (d->ref.isShared())
179 *this = copy();
180}
181
182// duplicates in qregion_win.cpp and qregion_wce.cpp
183#define QRGN_SETRECT 1 // region stream commands
184#define QRGN_SETELLIPSE 2 // (these are internal)
185#define QRGN_SETPTARRAY_ALT 3
186#define QRGN_SETPTARRAY_WIND 4
187#define QRGN_TRANSLATE 5
188#define QRGN_OR 6
189#define QRGN_AND 7
190#define QRGN_SUB 8
191#define QRGN_XOR 9
192#define QRGN_RECTS 10
193
194
195#ifndef QT_NO_DATASTREAM
196
197/*
198 Executes region commands in the internal buffer and rebuilds the
199 original region.
200
201 We do this when we read a region from the data stream.
202
203 If \a ver is non-0, uses the format version \a ver on reading the
204 byte array.
205*/
206void QRegion::exec(const QByteArray &buffer, int ver, QDataStream::ByteOrder byteOrder)
207{
208 QByteArray copy = buffer;
209 QDataStream s(&copy, QIODevice::ReadOnly);
210 if (ver)
211 s.setVersion(ver);
212 s.setByteOrder(byteOrder);
213 QRegion rgn;
214#ifndef QT_NO_DEBUG
215 int test_cnt = 0;
216#endif
217 while (!s.atEnd()) {
218 qint32 id;
219 if (s.version() == 1) {
220 int id_int;
221 s >> id_int;
222 id = id_int;
223 } else {
224 s >> id;
225 }
226#ifndef QT_NO_DEBUG
227 if (test_cnt > 0 && id != QRGN_TRANSLATE)
228 qWarning("QRegion::exec: Internal error");
229 test_cnt++;
230#endif
231 if (id == QRGN_SETRECT || id == QRGN_SETELLIPSE) {
232 QRect r;
233 s >> r;
234 rgn = QRegion(r, id == QRGN_SETRECT ? Rectangle : Ellipse);
235 } else if (id == QRGN_SETPTARRAY_ALT || id == QRGN_SETPTARRAY_WIND) {
236 QPolygon a;
237 s >> a;
238 rgn = QRegion(a, id == QRGN_SETPTARRAY_WIND ? Qt::WindingFill : Qt::OddEvenFill);
239 } else if (id == QRGN_TRANSLATE) {
240 QPoint p;
241 s >> p;
242 rgn.translate(p.x(), p.y());
243 } else if (id >= QRGN_OR && id <= QRGN_XOR) {
244 QByteArray bop1, bop2;
245 QRegion r1, r2;
246 s >> bop1;
247 r1.exec(bop1);
248 s >> bop2;
249 r2.exec(bop2);
250
251 switch (id) {
252 case QRGN_OR:
253 rgn = r1.united(r2);
254 break;
255 case QRGN_AND:
256 rgn = r1.intersected(r2);
257 break;
258 case QRGN_SUB:
259 rgn = r1.subtracted(r2);
260 break;
261 case QRGN_XOR:
262 rgn = r1.xored(r2);
263 break;
264 }
265 } else if (id == QRGN_RECTS) {
266 // (This is the only form used in Qt 2.0)
267 quint32 n;
268 s >> n;
269 QRect r;
270 for (int i=0; i < static_cast<int>(n); i++) {
271 s >> r;
272 rgn = rgn.united(QRegion(r));
273 }
274 }
275 }
276 *this = rgn;
277}
278
279
280/*****************************************************************************
281 QRegion stream functions
282 *****************************************************************************/
283
284/*!
285 \fn QRegion &QRegion::operator=(const QRegion &r)
286
287 Assigns \a r to this region and returns a reference to the region.
288*/
289
290/*!
291 \fn QRegion &QRegion::operator=(QRegion &&other)
292
293 Move-assigns \a other to this QRegion instance.
294
295 \since 5.2
296*/
297
298/*!
299 \fn void QRegion::swap(QRegion &other)
300 \since 4.8
301 \memberswap{region}
302*/
303
304/*!
305 \relates QRegion
306
307 Writes the region \a r to the stream \a s and returns a reference
308 to the stream.
309
310 \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
311*/
312
313QDataStream &operator<<(QDataStream &s, const QRegion &r)
314{
315 auto b = r.begin(), e = r.end();
316 if (b == e) {
317 s << static_cast<quint32>(0);
318 } else {
319 const auto size = e - b;
320 if (s.version() == 1) {
321 for (auto i = size - 1; i > 0; --i) {
322 s << static_cast<quint32>(12 + i * 24);
323 s << static_cast<int>(QRGN_OR);
324 }
325 for (auto it = b; it != e; ++it)
326 s << static_cast<quint32>(4+8) << static_cast<int>(QRGN_SETRECT) << *it;
327 } else {
328 s << quint32(4 + 4 + 16 * size); // 16: storage size of QRect
329 s << static_cast<qint32>(QRGN_RECTS);
330 s << quint32(size);
331 for (auto it = b; it != e; ++it)
332 s << *it;
333 }
334 }
335 return s;
336}
337
338/*!
339 \relates QRegion
340
341 Reads a region from the stream \a s into \a r and returns a
342 reference to the stream.
343
344 \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
345*/
346
347QDataStream &operator>>(QDataStream &s, QRegion &r)
348{
349 QByteArray b;
350 s >> b;
351 r.exec(b, s.version(), s.byteOrder());
352 return s;
353}
354#endif //QT_NO_DATASTREAM
355
356#ifndef QT_NO_DEBUG_STREAM
357QDebug operator<<(QDebug s, const QRegion &r)
358{
359 QDebugStateSaver saver(s);
360 s.nospace();
361 s << "QRegion(";
362 if (r.isNull()) {
363 s << "null";
364 } else if (r.isEmpty()) {
365 s << "empty";
366 } else {
367 const int count = r.rectCount();
368 if (count > 1)
369 s << "size=" << count << ", bounds=(";
370 QtDebugUtils::formatQRect(s, r.boundingRect());
371 if (count > 1) {
372 s << ") - [";
373 bool first = true;
374 for (const QRect &rect : r) {
375 if (!first)
376 s << ", ";
377 s << '(';
378 QtDebugUtils::formatQRect(s, rect);
379 s << ')';
380 first = false;
381 }
382 s << ']';
383 }
384 }
385 s << ')';
386 return s;
387}
388#endif
389
390
391// These are not inline - they can be implemented better on some platforms
392// (eg. Windows at least provides 3-variable operations). For now, simple.
393
394
395/*!
396 Applies the united() function to this region and \a r. \c r1|r2 is
397 equivalent to \c r1.united(r2).
398
399 \sa united(), operator+()
400*/
401QRegion QRegion::operator|(const QRegion &r) const
402 { return united(r); }
403
404/*!
405 Applies the united() function to this region and \a r. \c r1+r2 is
406 equivalent to \c r1.united(r2).
407
408 \sa united(), operator|()
409*/
410QRegion QRegion::operator+(const QRegion &r) const
411 { return united(r); }
412
413/*!
414 \overload
415 \since 4.4
416 */
417QRegion QRegion::operator+(const QRect &r) const
418 { return united(r); }
419
420/*!
421 Applies the intersected() function to this region and \a r. \c r1&r2
422 is equivalent to \c r1.intersected(r2).
423
424 \sa intersected()
425*/
426QRegion QRegion::operator&(const QRegion &r) const
427 { return intersected(r); }
428
429/*!
430 \overload
431 \since 4.4
432 */
433QRegion QRegion::operator&(const QRect &r) const
434{
435 return intersected(r);
436}
437
438/*!
439 Applies the subtracted() function to this region and \a r. \c r1-r2
440 is equivalent to \c r1.subtracted(r2).
441
442 \sa subtracted()
443*/
444QRegion QRegion::operator-(const QRegion &r) const
445 { return subtracted(r); }
446
447/*!
448 Applies the xored() function to this region and \a r. \c r1^r2 is
449 equivalent to \c r1.xored(r2).
450
451 \sa xored()
452*/
453QRegion QRegion::operator^(const QRegion &r) const
454 { return xored(r); }
455
456/*!
457 Applies the united() function to this region and \a r and assigns
458 the result to this region. \c r1|=r2 is equivalent to \c
459 {r1 = r1.united(r2)}.
460
461 \sa united()
462*/
463QRegion& QRegion::operator|=(const QRegion &r)
464 { return *this = *this | r; }
465
466/*!
467 \fn QRegion& QRegion::operator+=(const QRect &rect)
468
469 Returns a region that is the union of this region with the specified \a rect.
470
471 \sa united()
472*/
473/*!
474 \fn QRegion& QRegion::operator+=(const QRegion &r)
475
476 Applies the united() function to this region and \a r and assigns
477 the result to this region. \c r1+=r2 is equivalent to \c
478 {r1 = r1.united(r2)}.
479
480 \sa intersected()
481*/
482
483/*!
484 \fn QRegion& QRegion::operator&=(const QRegion &r)
485
486 Applies the intersected() function to this region and \a r and
487 assigns the result to this region. \c r1&=r2 is equivalent to \c
488 r1 = r1.intersected(r2).
489
490 \sa intersected()
491*/
492QRegion& QRegion::operator&=(const QRegion &r)
493 { return *this = *this & r; }
494
495/*!
496 \overload
497 \since 4.4
498 */
499#if defined (Q_OS_UNIX) || defined (Q_OS_WIN)
500QRegion& QRegion::operator&=(const QRect &r)
501{
502 return *this = *this & r;
503}
504#else
505QRegion& QRegion::operator&=(const QRect &r)
506{
507 return *this &= (QRegion(r));
508}
509#endif
510
511/*!
512 \fn QRegion& QRegion::operator-=(const QRegion &r)
513
514 Applies the subtracted() function to this region and \a r and
515 assigns the result to this region. \c r1-=r2 is equivalent to \c
516 {r1 = r1.subtracted(r2)}.
517
518 \sa subtracted()
519*/
520QRegion& QRegion::operator-=(const QRegion &r)
521 { return *this = *this - r; }
522
523/*!
524 Applies the xored() function to this region and \a r and
525 assigns the result to this region. \c r1^=r2 is equivalent to \c
526 {r1 = r1.xored(r2)}.
527
528 \sa xored()
529*/
530QRegion& QRegion::operator^=(const QRegion &r)
531 { return *this = *this ^ r; }
532
533/*!
534 \fn bool QRegion::operator!=(const QRegion &other) const
535
536 Returns \c true if this region is different from the \a other region;
537 otherwise returns \c false.
538*/
539
540/*!
541 Returns the region as a QVariant
542*/
543QRegion::operator QVariant() const
544{
545 return QVariant::fromValue(*this);
546}
547
548/*!
549 \fn bool QRegion::operator==(const QRegion &r) const
550
551 Returns \c true if the region is equal to \a r; otherwise returns
552 false.
553*/
554
555/*!
556 \fn void QRegion::translate(int dx, int dy)
557
558 Translates (moves) the region \a dx along the X axis and \a dy
559 along the Y axis.
560*/
561
562/*!
563 \fn QRegion QRegion::translated(const QPoint &p) const
564 \overload
565 \since 4.1
566
567 Returns a copy of the regtion that is translated \a{p}\e{.x()}
568 along the x axis and \a{p}\e{.y()} along the y axis, relative to
569 the current position. Positive values move the rectangle to the
570 right and down.
571
572 \sa translate()
573*/
574
575/*!
576 \since 4.1
577
578 Returns a copy of the region that is translated \a dx along the
579 x axis and \a dy along the y axis, relative to the current
580 position. Positive values move the region to the right and
581 down.
582
583 \sa translate()
584*/
585
586QRegion
587QRegion::translated(int dx, int dy) const
588{
589 QRegion ret(*this);
590 ret.translate(dx, dy);
591 return ret;
592}
593
594
595inline bool rect_intersects(const QRect &r1, const QRect &r2)
596{
597 return (r1.right() >= r2.left() && r1.left() <= r2.right() &&
598 r1.bottom() >= r2.top() && r1.top() <= r2.bottom());
599}
600
601/*!
602 \since 4.2
603
604 Returns \c true if this region intersects with \a region, otherwise
605 returns \c false.
606*/
607bool QRegion::intersects(const QRegion &region) const
608{
609 if (isEmpty() || region.isEmpty())
610 return false;
611
612 if (!rect_intersects(boundingRect(), region.boundingRect()))
613 return false;
614 if (rectCount() == 1 && region.rectCount() == 1)
615 return true;
616
617 for (const QRect &myRect : *this)
618 for (const QRect &otherRect : region)
619 if (rect_intersects(myRect, otherRect))
620 return true;
621 return false;
622}
623
624/*!
625 \fn bool QRegion::intersects(const QRect &rect) const
626 \since 4.2
627
628 Returns \c true if this region intersects with \a rect, otherwise
629 returns \c false.
630*/
631
632
633#if !defined (Q_OS_UNIX) && !defined (Q_OS_WIN) || defined(Q_QDOC)
634/*
635 \overload
636 \since 4.4
637*/
638QRegion QRegion::intersect(const QRect &r) const
639{
640 return intersect(QRegion(r));
641}
642#endif
643
644/*!
645 \fn int QRegion::rectCount() const
646 \since 4.6
647
648 Returns the number of rectangles that this region is composed of.
649 Same as \c{end() - begin()}.
650*/
651
652/*!
653 \fn bool QRegion::isEmpty() const
654
655 Returns \c true if the region is empty; otherwise returns \c false. An
656 empty region is a region that contains no points.
657
658 Example:
659 \snippet code/src_gui_painting_qregion_unix.cpp 0
660*/
661
662/*!
663 \fn bool QRegion::isNull() const
664 \since 5.0
665
666 Returns \c true if the region is empty; otherwise returns \c false. An
667 empty region is a region that contains no points. This function is
668 the same as isEmpty
669
670 \sa isEmpty()
671*/
672
673/*!
674 \fn bool QRegion::contains(const QPoint &p) const
675
676 Returns \c true if the region contains the point \a p; otherwise
677 returns \c false.
678*/
679
680/*!
681 \fn bool QRegion::contains(const QRect &r) const
682 \overload
683
684 Returns \c true if the region overlaps the rectangle \a r; otherwise
685 returns \c false.
686*/
687
688/*!
689 \fn QRegion QRegion::united(const QRect &rect) const
690 \since 4.4
691
692 Returns a region which is the union of this region and the given \a rect.
693
694 \sa intersected(), subtracted(), xored()
695*/
696
697/*!
698 \fn QRegion QRegion::united(const QRegion &r) const
699 \since 4.2
700
701 Returns a region which is the union of this region and \a r.
702
703 \image runion.png Region Union
704
705 The figure shows the union of two elliptical regions.
706
707 \sa intersected(), subtracted(), xored()
708*/
709
710/*!
711 \fn QRegion QRegion::intersected(const QRect &rect) const
712 \since 4.4
713
714 Returns a region which is the intersection of this region and the given \a rect.
715
716 \sa subtracted(), united(), xored()
717*/
718
719/*!
720 \fn QRegion QRegion::intersected(const QRegion &r) const
721 \since 4.2
722
723 Returns a region which is the intersection of this region and \a r.
724
725 \image rintersect.png Region Intersection
726
727 The figure shows the intersection of two elliptical regions.
728
729 \sa subtracted(), united(), xored()
730*/
731
732/*!
733 \fn QRegion QRegion::subtracted(const QRegion &r) const
734 \since 4.2
735
736 Returns a region which is \a r subtracted from this region.
737
738 \image rsubtract.png Region Subtraction
739
740 The figure shows the result when the ellipse on the right is
741 subtracted from the ellipse on the left (\c {left - right}).
742
743 \sa intersected(), united(), xored()
744*/
745
746/*!
747 \fn QRegion QRegion::xored(const QRegion &r) const
748 \since 4.2
749
750 Returns a region which is the exclusive or (XOR) of this region
751 and \a r.
752
753 \image rxor.png Region XORed
754
755 The figure shows the exclusive or of two elliptical regions.
756
757 \sa intersected(), united(), subtracted()
758*/
759
760/*!
761 \fn QRect QRegion::boundingRect() const
762
763 Returns the bounding rectangle of this region. An empty region
764 gives a rectangle that is QRect::isNull().
765*/
766
767/*!
768 \typedef QRegion::const_iterator
769 \since 5.8
770
771 An iterator over the non-overlapping rectangles that make up the
772 region.
773
774 The union of all the rectangles is equal to the original region.
775
776 QRegion does not offer mutable iterators.
777
778 \sa begin(), end()
779*/
780
781/*!
782 \typedef QRegion::const_reverse_iterator
783 \since 5.8
784
785 A reverse iterator over the non-overlapping rectangles that make up the
786 region.
787
788 The union of all the rectangles is equal to the original region.
789
790 QRegion does not offer mutable iterators.
791
792 \sa rbegin(), rend()
793*/
794
795/*!
796 \fn QRegion::begin() const
797 \since 5.8
798
799 Returns a const_iterator pointing to the beginning of the range of
800 non-overlapping rectangles that make up the region.
801
802 The union of all the rectangles is equal to the original region.
803
804 \sa rbegin(), cbegin(), end()
805*/
806
807/*!
808 \fn QRegion::cbegin() const
809 \since 5.8
810
811 Same as begin().
812*/
813
814/*!
815 \fn QRegion::end() const
816 \since 5.8
817
818 Returns a const_iterator pointing to one past the end of
819 non-overlapping rectangles that make up the region.
820
821 The union of all the rectangles is equal to the original region.
822
823 \sa rend(), cend(), begin()
824*/
825
826/*!
827 \fn QRegion::cend() const
828 \since 5.8
829
830 Same as end().
831*/
832
833/*!
834 \fn QRegion::rbegin() const
835 \since 5.8
836
837 Returns a const_reverse_iterator pointing to the beginning of the
838 range of non-overlapping rectangles that make up the region.
839
840 The union of all the rectangles is equal to the original region.
841
842 \sa begin(), crbegin(), rend()
843*/
844
845/*!
846 \fn QRegion::crbegin() const
847 \since 5.8
848
849 Same as rbegin().
850*/
851
852/*!
853 \fn QRegion::rend() const
854 \since 5.8
855
856 Returns a const_reverse_iterator pointing to one past the end of
857 the range of non-overlapping rectangles that make up the region.
858
859 The union of all the rectangles is equal to the original region.
860
861 \sa end(), crend(), rbegin()
862*/
863
864/*!
865 \fn QRegion::crend() const
866 \since 5.8
867
868 Same as rend().
869*/
870
871/*!
872 \fn void QRegion::setRects(const QRect *rects, int number)
873 \overload
874 \obsolete Use the QSpan overload instead.
875*/
876
877/*!
878 \fn void QRegion::setRects(QSpan<const QRect> rects)
879 \since 6.8
880
881 Sets the region using the array of rectangles specified by \a rects.
882 The rectangles \e must be optimally Y-X sorted and follow these restrictions:
883
884 \list
885 \li The rectangles must not intersect.
886 \li All rectangles with a given top coordinate must have the same height.
887 \li No two rectangles may abut horizontally (they should be combined
888 into a single wider rectangle in that case).
889 \li The rectangles must be sorted in ascending order, with Y as the major
890 sort key and X as the minor sort key.
891 \endlist
892 \omit
893 Only some platforms have these restrictions (Qt for Embedded Linux, X11 and \macos).
894 \endomit
895
896 \note For historical reasons, \c{rects.size()} must be less than \c{INT_MAX}
897 (see rectCount()).
898
899 \sa rects()
900*/
901
902namespace {
903
904struct Segment
905{
906 Segment() {}
907 Segment(const QPoint &p)
908 : added(false)
909 , point(p)
910 {
911 }
912
913 int left() const
914 {
915 return qMin(point.x(), next->point.x());
916 }
917
918 int right() const
919 {
920 return qMax(point.x(), next->point.x());
921 }
922
923 bool overlaps(const Segment &other) const
924 {
925 return left() < other.right() && other.left() < right();
926 }
927
928 void connect(Segment &other)
929 {
930 next = &other;
931 other.prev = this;
932
933 horizontal = (point.y() == other.point.y());
934 }
935
936 void merge(Segment &other)
937 {
938 if (right() <= other.right()) {
939 QPoint p = other.point;
940 Segment *oprev = other.prev;
941
942 other.point = point;
943 other.prev = prev;
944 prev->next = &other;
945
946 point = p;
947 prev = oprev;
948 oprev->next = this;
949 } else {
950 Segment *onext = other.next;
951 other.next = next;
952 next->prev = &other;
953
954 next = onext;
955 next->prev = this;
956 }
957 }
958
959 int horizontal : 1;
960 int added : 1;
961
962 QPoint point;
963 Segment *prev;
964 Segment *next;
965};
966
967void mergeSegments(Segment *a, int na, Segment *b, int nb)
968{
969 int i = 0;
970 int j = 0;
971
972 while (i != na && j != nb) {
973 Segment &sa = a[i];
974 Segment &sb = b[j];
975 const int ra = sa.right();
976 const int rb = sb.right();
977 if (sa.overlaps(sb))
978 sa.merge(sb);
979 i += (rb >= ra);
980 j += (ra >= rb);
981 }
982}
983
984void addSegmentsToPath(Segment *segment, QPainterPath &path)
985{
986 Segment *current = segment;
987 path.moveTo(current->point);
988
989 current->added = true;
990
991 Segment *last = current;
992 current = current->next;
993 while (current != segment) {
994 if (current->horizontal != last->horizontal)
995 path.lineTo(current->point);
996 current->added = true;
997 last = current;
998 current = current->next;
999 }
1000}
1001
1002} // unnamed namespace
1003
1004// the following is really a lie, because Segments cannot be relocated, as they
1005// reference each other by address. For the same reason, they aren't even copyable,
1006// but the code works with the compiler-generated (wrong) copy and move special
1007// members, so use this as an optimization. The only container these are used in
1008// (a QVarLengthArray in qt_regionToPath()) is resized once up-front, so doesn't
1009// have a problem with this, but benefits from not having to run Segment ctors:
1011
1012Q_GUI_EXPORT QPainterPath qt_regionToPath(const QRegion &region)
1013{
1014 QPainterPath result;
1015 if (region.rectCount() == 1) {
1016 result.addRect(region.boundingRect());
1017 return result;
1018 }
1019
1020 auto rect = region.begin();
1021 const auto end = region.end();
1022
1023 QVarLengthArray<Segment> segments;
1024 segments.resize(4 * (end - rect));
1025
1026 int lastRowSegmentCount = 0;
1027 Segment *lastRowSegments = nullptr;
1028
1029 int lastSegment = 0;
1030 int lastY = 0;
1031 while (rect != end) {
1032 const int y = rect[0].y();
1033 int count = 0;
1034 while (&rect[count] != end && rect[count].y() == y)
1035 ++count;
1036
1037 for (int i = 0; i < count; ++i) {
1038 int offset = lastSegment + i;
1039 segments[offset] = Segment(rect[i].topLeft());
1040 segments[offset += count] = Segment(rect[i].topRight() + QPoint(1, 0));
1041 segments[offset += count] = Segment(rect[i].bottomRight() + QPoint(1, 1));
1042 segments[offset += count] = Segment(rect[i].bottomLeft() + QPoint(0, 1));
1043
1044 offset = lastSegment + i;
1045 for (int j = 0; j < 4; ++j)
1046 segments[offset + j * count].connect(segments[offset + ((j + 1) % 4) * count]);
1047 }
1048
1049 if (lastRowSegments && lastY == y)
1050 mergeSegments(lastRowSegments, lastRowSegmentCount, &segments[lastSegment], count);
1051
1052 lastRowSegments = &segments[lastSegment + 2 * count];
1053 lastRowSegmentCount = count;
1054 lastSegment += 4 * count;
1055 lastY = y + rect[0].height();
1056 rect += count;
1057 }
1058
1059 for (int i = 0; i < lastSegment; ++i) {
1060 Segment *segment = &segments[i];
1061 if (!segment->added)
1062 addSegmentsToPath(segment, result);
1063 }
1064
1065 return result;
1066}
1067
1068//#define QT_REGION_DEBUG
1069/*
1070 * clip region
1071 */
1072
1077 QRect extents;
1079
1080 constexpr QRegionPrivate() : numRects(0), innerArea(-1) {}
1081 inline QRegionPrivate(const QRect &r)
1082 : numRects(1),
1083 innerArea(r.width() * r.height()),
1084 extents(r),
1085 innerRect(r)
1086 {
1087 }
1088
1089 void intersect(const QRect &r);
1090
1091 /*
1092 * Returns \c true if r is guaranteed to be fully contained in this region.
1093 * A false return value does not guarantee the opposite.
1094 */
1095 inline bool contains(const QRegionPrivate &r) const {
1096 return contains(r.extents);
1097 }
1098
1099 inline bool contains(const QRect &r2) const {
1100 const QRect &r1 = innerRect;
1101 return r2.left() >= r1.left() && r2.right() <= r1.right()
1102 && r2.top() >= r1.top() && r2.bottom() <= r1.bottom();
1103 }
1104
1105 /*
1106 * Returns \c true if this region is guaranteed to be fully contained in r.
1107 */
1108 inline bool within(const QRect &r1) const {
1109 const QRect &r2 = extents;
1110 return r2.left() >= r1.left() && r2.right() <= r1.right()
1111 && r2.top() >= r1.top() && r2.bottom() <= r1.bottom();
1112 }
1113
1114 inline void updateInnerRect(const QRect &rect) {
1115 const int area = rect.width() * rect.height();
1116 if (area > innerArea) {
1117 innerArea = area;
1118 innerRect = rect;
1119 }
1120 }
1121
1122 inline void vectorize() {
1123 if (numRects == 1) {
1124 if (!rects.size())
1125 rects.resize(1);
1126 rects[0] = extents;
1127 }
1128 }
1129
1130 const QRect *begin() const noexcept
1131 { return numRects == 1 ? &extents : rects.data(); } // avoid vectorize()
1132
1133 const QRect *end() const noexcept
1134 { return begin() + numRects; }
1135
1136 inline void append(const QRect *r);
1137 void append(const QRegionPrivate *r);
1138 void prepend(const QRect *r);
1139 void prepend(const QRegionPrivate *r);
1140 inline bool canAppend(const QRect *r) const;
1141 inline bool canAppend(const QRegionPrivate *r) const;
1142 inline bool canPrepend(const QRect *r) const;
1143 inline bool canPrepend(const QRegionPrivate *r) const;
1144
1145 inline bool mergeFromRight(QRect *left, const QRect *right);
1146 inline bool mergeFromLeft(QRect *left, const QRect *right);
1147 inline bool mergeFromBelow(QRect *top, const QRect *bottom,
1148 const QRect *nextToTop,
1149 const QRect *nextToBottom);
1150 inline bool mergeFromAbove(QRect *bottom, const QRect *top,
1151 const QRect *nextToBottom,
1152 const QRect *nextToTop);
1153
1154#ifdef QT_REGION_DEBUG
1155 void selfTest() const;
1156#endif
1157};
1158
1159static inline bool isEmptyHelper(const QRegionPrivate *preg)
1160{
1161 return !preg || preg->numRects == 0;
1162}
1163
1164static inline bool canMergeFromRight(const QRect *left, const QRect *right)
1165{
1166 return (right->top() == left->top()
1167 && right->bottom() == left->bottom()
1168 && right->left() <= (left->right() + 1));
1169}
1170
1171static inline bool canMergeFromLeft(const QRect *right, const QRect *left)
1172{
1173 return canMergeFromRight(left, right);
1174}
1175
1176bool QRegionPrivate::mergeFromRight(QRect *left, const QRect *right)
1177{
1178 if (canMergeFromRight(left, right)) {
1179 left->setRight(right->right());
1180 updateInnerRect(*left);
1181 return true;
1182 }
1183 return false;
1184}
1185
1186bool QRegionPrivate::mergeFromLeft(QRect *right, const QRect *left)
1187{
1188 if (canMergeFromLeft(right, left)) {
1189 right->setLeft(left->left());
1190 updateInnerRect(*right);
1191 return true;
1192 }
1193 return false;
1194}
1195
1196static inline bool canMergeFromBelow(const QRect *top, const QRect *bottom,
1197 const QRect *nextToTop,
1198 const QRect *nextToBottom)
1199{
1200 if (nextToTop && nextToTop->y() == top->y())
1201 return false;
1202 if (nextToBottom && nextToBottom->y() == bottom->y())
1203 return false;
1204
1205 return ((top->bottom() >= (bottom->top() - 1))
1206 && top->left() == bottom->left()
1207 && top->right() == bottom->right());
1208}
1209
1210bool QRegionPrivate::mergeFromBelow(QRect *top, const QRect *bottom,
1211 const QRect *nextToTop,
1212 const QRect *nextToBottom)
1213{
1214 if (canMergeFromBelow(top, bottom, nextToTop, nextToBottom)) {
1215 top->setBottom(bottom->bottom());
1217 return true;
1218 }
1219 return false;
1220}
1221
1222bool QRegionPrivate::mergeFromAbove(QRect *bottom, const QRect *top,
1223 const QRect *nextToBottom,
1224 const QRect *nextToTop)
1225{
1226 if (canMergeFromBelow(top, bottom, nextToTop, nextToBottom)) {
1227 bottom->setTop(top->top());
1228 updateInnerRect(*bottom);
1229 return true;
1230 }
1231 return false;
1232}
1233
1234static inline QRect qt_rect_intersect_normalized(const QRect &r1,
1235 const QRect &r2)
1236{
1237 QRect r;
1238 r.setLeft(qMax(r1.left(), r2.left()));
1239 r.setRight(qMin(r1.right(), r2.right()));
1240 r.setTop(qMax(r1.top(), r2.top()));
1241 r.setBottom(qMin(r1.bottom(), r2.bottom()));
1242 return r;
1243}
1244
1245void QRegionPrivate::intersect(const QRect &rect)
1246{
1247 Q_ASSERT(extents.intersects(rect));
1248 Q_ASSERT(numRects > 1);
1249
1250#ifdef QT_REGION_DEBUG
1251 selfTest();
1252#endif
1253
1254 const QRect r = rect.normalized();
1255 extents = QRect();
1256 innerRect = QRect();
1257 innerArea = -1;
1258
1259 QRect *dest = rects.data();
1260 const QRect *src = dest;
1261 int n = numRects;
1262 numRects = 0;
1263 while (n--) {
1264 *dest = qt_rect_intersect_normalized(*src++, r);
1265 if (dest->isEmpty())
1266 continue;
1267
1268 if (numRects == 0) {
1269 extents = *dest;
1270 } else {
1271 extents.setLeft(qMin(extents.left(), dest->left()));
1272 // hw: extents.top() will never change after initialization
1273 //extents.setTop(qMin(extents.top(), dest->top()));
1274 extents.setRight(qMax(extents.right(), dest->right()));
1275 extents.setBottom(qMax(extents.bottom(), dest->bottom()));
1276
1277 const QRect *nextToLast = (numRects > 1 ? dest - 2 : nullptr);
1278
1279 // mergeFromBelow inlined and optimized
1280 if (canMergeFromBelow(dest - 1, dest, nextToLast, nullptr)) {
1281 if (!n || src->y() != dest->y() || src->left() > r.right()) {
1282 QRect *prev = dest - 1;
1283 prev->setBottom(dest->bottom());
1284 updateInnerRect(*prev);
1285 continue;
1286 }
1287 }
1288 }
1289 updateInnerRect(*dest);
1290 ++dest;
1291 ++numRects;
1292 }
1293#ifdef QT_REGION_DEBUG
1294 selfTest();
1295#endif
1296}
1297
1298void QRegionPrivate::append(const QRect *r)
1299{
1300 Q_ASSERT(!r->isEmpty());
1301
1302 QRect *myLast = (numRects == 1 ? &extents : rects.data() + (numRects - 1));
1303 if (mergeFromRight(myLast, r)) {
1304 if (numRects > 1) {
1305 const QRect *nextToTop = (numRects > 2 ? myLast - 2 : nullptr);
1306 if (mergeFromBelow(myLast - 1, myLast, nextToTop, nullptr))
1307 --numRects;
1308 }
1309 } else if (mergeFromBelow(myLast, r, (numRects > 1 ? myLast - 1 : nullptr), nullptr)) {
1310 // nothing
1311 } else {
1313 ++numRects;
1315 if (rects.size() < numRects)
1316 rects.resize(numRects);
1317 rects[numRects - 1] = *r;
1318 }
1319 extents.setCoords(qMin(extents.left(), r->left()),
1320 qMin(extents.top(), r->top()),
1321 qMax(extents.right(), r->right()),
1322 qMax(extents.bottom(), r->bottom()));
1323
1324#ifdef QT_REGION_DEBUG
1325 selfTest();
1326#endif
1327}
1328
1330{
1331 Q_ASSERT(!isEmptyHelper(r));
1332
1333 if (r->numRects == 1) {
1334 append(&r->extents);
1335 return;
1336 }
1337
1339
1340 QRect *destRect = rects.data() + numRects;
1341 const QRect *srcRect = r->rects.constData();
1342 int numAppend = r->numRects;
1343
1344 // try merging
1345 {
1346 const QRect *rFirst = srcRect;
1347 QRect *myLast = destRect - 1;
1348 const QRect *nextToLast = (numRects > 1 ? myLast - 1 : nullptr);
1349 if (mergeFromRight(myLast, rFirst)) {
1350 ++srcRect;
1351 --numAppend;
1352 const QRect *rNextToFirst = (numAppend > 1 ? rFirst + 2 : nullptr);
1353 if (mergeFromBelow(myLast, rFirst + 1, nextToLast, rNextToFirst)) {
1354 ++srcRect;
1355 --numAppend;
1356 }
1357 if (numRects > 1) {
1358 nextToLast = (numRects > 2 ? myLast - 2 : nullptr);
1359 rNextToFirst = (numAppend > 0 ? srcRect : nullptr);
1360 if (mergeFromBelow(myLast - 1, myLast, nextToLast, rNextToFirst)) {
1361 --destRect;
1362 --numRects;
1363 }
1364 }
1365 } else if (mergeFromBelow(myLast, rFirst, nextToLast, rFirst + 1)) {
1366 ++srcRect;
1367 --numAppend;
1368 }
1369 }
1370
1371 // append rectangles
1372 if (numAppend > 0) {
1373 const int newNumRects = numRects + numAppend;
1374 if (newNumRects > rects.size()) {
1375 rects.resize(newNumRects);
1376 destRect = rects.data() + numRects;
1377 }
1378 memcpy(destRect, srcRect, numAppend * sizeof(QRect));
1379
1380 numRects = newNumRects;
1381 }
1382
1383 // update inner rectangle
1384 if (innerArea < r->innerArea) {
1386 innerRect = r->innerRect;
1387 }
1388
1389 // update extents
1390 destRect = &extents;
1391 srcRect = &r->extents;
1392 extents.setCoords(qMin(destRect->left(), srcRect->left()),
1393 qMin(destRect->top(), srcRect->top()),
1394 qMax(destRect->right(), srcRect->right()),
1395 qMax(destRect->bottom(), srcRect->bottom()));
1396
1397#ifdef QT_REGION_DEBUG
1398 selfTest();
1399#endif
1400}
1401
1403{
1404 Q_ASSERT(!isEmptyHelper(r));
1405
1406 if (r->numRects == 1) {
1407 prepend(&r->extents);
1408 return;
1409 }
1410
1412
1413 int numPrepend = r->numRects;
1414 int numSkip = 0;
1415
1416 // try merging
1417 {
1418 QRect *myFirst = rects.data();
1419 const QRect *nextToFirst = (numRects > 1 ? myFirst + 1 : nullptr);
1420 const QRect *rLast = r->rects.constData() + r->numRects - 1;
1421 const QRect *rNextToLast = (r->numRects > 1 ? rLast - 1 : nullptr);
1422 if (mergeFromLeft(myFirst, rLast)) {
1423 --numPrepend;
1424 --rLast;
1425 rNextToLast = (numPrepend > 1 ? rLast - 1 : nullptr);
1426 if (mergeFromAbove(myFirst, rLast, nextToFirst, rNextToLast)) {
1427 --numPrepend;
1428 --rLast;
1429 }
1430 if (numRects > 1) {
1431 nextToFirst = (numRects > 2? myFirst + 2 : nullptr);
1432 rNextToLast = (numPrepend > 0 ? rLast : nullptr);
1433 if (mergeFromAbove(myFirst + 1, myFirst, nextToFirst, rNextToLast)) {
1434 --numRects;
1435 ++numSkip;
1436 }
1437 }
1438 } else if (mergeFromAbove(myFirst, rLast, nextToFirst, rNextToLast)) {
1439 --numPrepend;
1440 }
1441 }
1442
1443 if (numPrepend > 0) {
1444 const int newNumRects = numRects + numPrepend;
1445 if (newNumRects > rects.size())
1446 rects.resize(newNumRects);
1447
1448 // move existing rectangles
1449 memmove(rects.data() + numPrepend, rects.constData() + numSkip,
1450 numRects * sizeof(QRect));
1451
1452 // prepend new rectangles
1453 memcpy(rects.data(), r->rects.constData(), numPrepend * sizeof(QRect));
1454
1455 numRects = newNumRects;
1456 }
1457
1458 // update inner rectangle
1459 if (innerArea < r->innerArea) {
1461 innerRect = r->innerRect;
1462 }
1463
1464 // update extents
1465 extents.setCoords(qMin(extents.left(), r->extents.left()),
1466 qMin(extents.top(), r->extents.top()),
1467 qMax(extents.right(), r->extents.right()),
1468 qMax(extents.bottom(), r->extents.bottom()));
1469
1470#ifdef QT_REGION_DEBUG
1471 selfTest();
1472#endif
1473}
1474
1475void QRegionPrivate::prepend(const QRect *r)
1476{
1477 Q_ASSERT(!r->isEmpty());
1478
1479 QRect *myFirst = (numRects == 1 ? &extents : rects.data());
1480 if (mergeFromLeft(myFirst, r)) {
1481 if (numRects > 1) {
1482 const QRect *nextToFirst = (numRects > 2 ? myFirst + 2 : nullptr);
1483 if (mergeFromAbove(myFirst + 1, myFirst, nextToFirst, nullptr)) {
1484 --numRects;
1485 memmove(rects.data(), rects.constData() + 1,
1486 numRects * sizeof(QRect));
1487 }
1488 }
1489 } else if (mergeFromAbove(myFirst, r, (numRects > 1 ? myFirst + 1 : nullptr), nullptr)) {
1490 // nothing
1491 } else {
1493 ++numRects;
1495 rects.prepend(*r);
1496 }
1497 extents.setCoords(qMin(extents.left(), r->left()),
1498 qMin(extents.top(), r->top()),
1499 qMax(extents.right(), r->right()),
1500 qMax(extents.bottom(), r->bottom()));
1501
1502#ifdef QT_REGION_DEBUG
1503 selfTest();
1504#endif
1505}
1506
1507bool QRegionPrivate::canAppend(const QRect *r) const
1508{
1509 Q_ASSERT(!r->isEmpty());
1510
1511 const QRect *myLast = (numRects == 1) ? &extents : (rects.constData() + (numRects - 1));
1512 if (r->top() > myLast->bottom())
1513 return true;
1514 if (r->top() == myLast->top()
1515 && r->height() == myLast->height()
1516 && r->left() > myLast->right())
1517 {
1518 return true;
1519 }
1520
1521 return false;
1522}
1523
1525{
1526 return canAppend(r->numRects == 1 ? &r->extents : r->rects.constData());
1527}
1528
1529bool QRegionPrivate::canPrepend(const QRect *r) const
1530{
1531 Q_ASSERT(!r->isEmpty());
1532
1533 const QRect *myFirst = (numRects == 1) ? &extents : rects.constData();
1534 if (r->bottom() < myFirst->top()) // not overlapping
1535 return true;
1536 if (r->top() == myFirst->top()
1537 && r->height() == myFirst->height()
1538 && r->right() < myFirst->left())
1539 {
1540 return true;
1541 }
1542
1543 return false;
1544}
1545
1547{
1548 return canPrepend(r->numRects == 1 ? &r->extents : r->rects.constData() + r->numRects - 1);
1549}
1550
1551#ifdef QT_REGION_DEBUG
1552void QRegionPrivate::selfTest() const
1553{
1554 if (numRects == 0) {
1555 Q_ASSERT(extents.isEmpty());
1556 Q_ASSERT(innerRect.isEmpty());
1557 return;
1558 }
1559
1560 Q_ASSERT(innerArea == (innerRect.width() * innerRect.height()));
1561
1562 if (numRects == 1) {
1563 Q_ASSERT(innerRect == extents);
1564 Q_ASSERT(!innerRect.isEmpty());
1565 return;
1566 }
1567
1568 for (int i = 0; i < numRects; ++i) {
1569 const QRect r = rects.at(i);
1570 if ((r.width() * r.height()) > innerArea)
1571 qDebug() << "selfTest(): innerRect" << innerRect << '<' << r;
1572 }
1573
1574 QRect r = rects.first();
1575 for (int i = 1; i < numRects; ++i) {
1576 const QRect r2 = rects.at(i);
1577 Q_ASSERT(!r2.isEmpty());
1578 if (r2.y() == r.y()) {
1579 Q_ASSERT(r.bottom() == r2.bottom());
1580 Q_ASSERT(r.right() < (r2.left() + 1));
1581 } else {
1582 Q_ASSERT(r2.y() >= r.bottom());
1583 }
1584 r = r2;
1585 }
1586}
1587#endif // QT_REGION_DEBUG
1588
1589Q_CONSTINIT static QRegionPrivate qrp;
1590Q_CONSTINIT const QRegion::QRegionData QRegion::shared_empty = {Q_REFCOUNT_INITIALIZE_STATIC, &qrp};
1591
1592typedef void (*OverlapFunc)(QRegionPrivate &dest, const QRect *r1, const QRect *r1End,
1593 const QRect *r2, const QRect *r2End, int y1, int y2);
1594typedef void (*NonOverlapFunc)(QRegionPrivate &dest, const QRect *r, const QRect *rEnd,
1595 int y1, int y2);
1596
1597static bool EqualRegion(const QRegionPrivate *r1, const QRegionPrivate *r2);
1598static void UnionRegion(const QRegionPrivate *reg1, const QRegionPrivate *reg2, QRegionPrivate &dest);
1599static void miRegionOp(QRegionPrivate &dest, const QRegionPrivate *reg1, const QRegionPrivate *reg2,
1600 OverlapFunc overlapFunc, NonOverlapFunc nonOverlap1Func,
1601 NonOverlapFunc nonOverlap2Func);
1602
1603#define RectangleOut 0
1604#define RectangleIn 1
1605#define RectanglePart 2
1606#define EvenOddRule 0
1607#define WindingRule 1
1608
1609// START OF region.h extract
1610/* $XConsortium: region.h,v 11.14 94/04/17 20:22:20 rws Exp $ */
1611/************************************************************************
1612
1613Copyright (c) 1987 X Consortium
1614
1615Permission is hereby granted, free of charge, to any person obtaining a copy
1616of this software and associated documentation files (the "Software"), to deal
1617in the Software without restriction, including without limitation the rights
1618to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1619copies of the Software, and to permit persons to whom the Software is
1620furnished to do so, subject to the following conditions:
1621
1622The above copyright notice and this permission notice shall be included in
1623all copies or substantial portions of the Software.
1624
1625THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1626IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1627FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1628X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
1629AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1630CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1631
1632Except as contained in this notice, the name of the X Consortium shall not be
1633used in advertising or otherwise to promote the sale, use or other dealings
1634in this Software without prior written authorization from the X Consortium.
1635
1636
1637Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
1638
1639 All Rights Reserved
1640
1641Permission to use, copy, modify, and distribute this software and its
1642documentation for any purpose and without fee is hereby granted,
1643provided that the above copyright notice appear in all copies and that
1644both that copyright notice and this permission notice appear in
1645supporting documentation, and that the name of Digital not be
1646used in advertising or publicity pertaining to distribution of the
1647software without specific, written prior permission.
1648
1649DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
1650ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
1651DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
1652ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
1653WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
1654ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
1655SOFTWARE.
1656
1657************************************************************************/
1658
1659#ifndef _XREGION_H
1660#define _XREGION_H
1661
1662QT_BEGIN_INCLUDE_NAMESPACE
1663#include <limits.h>
1664QT_END_INCLUDE_NAMESPACE
1665
1666/* 1 if two BOXes overlap.
1667 * 0 if two BOXes do not overlap.
1668 * Remember, x2 and y2 are not in the region
1669 */
1670#define EXTENTCHECK(r1, r2)
1671 ((r1)->right() >= (r2)->left() &&
1672 (r1)->left() <= (r2)->right() &&
1673 (r1)->bottom() >= (r2)->top() &&
1674 (r1)->top() <= (r2)->bottom())
1675
1676/*
1677 * update region extents
1678 */
1679#define EXTENTS(r,idRect){
1680 if((r)->left() < (idRect)->extents.left())
1681 (idRect)->extents.setLeft((r)->left());
1682 if((r)->top() < (idRect)->extents.top())
1683 (idRect)->extents.setTop((r)->top());
1684 if((r)->right() > (idRect)->extents.right())
1685 (idRect)->extents.setRight((r)->right());
1686 if((r)->bottom() > (idRect)->extents.bottom())
1687 (idRect)->extents.setBottom((r)->bottom());
1688 }
1689
1690/*
1691 * Check to see if there is enough memory in the present region.
1692 */
1693#define MEMCHECK(dest, rect, firstrect){
1694 if ((dest).numRects >= ((dest).rects.size()-1)){
1695 firstrect.resize(firstrect.size() * 2);
1696 (rect) = (firstrect).data() + (dest).numRects;
1697 }
1698 }
1699
1700
1701/*
1702 * number of points to buffer before sending them off
1703 * to scanlines(): Must be an even number
1704 */
1705#define NUMPTSTOBUFFER 200
1706
1707/*
1708 * used to allocate buffers for points and link
1709 * the buffers together
1710 */
1711typedef struct _POINTBLOCK {
1712 char data[NUMPTSTOBUFFER * sizeof(QPoint)];
1715} POINTBLOCK;
1716
1717#endif
1718// END OF region.h extract
1719
1720// START OF Region.c extract
1721/* $XConsortium: Region.c /main/30 1996/10/22 14:21:24 kaleb $ */
1722/************************************************************************
1723
1724Copyright (c) 1987, 1988 X Consortium
1725
1726Permission is hereby granted, free of charge, to any person obtaining a copy
1727of this software and associated documentation files (the "Software"), to deal
1728in the Software without restriction, including without limitation the rights
1729to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1730copies of the Software, and to permit persons to whom the Software is
1731furnished to do so, subject to the following conditions:
1732
1733The above copyright notice and this permission notice shall be included in
1734all copies or substantial portions of the Software.
1735
1736THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1737IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1738FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1739X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
1740AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1741CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1742
1743Except as contained in this notice, the name of the X Consortium shall not be
1744used in advertising or otherwise to promote the sale, use or other dealings
1745in this Software without prior written authorization from the X Consortium.
1746
1747
1748Copyright 1987, 1988 by Digital Equipment Corporation, Maynard, Massachusetts.
1749
1750 All Rights Reserved
1751
1752Permission to use, copy, modify, and distribute this software and its
1753documentation for any purpose and without fee is hereby granted,
1754provided that the above copyright notice appear in all copies and that
1755both that copyright notice and this permission notice appear in
1756supporting documentation, and that the name of Digital not be
1757used in advertising or publicity pertaining to distribution of the
1758software without specific, written prior permission.
1759
1760DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
1761ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
1762DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
1763ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
1764WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
1765ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
1766SOFTWARE.
1767
1768************************************************************************/
1769/*
1770 * The functions in this file implement the Region abstraction, similar to one
1771 * used in the X11 sample server. A Region is simply an area, as the name
1772 * implies, and is implemented as a "y-x-banded" array of rectangles. To
1773 * explain: Each Region is made up of a certain number of rectangles sorted
1774 * by y coordinate first, and then by x coordinate.
1775 *
1776 * Furthermore, the rectangles are banded such that every rectangle with a
1777 * given upper-left y coordinate (y1) will have the same lower-right y
1778 * coordinate (y2) and vice versa. If a rectangle has scanlines in a band, it
1779 * will span the entire vertical distance of the band. This means that some
1780 * areas that could be merged into a taller rectangle will be represented as
1781 * several shorter rectangles to account for shorter rectangles to its left
1782 * or right but within its "vertical scope".
1783 *
1784 * An added constraint on the rectangles is that they must cover as much
1785 * horizontal area as possible. E.g. no two rectangles in a band are allowed
1786 * to touch.
1787 *
1788 * Whenever possible, bands will be merged together to cover a greater vertical
1789 * distance (and thus reduce the number of rectangles). Two bands can be merged
1790 * only if the bottom of one touches the top of the other and they have
1791 * rectangles in the same places (of the same width, of course). This maintains
1792 * the y-x-banding that's so nice to have...
1793 */
1794/* $XFree86: xc/lib/X11/Region.c,v 1.1.1.2.2.2 1998/10/04 15:22:50 hohndel Exp $ */
1795
1796static void UnionRectWithRegion(const QRect *rect, const QRegionPrivate *source,
1797 QRegionPrivate &dest)
1798{
1799 if (rect->isEmpty())
1800 return;
1801
1802 Q_ASSERT(EqualRegion(source, &dest));
1803
1804 if (dest.numRects == 0) {
1805 dest = QRegionPrivate(*rect);
1806 } else if (dest.canAppend(rect)) {
1807 dest.append(rect);
1808 } else {
1809 QRegionPrivate p(*rect);
1810 UnionRegion(&p, source, dest);
1811 }
1812}
1813
1814/*-
1815 *-----------------------------------------------------------------------
1816 * miSetExtents --
1817 * Reset the extents and innerRect of a region to what they should be.
1818 * Called by miSubtract and miIntersect b/c they can't figure it out
1819 * along the way or do so easily, as miUnion can.
1820 *
1821 * Results:
1822 * None.
1823 *
1824 * Side Effects:
1825 * The region's 'extents' and 'innerRect' structure is overwritten.
1826 *
1827 *-----------------------------------------------------------------------
1828 */
1830{
1831 const QRect *pBox,
1832 *pBoxEnd;
1833 QRect *pExtents;
1834
1835 dest.innerRect.setCoords(0, 0, -1, -1);
1836 dest.innerArea = -1;
1837 if (dest.numRects == 0) {
1838 dest.extents.setCoords(0, 0, -1, -1);
1839 return;
1840 }
1841
1842 pExtents = &dest.extents;
1843 if (dest.rects.isEmpty())
1844 pBox = &dest.extents;
1845 else
1846 pBox = dest.rects.constData();
1847 pBoxEnd = pBox + dest.numRects - 1;
1848
1849 /*
1850 * Since pBox is the first rectangle in the region, it must have the
1851 * smallest y1 and since pBoxEnd is the last rectangle in the region,
1852 * it must have the largest y2, because of banding. Initialize x1 and
1853 * x2 from pBox and pBoxEnd, resp., as good things to initialize them
1854 * to...
1855 */
1856 pExtents->setLeft(pBox->left());
1857 pExtents->setTop(pBox->top());
1858 pExtents->setRight(pBoxEnd->right());
1859 pExtents->setBottom(pBoxEnd->bottom());
1860
1861 Q_ASSERT(pExtents->top() <= pExtents->bottom());
1862 while (pBox <= pBoxEnd) {
1863 if (pBox->left() < pExtents->left())
1864 pExtents->setLeft(pBox->left());
1865 if (pBox->right() > pExtents->right())
1866 pExtents->setRight(pBox->right());
1867 dest.updateInnerRect(*pBox);
1868 ++pBox;
1869 }
1870 Q_ASSERT(pExtents->left() <= pExtents->right());
1871}
1872
1873/* TranslateRegion(pRegion, x, y)
1874 translates in place
1875 added by raymond
1876*/
1877
1878static void OffsetRegion(QRegionPrivate &region, int x, int y)
1879{
1880 if (region.rects.size()) {
1881 QRect *pbox = region.rects.data();
1882 int nbox = region.numRects;
1883
1884 while (nbox--) {
1885 pbox->translate(x, y);
1886 ++pbox;
1887 }
1888 }
1889 region.extents.translate(x, y);
1890 region.innerRect.translate(x, y);
1891}
1892
1893/*======================================================================
1894 * Region Intersection
1895 *====================================================================*/
1896/*-
1897 *-----------------------------------------------------------------------
1898 * miIntersectO --
1899 * Handle an overlapping band for miIntersect.
1900 *
1901 * Results:
1902 * None.
1903 *
1904 * Side Effects:
1905 * Rectangles may be added to the region.
1906 *
1907 *-----------------------------------------------------------------------
1908 */
1909static void miIntersectO(QRegionPrivate &dest, const QRect *r1, const QRect *r1End,
1910 const QRect *r2, const QRect *r2End, int y1, int y2)
1911{
1912 int x1;
1913 int x2;
1914 QRect *pNextRect;
1915
1916 pNextRect = dest.rects.data() + dest.numRects;
1917
1918 while (r1 != r1End && r2 != r2End) {
1919 x1 = qMax(r1->left(), r2->left());
1920 x2 = qMin(r1->right(), r2->right());
1921
1922 /*
1923 * If there's any overlap between the two rectangles, add that
1924 * overlap to the new region.
1925 * There's no need to check for subsumption because the only way
1926 * such a need could arise is if some region has two rectangles
1927 * right next to each other. Since that should never happen...
1928 */
1929 if (x1 <= x2) {
1930 Q_ASSERT(y1 <= y2);
1931 MEMCHECK(dest, pNextRect, dest.rects)
1932 pNextRect->setCoords(x1, y1, x2, y2);
1933 ++dest.numRects;
1934 ++pNextRect;
1935 }
1936
1937 /*
1938 * Need to advance the pointers. Shift the one that extends
1939 * to the right the least, since the other still has a chance to
1940 * overlap with that region's next rectangle, if you see what I mean.
1941 */
1942 if (r1->right() < r2->right()) {
1943 ++r1;
1944 } else if (r2->right() < r1->right()) {
1945 ++r2;
1946 } else {
1947 ++r1;
1948 ++r2;
1949 }
1950 }
1951}
1952
1953/*======================================================================
1954 * Generic Region Operator
1955 *====================================================================*/
1956
1957/*-
1958 *-----------------------------------------------------------------------
1959 * miCoalesce --
1960 * Attempt to merge the boxes in the current band with those in the
1961 * previous one. Used only by miRegionOp.
1962 *
1963 * Results:
1964 * The new index for the previous band.
1965 *
1966 * Side Effects:
1967 * If coalescing takes place:
1968 * - rectangles in the previous band will have their y2 fields
1969 * altered.
1970 * - dest.numRects will be decreased.
1971 *
1972 *-----------------------------------------------------------------------
1973 */
1974static int miCoalesce(QRegionPrivate &dest, int prevStart, int curStart)
1975{
1976 QRect *pPrevBox; /* Current box in previous band */
1977 QRect *pCurBox; /* Current box in current band */
1978 QRect *pRegEnd; /* End of region */
1979 int curNumRects; /* Number of rectangles in current band */
1980 int prevNumRects; /* Number of rectangles in previous band */
1981 int bandY1; /* Y1 coordinate for current band */
1982 QRect *rData = dest.rects.data();
1983
1984 pRegEnd = rData + dest.numRects;
1985
1986 pPrevBox = rData + prevStart;
1987 prevNumRects = curStart - prevStart;
1988
1989 /*
1990 * Figure out how many rectangles are in the current band. Have to do
1991 * this because multiple bands could have been added in miRegionOp
1992 * at the end when one region has been exhausted.
1993 */
1994 pCurBox = rData + curStart;
1995 bandY1 = pCurBox->top();
1996 for (curNumRects = 0; pCurBox != pRegEnd && pCurBox->top() == bandY1; ++curNumRects) {
1997 ++pCurBox;
1998 }
1999
2000 if (pCurBox != pRegEnd) {
2001 /*
2002 * If more than one band was added, we have to find the start
2003 * of the last band added so the next coalescing job can start
2004 * at the right place... (given when multiple bands are added,
2005 * this may be pointless -- see above).
2006 */
2007 --pRegEnd;
2008 while ((pRegEnd - 1)->top() == pRegEnd->top())
2009 --pRegEnd;
2010 curStart = pRegEnd - rData;
2011 pRegEnd = rData + dest.numRects;
2012 }
2013
2014 if (curNumRects == prevNumRects && curNumRects != 0) {
2015 pCurBox -= curNumRects;
2016 /*
2017 * The bands may only be coalesced if the bottom of the previous
2018 * matches the top scanline of the current.
2019 */
2020 if (pPrevBox->bottom() == pCurBox->top() - 1) {
2021 /*
2022 * Make sure the bands have boxes in the same places. This
2023 * assumes that boxes have been added in such a way that they
2024 * cover the most area possible. I.e. two boxes in a band must
2025 * have some horizontal space between them.
2026 */
2027 do {
2028 if (pPrevBox->left() != pCurBox->left() || pPrevBox->right() != pCurBox->right()) {
2029 // The bands don't line up so they can't be coalesced.
2030 return curStart;
2031 }
2032 ++pPrevBox;
2033 ++pCurBox;
2034 --prevNumRects;
2035 } while (prevNumRects != 0);
2036
2037 dest.numRects -= curNumRects;
2038 pCurBox -= curNumRects;
2039 pPrevBox -= curNumRects;
2040
2041 /*
2042 * The bands may be merged, so set the bottom y of each box
2043 * in the previous band to that of the corresponding box in
2044 * the current band.
2045 */
2046 do {
2047 pPrevBox->setBottom(pCurBox->bottom());
2048 dest.updateInnerRect(*pPrevBox);
2049 ++pPrevBox;
2050 ++pCurBox;
2051 curNumRects -= 1;
2052 } while (curNumRects != 0);
2053
2054 /*
2055 * If only one band was added to the region, we have to backup
2056 * curStart to the start of the previous band.
2057 *
2058 * If more than one band was added to the region, copy the
2059 * other bands down. The assumption here is that the other bands
2060 * came from the same region as the current one and no further
2061 * coalescing can be done on them since it's all been done
2062 * already... curStart is already in the right place.
2063 */
2064 if (pCurBox == pRegEnd) {
2065 curStart = prevStart;
2066 } else {
2067 do {
2068 *pPrevBox++ = *pCurBox++;
2069 dest.updateInnerRect(*pPrevBox);
2070 } while (pCurBox != pRegEnd);
2071 }
2072 }
2073 }
2074 return curStart;
2075}
2076
2077/*-
2078 *-----------------------------------------------------------------------
2079 * miRegionOp --
2080 * Apply an operation to two regions. Called by miUnion, miInverse,
2081 * miSubtract, miIntersect...
2082 *
2083 * Results:
2084 * None.
2085 *
2086 * Side Effects:
2087 * The new region is overwritten.
2088 *
2089 * Notes:
2090 * The idea behind this function is to view the two regions as sets.
2091 * Together they cover a rectangle of area that this function divides
2092 * into horizontal bands where points are covered only by one region
2093 * or by both. For the first case, the nonOverlapFunc is called with
2094 * each the band and the band's upper and lower extents. For the
2095 * second, the overlapFunc is called to process the entire band. It
2096 * is responsible for clipping the rectangles in the band, though
2097 * this function provides the boundaries.
2098 * At the end of each band, the new region is coalesced, if possible,
2099 * to reduce the number of rectangles in the region.
2100 *
2101 *-----------------------------------------------------------------------
2102 */
2103static void miRegionOp(QRegionPrivate &dest,
2104 const QRegionPrivate *reg1, const QRegionPrivate *reg2,
2105 OverlapFunc overlapFunc, NonOverlapFunc nonOverlap1Func,
2106 NonOverlapFunc nonOverlap2Func)
2107{
2108 const QRect *r1; // Pointer into first region
2109 const QRect *r2; // Pointer into 2d region
2110 const QRect *r1End; // End of 1st region
2111 const QRect *r2End; // End of 2d region
2112 int ybot; // Bottom of intersection
2113 int ytop; // Top of intersection
2114 int prevBand; // Index of start of previous band in dest
2115 int curBand; // Index of start of current band in dest
2116 const QRect *r1BandEnd; // End of current band in r1
2117 const QRect *r2BandEnd; // End of current band in r2
2118 int top; // Top of non-overlapping band
2119 int bot; // Bottom of non-overlapping band
2120
2121 /*
2122 * Initialization:
2123 * set r1, r2, r1End and r2End appropriately, preserve the important
2124 * parts of the destination region until the end in case it's one of
2125 * the two source regions, then mark the "new" region empty, allocating
2126 * another array of rectangles for it to use.
2127 */
2128 if (reg1->numRects == 1)
2129 r1 = &reg1->extents;
2130 else
2131 r1 = reg1->rects.constData();
2132 if (reg2->numRects == 1)
2133 r2 = &reg2->extents;
2134 else
2135 r2 = reg2->rects.constData();
2136
2137 r1End = r1 + reg1->numRects;
2138 r2End = r2 + reg2->numRects;
2139
2140 dest.vectorize();
2141
2142 /*
2143 * The following calls are going to detach dest.rects. Since dest might be
2144 * aliasing *reg1 and/or *reg2, and we could have active iterators on
2145 * reg1->rects and reg2->rects (if the regions have more than 1 rectangle),
2146 * take a copy of dest.rects to keep those iteractors valid.
2147 */
2148 const QList<QRect> destRectsCopy = dest.rects;
2149 Q_UNUSED(destRectsCopy);
2150
2151 dest.numRects = 0;
2152
2153 /*
2154 * Allocate a reasonable number of rectangles for the new region. The idea
2155 * is to allocate enough so the individual functions don't need to
2156 * reallocate and copy the array, which is time consuming, yet we don't
2157 * have to worry about using too much memory. I hope to be able to
2158 * nuke the realloc() at the end of this function eventually.
2159 */
2160 dest.rects.resize(qMax(reg1->numRects,reg2->numRects) * 2);
2161
2162 /*
2163 * Initialize ybot and ytop.
2164 * In the upcoming loop, ybot and ytop serve different functions depending
2165 * on whether the band being handled is an overlapping or non-overlapping
2166 * band.
2167 * In the case of a non-overlapping band (only one of the regions
2168 * has points in the band), ybot is the bottom of the most recent
2169 * intersection and thus clips the top of the rectangles in that band.
2170 * ytop is the top of the next intersection between the two regions and
2171 * serves to clip the bottom of the rectangles in the current band.
2172 * For an overlapping band (where the two regions intersect), ytop clips
2173 * the top of the rectangles of both regions and ybot clips the bottoms.
2174 */
2175 if (reg1->extents.top() < reg2->extents.top())
2176 ybot = reg1->extents.top() - 1;
2177 else
2178 ybot = reg2->extents.top() - 1;
2179
2180 /*
2181 * prevBand serves to mark the start of the previous band so rectangles
2182 * can be coalesced into larger rectangles. qv. miCoalesce, above.
2183 * In the beginning, there is no previous band, so prevBand == curBand
2184 * (curBand is set later on, of course, but the first band will always
2185 * start at index 0). prevBand and curBand must be indices because of
2186 * the possible expansion, and resultant moving, of the new region's
2187 * array of rectangles.
2188 */
2189 prevBand = 0;
2190
2191 do {
2192 curBand = dest.numRects;
2193
2194 /*
2195 * This algorithm proceeds one source-band (as opposed to a
2196 * destination band, which is determined by where the two regions
2197 * intersect) at a time. r1BandEnd and r2BandEnd serve to mark the
2198 * rectangle after the last one in the current band for their
2199 * respective regions.
2200 */
2201 r1BandEnd = r1;
2202 while (r1BandEnd != r1End && r1BandEnd->top() == r1->top())
2203 ++r1BandEnd;
2204
2205 r2BandEnd = r2;
2206 while (r2BandEnd != r2End && r2BandEnd->top() == r2->top())
2207 ++r2BandEnd;
2208
2209 /*
2210 * First handle the band that doesn't intersect, if any.
2211 *
2212 * Note that attention is restricted to one band in the
2213 * non-intersecting region at once, so if a region has n
2214 * bands between the current position and the next place it overlaps
2215 * the other, this entire loop will be passed through n times.
2216 */
2217 if (r1->top() < r2->top()) {
2218 top = qMax(r1->top(), ybot + 1);
2219 bot = qMin(r1->bottom(), r2->top() - 1);
2220
2221 if (nonOverlap1Func != nullptr && bot >= top)
2222 (*nonOverlap1Func)(dest, r1, r1BandEnd, top, bot);
2223 ytop = r2->top();
2224 } else if (r2->top() < r1->top()) {
2225 top = qMax(r2->top(), ybot + 1);
2226 bot = qMin(r2->bottom(), r1->top() - 1);
2227
2228 if (nonOverlap2Func != nullptr && bot >= top)
2229 (*nonOverlap2Func)(dest, r2, r2BandEnd, top, bot);
2230 ytop = r1->top();
2231 } else {
2232 ytop = r1->top();
2233 }
2234
2235 /*
2236 * If any rectangles got added to the region, try and coalesce them
2237 * with rectangles from the previous band. Note we could just do
2238 * this test in miCoalesce, but some machines incur a not
2239 * inconsiderable cost for function calls, so...
2240 */
2241 if (dest.numRects != curBand)
2242 prevBand = miCoalesce(dest, prevBand, curBand);
2243
2244 /*
2245 * Now see if we've hit an intersecting band. The two bands only
2246 * intersect if ybot >= ytop
2247 */
2248 ybot = qMin(r1->bottom(), r2->bottom());
2249 curBand = dest.numRects;
2250 if (ybot >= ytop)
2251 (*overlapFunc)(dest, r1, r1BandEnd, r2, r2BandEnd, ytop, ybot);
2252
2253 if (dest.numRects != curBand)
2254 prevBand = miCoalesce(dest, prevBand, curBand);
2255
2256 /*
2257 * If we've finished with a band (y2 == ybot) we skip forward
2258 * in the region to the next band.
2259 */
2260 if (r1->bottom() == ybot)
2261 r1 = r1BandEnd;
2262 if (r2->bottom() == ybot)
2263 r2 = r2BandEnd;
2264 } while (r1 != r1End && r2 != r2End);
2265
2266 /*
2267 * Deal with whichever region still has rectangles left.
2268 */
2269 curBand = dest.numRects;
2270 if (r1 != r1End) {
2271 if (nonOverlap1Func != nullptr) {
2272 do {
2273 r1BandEnd = r1;
2274 while (r1BandEnd < r1End && r1BandEnd->top() == r1->top())
2275 ++r1BandEnd;
2276 (*nonOverlap1Func)(dest, r1, r1BandEnd, qMax(r1->top(), ybot + 1), r1->bottom());
2277 r1 = r1BandEnd;
2278 } while (r1 != r1End);
2279 }
2280 } else if ((r2 != r2End) && (nonOverlap2Func != nullptr)) {
2281 do {
2282 r2BandEnd = r2;
2283 while (r2BandEnd < r2End && r2BandEnd->top() == r2->top())
2284 ++r2BandEnd;
2285 (*nonOverlap2Func)(dest, r2, r2BandEnd, qMax(r2->top(), ybot + 1), r2->bottom());
2286 r2 = r2BandEnd;
2287 } while (r2 != r2End);
2288 }
2289
2290 if (dest.numRects != curBand)
2291 (void)miCoalesce(dest, prevBand, curBand);
2292
2293 /*
2294 * A bit of cleanup. To keep regions from growing without bound,
2295 * we shrink the array of rectangles to match the new number of
2296 * rectangles in the region.
2297 *
2298 * Only do this stuff if the number of rectangles allocated is more than
2299 * twice the number of rectangles in the region (a simple optimization).
2300 */
2301 if (qMax(4, dest.numRects) < (dest.rects.size() >> 1))
2302 dest.rects.resize(dest.numRects);
2303}
2304
2305/*======================================================================
2306 * Region Union
2307 *====================================================================*/
2308
2309/*-
2310 *-----------------------------------------------------------------------
2311 * miUnionNonO --
2312 * Handle a non-overlapping band for the union operation. Just
2313 * Adds the rectangles into the region. Doesn't have to check for
2314 * subsumption or anything.
2315 *
2316 * Results:
2317 * None.
2318 *
2319 * Side Effects:
2320 * dest.numRects is incremented and the final rectangles overwritten
2321 * with the rectangles we're passed.
2322 *
2323 *-----------------------------------------------------------------------
2324 */
2325
2326static void miUnionNonO(QRegionPrivate &dest, const QRect *r, const QRect *rEnd,
2327 int y1, int y2)
2328{
2329 QRect *pNextRect;
2330
2331 pNextRect = dest.rects.data() + dest.numRects;
2332
2333 Q_ASSERT(y1 <= y2);
2334
2335 while (r != rEnd) {
2336 Q_ASSERT(r->left() <= r->right());
2337 MEMCHECK(dest, pNextRect, dest.rects)
2338 pNextRect->setCoords(r->left(), y1, r->right(), y2);
2339 dest.numRects++;
2340 ++pNextRect;
2341 ++r;
2342 }
2343}
2344
2345
2346/*-
2347 *-----------------------------------------------------------------------
2348 * miUnionO --
2349 * Handle an overlapping band for the union operation. Picks the
2350 * left-most rectangle each time and merges it into the region.
2351 *
2352 * Results:
2353 * None.
2354 *
2355 * Side Effects:
2356 * Rectangles are overwritten in dest.rects and dest.numRects will
2357 * be changed.
2358 *
2359 *-----------------------------------------------------------------------
2360 */
2361
2362static void miUnionO(QRegionPrivate &dest, const QRect *r1, const QRect *r1End,
2363 const QRect *r2, const QRect *r2End, int y1, int y2)
2364{
2365 QRect *pNextRect;
2366
2367 pNextRect = dest.rects.data() + dest.numRects;
2368
2369#define MERGERECT(r)
2370 if ((dest.numRects != 0) &&
2371 (pNextRect[-1].top() == y1) &&
2372 (pNextRect[-1].bottom() == y2) &&
2373 (pNextRect[-1].right() >= r->left()-1)) {
2374 if (pNextRect[-1].right() < r->right()) {
2375 pNextRect[-1].setRight(r->right());
2376 dest.updateInnerRect(pNextRect[-1]);
2377 Q_ASSERT(pNextRect[-1].left() <= pNextRect[-1].right());
2378 }
2379 } else {
2380 MEMCHECK(dest, pNextRect, dest.rects)
2381 pNextRect->setCoords(r->left(), y1, r->right(), y2);
2382 dest.updateInnerRect(*pNextRect);
2383 dest.numRects++;
2384 pNextRect++;
2385 }
2386 r++;
2387
2388 Q_ASSERT(y1 <= y2);
2389 while (r1 != r1End && r2 != r2End) {
2390 if (r1->left() < r2->left()) {
2391 MERGERECT(r1)
2392 } else {
2393 MERGERECT(r2)
2394 }
2395 }
2396
2397 if (r1 != r1End) {
2398 do {
2399 MERGERECT(r1)
2400 } while (r1 != r1End);
2401 } else {
2402 while (r2 != r2End) {
2403 MERGERECT(r2)
2404 }
2405 }
2406}
2407
2408static void UnionRegion(const QRegionPrivate *reg1, const QRegionPrivate *reg2, QRegionPrivate &dest)
2409{
2410 Q_ASSERT(!isEmptyHelper(reg1) && !isEmptyHelper(reg2));
2411 Q_ASSERT(!reg1->contains(*reg2));
2412 Q_ASSERT(!reg2->contains(*reg1));
2413 Q_ASSERT(!EqualRegion(reg1, reg2));
2414 Q_ASSERT(!reg1->canAppend(reg2));
2415 Q_ASSERT(!reg2->canAppend(reg1));
2416
2417 if (reg1->innerArea > reg2->innerArea) {
2418 dest.innerArea = reg1->innerArea;
2419 dest.innerRect = reg1->innerRect;
2420 } else {
2421 dest.innerArea = reg2->innerArea;
2422 dest.innerRect = reg2->innerRect;
2423 }
2425
2426 dest.extents.setCoords(qMin(reg1->extents.left(), reg2->extents.left()),
2427 qMin(reg1->extents.top(), reg2->extents.top()),
2428 qMax(reg1->extents.right(), reg2->extents.right()),
2429 qMax(reg1->extents.bottom(), reg2->extents.bottom()));
2430}
2431
2432/*======================================================================
2433 * Region Subtraction
2434 *====================================================================*/
2435
2436/*-
2437 *-----------------------------------------------------------------------
2438 * miSubtractNonO --
2439 * Deal with non-overlapping band for subtraction. Any parts from
2440 * region 2 we discard. Anything from region 1 we add to the region.
2441 *
2442 * Results:
2443 * None.
2444 *
2445 * Side Effects:
2446 * dest may be affected.
2447 *
2448 *-----------------------------------------------------------------------
2449 */
2450
2451static void miSubtractNonO1(QRegionPrivate &dest, const QRect *r,
2452 const QRect *rEnd, int y1, int y2)
2453{
2454 QRect *pNextRect;
2455
2456 pNextRect = dest.rects.data() + dest.numRects;
2457
2458 Q_ASSERT(y1<=y2);
2459
2460 while (r != rEnd) {
2461 Q_ASSERT(r->left() <= r->right());
2462 MEMCHECK(dest, pNextRect, dest.rects)
2463 pNextRect->setCoords(r->left(), y1, r->right(), y2);
2464 ++dest.numRects;
2465 ++pNextRect;
2466 ++r;
2467 }
2468}
2469
2470/*-
2471 *-----------------------------------------------------------------------
2472 * miSubtractO --
2473 * Overlapping band subtraction. x1 is the left-most point not yet
2474 * checked.
2475 *
2476 * Results:
2477 * None.
2478 *
2479 * Side Effects:
2480 * dest may have rectangles added to it.
2481 *
2482 *-----------------------------------------------------------------------
2483 */
2484
2485static void miSubtractO(QRegionPrivate &dest, const QRect *r1, const QRect *r1End,
2486 const QRect *r2, const QRect *r2End, int y1, int y2)
2487{
2488 QRect *pNextRect;
2489 int x1;
2490
2491 x1 = r1->left();
2492
2493 Q_ASSERT(y1 <= y2);
2494 pNextRect = dest.rects.data() + dest.numRects;
2495
2496 while (r1 != r1End && r2 != r2End) {
2497 if (r2->right() < x1) {
2498 /*
2499 * Subtrahend missed the boat: go to next subtrahend.
2500 */
2501 ++r2;
2502 } else if (r2->left() <= x1) {
2503 /*
2504 * Subtrahend precedes minuend: nuke left edge of minuend.
2505 */
2506 x1 = r2->right() + 1;
2507 if (x1 > r1->right()) {
2508 /*
2509 * Minuend completely covered: advance to next minuend and
2510 * reset left fence to edge of new minuend.
2511 */
2512 ++r1;
2513 if (r1 != r1End)
2514 x1 = r1->left();
2515 } else {
2516 // Subtrahend now used up since it doesn't extend beyond minuend
2517 ++r2;
2518 }
2519 } else if (r2->left() <= r1->right()) {
2520 /*
2521 * Left part of subtrahend covers part of minuend: add uncovered
2522 * part of minuend to region and skip to next subtrahend.
2523 */
2524 Q_ASSERT(x1 < r2->left());
2525 MEMCHECK(dest, pNextRect, dest.rects)
2526 pNextRect->setCoords(x1, y1, r2->left() - 1, y2);
2527 ++dest.numRects;
2528 ++pNextRect;
2529
2530 x1 = r2->right() + 1;
2531 if (x1 > r1->right()) {
2532 /*
2533 * Minuend used up: advance to new...
2534 */
2535 ++r1;
2536 if (r1 != r1End)
2537 x1 = r1->left();
2538 } else {
2539 // Subtrahend used up
2540 ++r2;
2541 }
2542 } else {
2543 /*
2544 * Minuend used up: add any remaining piece before advancing.
2545 */
2546 if (r1->right() >= x1) {
2547 MEMCHECK(dest, pNextRect, dest.rects)
2548 pNextRect->setCoords(x1, y1, r1->right(), y2);
2549 ++dest.numRects;
2550 ++pNextRect;
2551 }
2552 ++r1;
2553 if (r1 != r1End)
2554 x1 = r1->left();
2555 }
2556 }
2557
2558 /*
2559 * Add remaining minuend rectangles to region.
2560 */
2561 while (r1 != r1End) {
2562 Q_ASSERT(x1 <= r1->right());
2563 MEMCHECK(dest, pNextRect, dest.rects)
2564 pNextRect->setCoords(x1, y1, r1->right(), y2);
2565 ++dest.numRects;
2566 ++pNextRect;
2567
2568 ++r1;
2569 if (r1 != r1End)
2570 x1 = r1->left();
2571 }
2572}
2573
2574/*-
2575 *-----------------------------------------------------------------------
2576 * miSubtract --
2577 * Subtract regS from regM and leave the result in regD.
2578 * S stands for subtrahend, M for minuend and D for difference.
2579 *
2580 * Side Effects:
2581 * regD is overwritten.
2582 *
2583 *-----------------------------------------------------------------------
2584 */
2585
2587 QRegionPrivate &dest)
2588{
2589 Q_ASSERT(!isEmptyHelper(regM));
2590 Q_ASSERT(!isEmptyHelper(regS));
2591 Q_ASSERT(EXTENTCHECK(&regM->extents, &regS->extents));
2592 Q_ASSERT(!regS->contains(*regM));
2593 Q_ASSERT(!EqualRegion(regM, regS));
2594
2595 miRegionOp(dest, regM, regS, miSubtractO, miSubtractNonO1, nullptr);
2596
2597 /*
2598 * Can't alter dest's extents before we call miRegionOp because
2599 * it might be one of the source regions and miRegionOp depends
2600 * on the extents of those regions being the unaltered. Besides, this
2601 * way there's no checking against rectangles that will be nuked
2602 * due to coalescing, so we have to examine fewer rectangles.
2603 */
2604 miSetExtents(dest);
2605}
2606
2608{
2609 Q_ASSERT(!isEmptyHelper(sra) && !isEmptyHelper(srb));
2610 Q_ASSERT(EXTENTCHECK(&sra->extents, &srb->extents));
2611 Q_ASSERT(!EqualRegion(sra, srb));
2612
2613 QRegionPrivate tra, trb;
2614
2615 if (!srb->contains(*sra))
2616 SubtractRegion(sra, srb, tra);
2617 if (!sra->contains(*srb))
2618 SubtractRegion(srb, sra, trb);
2619
2620 Q_ASSERT(isEmptyHelper(&trb) || !tra.contains(trb));
2621 Q_ASSERT(isEmptyHelper(&tra) || !trb.contains(tra));
2622
2623 if (isEmptyHelper(&tra)) {
2624 dest = trb;
2625 } else if (isEmptyHelper(&trb)) {
2626 dest = tra;
2627 } else if (tra.canAppend(&trb)) {
2628 dest = tra;
2629 dest.append(&trb);
2630 } else if (trb.canAppend(&tra)) {
2631 dest = trb;
2632 dest.append(&tra);
2633 } else {
2634 UnionRegion(&tra, &trb, dest);
2635 }
2636}
2637
2638/*
2639 * Check to see if two regions are equal
2640 */
2641static bool EqualRegion(const QRegionPrivate *r1, const QRegionPrivate *r2)
2642{
2643 if (r1->numRects != r2->numRects) {
2644 return false;
2645 } else if (r1->numRects == 0) {
2646 return true;
2647 } else if (r1->extents != r2->extents) {
2648 return false;
2649 } else if (r1->numRects == 1 && r2->numRects == 1) {
2650 return true; // equality tested in previous if-statement
2651 } else {
2652 const QRect *rr1 = (r1->numRects == 1) ? &r1->extents : r1->rects.constData();
2653 const QRect *rr2 = (r2->numRects == 1) ? &r2->extents : r2->rects.constData();
2654 for (int i = 0; i < r1->numRects; ++i, ++rr1, ++rr2) {
2655 if (*rr1 != *rr2)
2656 return false;
2657 }
2658 }
2659
2660 return true;
2661}
2662
2663namespace {
2664struct ByBottom
2665{
2666 bool operator()(QRect lhs, int rhs) const { return lhs.bottom() < rhs; }
2667 bool operator()(int lhs, QRect rhs) const { return lhs < rhs.bottom(); }
2668 bool operator()(QRect lhs, QRect rhs) const { return lhs.bottom() < rhs.bottom(); }
2669};
2670} // unnamed namespace
2671
2672static bool PointInRegion(QRegionPrivate *pRegion, int x, int y)
2673{
2674 if (isEmptyHelper(pRegion))
2675 return false;
2676 if (!pRegion->extents.contains(x, y))
2677 return false;
2678 if (pRegion->numRects == 1)
2679 return true; // extents already contains(x,y)
2680 if (pRegion->innerRect.contains(x, y))
2681 return true;
2682 // Rects are Y-X banded: sorted by top(), all rects of a band share height,
2683 // and bands never overlap in y, so bottom() is monotonic as well. That makes
2684 // the band containing y the first rect whose bottom() is >= y.
2685 const QRect *pbox = pRegion->rects.constData();
2686 const QRect *pboxEnd = pbox + pRegion->numRects;
2687 pbox = std::lower_bound(pbox, pboxEnd, y, ByBottom());
2688 for (; pbox != pboxEnd; ++pbox) {
2689 // Within a band rects are sorted by left(), and a row belongs to one
2690 // band only, so the first rect starting right of x ends the search.
2691 if (y < pbox->top() || x < pbox->left())
2692 return false;
2693 if (x <= pbox->right())
2694 return true;
2695 }
2696 return false;
2697}
2698
2699static bool RectInRegion(QRegionPrivate *region, int rx, int ry, uint rwidth, uint rheight)
2700{
2701 const QRect *pbox;
2702 const QRect *pboxEnd;
2703 QRect rect(rx, ry, rwidth, rheight);
2704 QRect *prect = &rect;
2705 int partIn, partOut;
2706
2707 if (!region || region->numRects == 0 || !EXTENTCHECK(&region->extents, prect))
2708 return RectangleOut;
2709
2710 partOut = false;
2711 partIn = false;
2712
2713 /* can stop when both partOut and partIn are true, or we reach prect->y2 */
2714 pbox = (region->numRects == 1) ? &region->extents : region->rects.constData();
2715 pboxEnd = pbox + region->numRects;
2716 for (; pbox < pboxEnd; ++pbox) {
2717 if (pbox->bottom() < ry)
2718 continue;
2719
2720 if (pbox->top() > ry) {
2721 partOut = true;
2722 if (partIn || pbox->top() > prect->bottom())
2723 break;
2724 ry = pbox->top();
2725 }
2726
2727 if (pbox->right() < rx)
2728 continue; /* not far enough over yet */
2729
2730 if (pbox->left() > rx) {
2731 partOut = true; /* missed part of rectangle to left */
2732 if (partIn)
2733 break;
2734 }
2735
2736 if (pbox->left() <= prect->right()) {
2737 partIn = true; /* definitely overlap */
2738 if (partOut)
2739 break;
2740 }
2741
2742 if (pbox->right() >= prect->right()) {
2743 ry = pbox->bottom() + 1; /* finished with this band */
2744 if (ry > prect->bottom())
2745 break;
2746 rx = prect->left(); /* reset x out to left again */
2747 } else {
2748 /*
2749 * Because boxes in a band are maximal width, if the first box
2750 * to overlap the rectangle doesn't completely cover it in that
2751 * band, the rectangle must be partially out, since some of it
2752 * will be uncovered in that band. partIn will have been set true
2753 * by now...
2754 */
2755 break;
2756 }
2757 }
2758 return partIn;
2759}
2760// END OF Region.c extract
2761// START OF poly.h extract
2762/* $XConsortium: poly.h,v 1.4 94/04/17 20:22:19 rws Exp $ */
2763/************************************************************************
2764
2765Copyright (c) 1987 X Consortium
2766
2767Permission is hereby granted, free of charge, to any person obtaining a copy
2768of this software and associated documentation files (the "Software"), to deal
2769in the Software without restriction, including without limitation the rights
2770to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2771copies of the Software, and to permit persons to whom the Software is
2772furnished to do so, subject to the following conditions:
2773
2774The above copyright notice and this permission notice shall be included in
2775all copies or substantial portions of the Software.
2776
2777THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2778IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2779FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2780X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
2781AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2782CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2783
2784Except as contained in this notice, the name of the X Consortium shall not be
2785used in advertising or otherwise to promote the sale, use or other dealings
2786in this Software without prior written authorization from the X Consortium.
2787
2788
2789Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
2790
2791 All Rights Reserved
2792
2793Permission to use, copy, modify, and distribute this software and its
2794documentation for any purpose and without fee is hereby granted,
2795provided that the above copyright notice appear in all copies and that
2796both that copyright notice and this permission notice appear in
2797supporting documentation, and that the name of Digital not be
2798used in advertising or publicity pertaining to distribution of the
2799software without specific, written prior permission.
2800
2801DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
2802ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
2803DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
2804ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
2805WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
2806ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
2807SOFTWARE.
2808
2809************************************************************************/
2810
2811/*
2812 * This file contains a few macros to help track
2813 * the edge of a filled object. The object is assumed
2814 * to be filled in scanline order, and thus the
2815 * algorithm used is an extension of Bresenham's line
2816 * drawing algorithm which assumes that y is always the
2817 * major axis.
2818 * Since these pieces of code are the same for any filled shape,
2819 * it is more convenient to gather the library in one
2820 * place, but since these pieces of code are also in
2821 * the inner loops of output primitives, procedure call
2822 * overhead is out of the question.
2823 * See the author for a derivation if needed.
2824 */
2825
2826
2827/*
2828 * In scan converting polygons, we want to choose those pixels
2829 * which are inside the polygon. Thus, we add .5 to the starting
2830 * x coordinate for both left and right edges. Now we choose the
2831 * first pixel which is inside the pgon for the left edge and the
2832 * first pixel which is outside the pgon for the right edge.
2833 * Draw the left pixel, but not the right.
2834 *
2835 * How to add .5 to the starting x coordinate:
2836 * If the edge is moving to the right, then subtract dy from the
2837 * error term from the general form of the algorithm.
2838 * If the edge is moving to the left, then add dy to the error term.
2839 *
2840 * The reason for the difference between edges moving to the left
2841 * and edges moving to the right is simple: If an edge is moving
2842 * to the right, then we want the algorithm to flip immediately.
2843 * If it is moving to the left, then we don't want it to flip until
2844 * we traverse an entire pixel.
2845 */
2846#define BRESINITPGON(dy, x1, x2, xStart, d, m, m1, incr1, incr2) {
2847 int dx; /* local storage */
2848
2849 /* \
2850 * if the edge is horizontal, then it is ignored \
2851 * and assumed not to be processed. Otherwise, do this stuff. \
2852 */
2853 if ((dy) != 0) {
2854 xStart = (x1);
2855 dx = (x2) - xStart;
2856 if (dx < 0) {
2857 m = dx / (dy);
2858 m1 = m - 1;
2859 incr1 = -2 * dx + 2 * (dy) * m1;
2860 incr2 = -2 * dx + 2 * (dy) * m;
2861 d = 2 * m * (dy) - 2 * dx - 2 * (dy);
2862 } else {
2863 m = dx / (dy);
2864 m1 = m + 1;
2865 incr1 = 2 * dx - 2 * (dy) * m1;
2866 incr2 = 2 * dx - 2 * (dy) * m;
2867 d = -2 * m * (dy) + 2 * dx;
2868 }
2869 } \
2870}
2871
2872#define BRESINCRPGON(d, minval, m, m1, incr1, incr2) {
2873 if (m1 > 0) {
2874 if (d > 0) {
2875 minval += m1;
2876 d += incr1;
2877 }
2878 else {
2879 minval += m;
2880 d += incr2;
2881 }
2882 } else {
2883 if (d >= 0) {
2884 minval += m1;
2885 d += incr1;
2886 }
2887 else {
2888 minval += m;
2889 d += incr2;
2890 }
2891 } \
2892}
2893
2894
2895/*
2896 * This structure contains all of the information needed
2897 * to run the bresenham algorithm.
2898 * The variables may be hardcoded into the declarations
2899 * instead of using this structure to make use of
2900 * register declarations.
2901 */
2902typedef struct {
2903 int minor_axis; /* minor axis */
2904 int d; /* decision variable */
2905 int m, m1; /* slope and slope+1 */
2906 int incr1, incr2; /* error increments */
2907} BRESINFO;
2908
2909
2910#define BRESINITPGONSTRUCT(dmaj, min1, min2, bres)
2911 BRESINITPGON(dmaj, min1, min2, bres.minor_axis, bres.d,
2912 bres.m, bres.m1, bres.incr1, bres.incr2)
2913
2914#define BRESINCRPGONSTRUCT(bres)
2915 BRESINCRPGON(bres.d, bres.minor_axis, bres.m, bres.m1, bres.incr1, bres.incr2)
2916
2917
2918
2919/*
2920 * These are the data structures needed to scan
2921 * convert regions. Two different scan conversion
2922 * methods are available -- the even-odd method, and
2923 * the winding number method.
2924 * The even-odd rule states that a point is inside
2925 * the polygon if a ray drawn from that point in any
2926 * direction will pass through an odd number of
2927 * path segments.
2928 * By the winding number rule, a point is decided
2929 * to be inside the polygon if a ray drawn from that
2930 * point in any direction passes through a different
2931 * number of clockwise and counter-clockwise path
2932 * segments.
2933 *
2934 * These data structures are adapted somewhat from
2935 * the algorithm in (Foley/Van Dam) for scan converting
2936 * polygons.
2937 * The basic algorithm is to start at the top (smallest y)
2938 * of the polygon, stepping down to the bottom of
2939 * the polygon by incrementing the y coordinate. We
2940 * keep a list of edges which the current scanline crosses,
2941 * sorted by x. This list is called the Active Edge Table (AET)
2942 * As we change the y-coordinate, we update each entry in
2943 * in the active edge table to reflect the edges new xcoord.
2944 * This list must be sorted at each scanline in case
2945 * two edges intersect.
2946 * We also keep a data structure known as the Edge Table (ET),
2947 * which keeps track of all the edges which the current
2948 * scanline has not yet reached. The ET is basically a
2949 * list of ScanLineList structures containing a list of
2950 * edges which are entered at a given scanline. There is one
2951 * ScanLineList per scanline at which an edge is entered.
2952 * When we enter a new edge, we move it from the ET to the AET.
2953 *
2954 * From the AET, we can implement the even-odd rule as in
2955 * (Foley/Van Dam).
2956 * The winding number rule is a little trickier. We also
2957 * keep the EdgeTableEntries in the AET linked by the
2958 * nextWETE (winding EdgeTableEntry) link. This allows
2959 * the edges to be linked just as before for updating
2960 * purposes, but only uses the edges linked by the nextWETE
2961 * link as edges representing spans of the polygon to
2962 * drawn (as with the even-odd rule).
2963 */
2964
2965/*
2966 * for the winding number rule
2967 */
2968#define CLOCKWISE 1
2969#define COUNTERCLOCKWISE -1
2970
2971typedef struct _EdgeTableEntry {
2972 int ymax; /* ycoord at which we exit this edge. */
2973 int ClockWise; /* flag for winding number rule */
2974 BRESINFO bres; /* Bresenham info to run the edge */
2975 struct _EdgeTableEntry *next; /* next in the list */
2976 struct _EdgeTableEntry *back; /* for insertion sort */
2977 struct _EdgeTableEntry *nextWETE; /* for winding num rule */
2978} EdgeTableEntry;
2979
2980
2981typedef struct _ScanLineList{
2982 int scanline; /* the scanline represented */
2983 EdgeTableEntry *edgelist; /* header node */
2984 struct _ScanLineList *next; /* next in the list */
2985} ScanLineList;
2986
2987
2988typedef struct {
2989 int ymax; /* ymax for the polygon */
2990 int ymin; /* ymin for the polygon */
2991 ScanLineList scanlines; /* header node */
2992} EdgeTable;
2993
2994
2995/*
2996 * Here is a struct to help with storage allocation
2997 * so we can allocate a big chunk at a time, and then take
2998 * pieces from this heap when we need to.
2999 */
3000#define SLLSPERBLOCK 25
3001
3002typedef struct _ScanLineListBlock {
3003 ScanLineList SLLs[SLLSPERBLOCK];
3005} ScanLineListBlock;
3006
3007
3008
3009/*
3010 *
3011 * a few macros for the inner loops of the fill code where
3012 * performance considerations don't allow a procedure call.
3013 *
3014 * Evaluate the given edge at the given scanline.
3015 * If the edge has expired, then we leave it and fix up
3016 * the active edge table; otherwise, we increment the
3017 * x value to be ready for the next scanline.
3018 * The winding number rule is in effect, so we must notify
3019 * the caller when the edge has been removed so he
3020 * can reorder the Winding Active Edge Table.
3021 */
3022#define EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET) {
3023 if (pAET->ymax == y) { /* leaving this edge */
3024 pPrevAET->next = pAET->next;
3025 pAET = pPrevAET->next;
3026 fixWAET = 1;
3027 if (pAET)
3028 pAET->back = pPrevAET;
3029 }
3030 else {
3031 BRESINCRPGONSTRUCT(pAET->bres)
3032 pPrevAET = pAET;
3033 pAET = pAET->next;
3034 } \
3035}
3036
3037
3038/*
3039 * Evaluate the given edge at the given scanline.
3040 * If the edge has expired, then we leave it and fix up
3041 * the active edge table; otherwise, we increment the
3042 * x value to be ready for the next scanline.
3043 * The even-odd rule is in effect.
3044 */
3045#define EVALUATEEDGEEVENODD(pAET, pPrevAET, y) {
3046 if (pAET->ymax == y) { /* leaving this edge */
3047 pPrevAET->next = pAET->next;
3048 pAET = pPrevAET->next;
3049 if (pAET)
3050 pAET->back = pPrevAET;
3051 }
3052 else {
3053 BRESINCRPGONSTRUCT(pAET->bres)
3054 pPrevAET = pAET;
3055 pAET = pAET->next;
3056 } \
3057}
3058// END OF poly.h extract
3059// START OF PolyReg.c extract
3060/* $XConsortium: PolyReg.c,v 11.23 94/11/17 21:59:37 converse Exp $ */
3061/************************************************************************
3062
3063Copyright (c) 1987 X Consortium
3064
3065Permission is hereby granted, free of charge, to any person obtaining a copy
3066of this software and associated documentation files (the "Software"), to deal
3067in the Software without restriction, including without limitation the rights
3068to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3069copies of the Software, and to permit persons to whom the Software is
3070furnished to do so, subject to the following conditions:
3071
3072The above copyright notice and this permission notice shall be included in
3073all copies or substantial portions of the Software.
3074
3075THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3076IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3077FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3078X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
3079AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
3080CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3081
3082Except as contained in this notice, the name of the X Consortium shall not be
3083used in advertising or otherwise to promote the sale, use or other dealings
3084in this Software without prior written authorization from the X Consortium.
3085
3086
3087Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
3088
3089 All Rights Reserved
3090
3091Permission to use, copy, modify, and distribute this software and its
3092documentation for any purpose and without fee is hereby granted,
3093provided that the above copyright notice appear in all copies and that
3094both that copyright notice and this permission notice appear in
3095supporting documentation, and that the name of Digital not be
3096used in advertising or publicity pertaining to distribution of the
3097software without specific, written prior permission.
3098
3099DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
3100ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
3101DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
3102ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
3103WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
3104ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
3105SOFTWARE.
3106
3107************************************************************************/
3108/* $XFree86: xc/lib/X11/PolyReg.c,v 1.1.1.2.8.2 1998/10/04 15:22:49 hohndel Exp $ */
3109
3110#define LARGE_COORDINATE INT_MAX
3111#define SMALL_COORDINATE INT_MIN
3112
3113/*
3114 * InsertEdgeInET
3115 *
3116 * Insert the given edge into the edge table.
3117 * First we must find the correct bucket in the
3118 * Edge table, then find the right slot in the
3119 * bucket. Finally, we can insert it.
3120 *
3121 */
3122static void InsertEdgeInET(EdgeTable *ET, EdgeTableEntry *ETE, int scanline,
3123 ScanLineListBlock **SLLBlock, int *iSLLBlock)
3124{
3125 EdgeTableEntry *start, *prev;
3126 ScanLineList *pSLL, *pPrevSLL;
3127 ScanLineListBlock *tmpSLLBlock;
3128
3129 /*
3130 * find the right bucket to put the edge into
3131 */
3132 pPrevSLL = &ET->scanlines;
3133 pSLL = pPrevSLL->next;
3134 while (pSLL && (pSLL->scanline < scanline)) {
3135 pPrevSLL = pSLL;
3136 pSLL = pSLL->next;
3137 }
3138
3139 /*
3140 * reassign pSLL (pointer to ScanLineList) if necessary
3141 */
3142 if ((!pSLL) || (pSLL->scanline > scanline)) {
3143 if (*iSLLBlock > SLLSPERBLOCK-1)
3144 {
3145 tmpSLLBlock =
3146 (ScanLineListBlock *)malloc(sizeof(ScanLineListBlock));
3147 Q_CHECK_PTR(tmpSLLBlock);
3148 (*SLLBlock)->next = tmpSLLBlock;
3149 tmpSLLBlock->next = (ScanLineListBlock *)nullptr;
3150 *SLLBlock = tmpSLLBlock;
3151 *iSLLBlock = 0;
3152 }
3153 pSLL = &((*SLLBlock)->SLLs[(*iSLLBlock)++]);
3154
3155 pSLL->next = pPrevSLL->next;
3156 pSLL->edgelist = (EdgeTableEntry *)nullptr;
3157 pPrevSLL->next = pSLL;
3158 }
3159 pSLL->scanline = scanline;
3160
3161 /*
3162 * now insert the edge in the right bucket
3163 */
3164 prev = nullptr;
3165 start = pSLL->edgelist;
3166 while (start && (start->bres.minor_axis < ETE->bres.minor_axis)) {
3167 prev = start;
3168 start = start->next;
3169 }
3170 ETE->next = start;
3171
3172 if (prev)
3173 prev->next = ETE;
3174 else
3175 pSLL->edgelist = ETE;
3176}
3177
3178/*
3179 * CreateEdgeTable
3180 *
3181 * This routine creates the edge table for
3182 * scan converting polygons.
3183 * The Edge Table (ET) looks like:
3184 *
3185 * EdgeTable
3186 * --------
3187 * | ymax | ScanLineLists
3188 * |scanline|-->------------>-------------->...
3189 * -------- |scanline| |scanline|
3190 * |edgelist| |edgelist|
3191 * --------- ---------
3192 * | |
3193 * | |
3194 * V V
3195 * list of ETEs list of ETEs
3196 *
3197 * where ETE is an EdgeTableEntry data structure,
3198 * and there is one ScanLineList per scanline at
3199 * which an edge is initially entered.
3200 *
3201 */
3202
3203static void CreateETandAET(int count, const QPoint *pts,
3204 EdgeTable *ET, EdgeTableEntry *AET, EdgeTableEntry *pETEs,
3205 ScanLineListBlock *pSLLBlock)
3206{
3207 const QPoint *top,
3208 *bottom,
3209 *PrevPt,
3210 *CurrPt;
3211 int iSLLBlock = 0;
3212 int dy;
3213
3214 Q_ASSERT(count > 1);
3215
3216 /*
3217 * initialize the Active Edge Table
3218 */
3219 AET->next = nullptr;
3220 AET->back = nullptr;
3221 AET->nextWETE = nullptr;
3223
3224 /*
3225 * initialize the Edge Table.
3226 */
3227 ET->scanlines.next = nullptr;
3230 pSLLBlock->next = nullptr;
3231
3232 PrevPt = &pts[count - 1];
3233
3234 /*
3235 * for each vertex in the array of points.
3236 * In this loop we are dealing with two vertices at
3237 * a time -- these make up one edge of the polygon.
3238 */
3239 while (count--) {
3240 CurrPt = pts++;
3241
3242 /*
3243 * find out which point is above and which is below.
3244 */
3245 if (PrevPt->y() > CurrPt->y()) {
3246 bottom = PrevPt;
3247 top = CurrPt;
3248 pETEs->ClockWise = 0;
3249 } else {
3250 bottom = CurrPt;
3251 top = PrevPt;
3252 pETEs->ClockWise = 1;
3253 }
3254
3255 /*
3256 * don't add horizontal edges to the Edge table.
3257 */
3258 if (bottom->y() != top->y()) {
3259 pETEs->ymax = bottom->y() - 1; /* -1 so we don't get last scanline */
3260
3261 /*
3262 * initialize integer edge algorithm
3263 */
3264 dy = bottom->y() - top->y();
3265 BRESINITPGONSTRUCT(dy, top->x(), bottom->x(), pETEs->bres)
3266
3267 InsertEdgeInET(ET, pETEs, top->y(), &pSLLBlock, &iSLLBlock);
3268
3269 if (PrevPt->y() > ET->ymax)
3270 ET->ymax = PrevPt->y();
3271 if (PrevPt->y() < ET->ymin)
3272 ET->ymin = PrevPt->y();
3273 ++pETEs;
3274 }
3275
3276 PrevPt = CurrPt;
3277 }
3278}
3279
3280/*
3281 * loadAET
3282 *
3283 * This routine moves EdgeTableEntries from the
3284 * EdgeTable into the Active Edge Table,
3285 * leaving them sorted by smaller x coordinate.
3286 *
3287 */
3288
3289static void loadAET(EdgeTableEntry *AET, EdgeTableEntry *ETEs)
3290{
3291 EdgeTableEntry *pPrevAET;
3292 EdgeTableEntry *tmp;
3293
3294 pPrevAET = AET;
3295 AET = AET->next;
3296 while (ETEs) {
3297 while (AET && AET->bres.minor_axis < ETEs->bres.minor_axis) {
3298 pPrevAET = AET;
3299 AET = AET->next;
3300 }
3301 tmp = ETEs->next;
3302 ETEs->next = AET;
3303 if (AET)
3304 AET->back = ETEs;
3305 ETEs->back = pPrevAET;
3306 pPrevAET->next = ETEs;
3307 pPrevAET = ETEs;
3308
3309 ETEs = tmp;
3310 }
3311}
3312
3313/*
3314 * computeWAET
3315 *
3316 * This routine links the AET by the
3317 * nextWETE (winding EdgeTableEntry) link for
3318 * use by the winding number rule. The final
3319 * Active Edge Table (AET) might look something
3320 * like:
3321 *
3322 * AET
3323 * ---------- --------- ---------
3324 * |ymax | |ymax | |ymax |
3325 * | ... | |... | |... |
3326 * |next |->|next |->|next |->...
3327 * |nextWETE| |nextWETE| |nextWETE|
3328 * --------- --------- ^--------
3329 * | | |
3330 * V-------------------> V---> ...
3331 *
3332 */
3333static void computeWAET(EdgeTableEntry *AET)
3334{
3335 EdgeTableEntry *pWETE;
3336 int inside = 1;
3337 int isInside = 0;
3338
3339 AET->nextWETE = nullptr;
3340 pWETE = AET;
3341 AET = AET->next;
3342 while (AET) {
3343 if (AET->ClockWise)
3344 ++isInside;
3345 else
3346 --isInside;
3347
3348 if ((!inside && !isInside) || (inside && isInside)) {
3349 pWETE->nextWETE = AET;
3350 pWETE = AET;
3351 inside = !inside;
3352 }
3353 AET = AET->next;
3354 }
3355 pWETE->nextWETE = nullptr;
3356}
3357
3358/*
3359 * InsertionSort
3360 *
3361 * Just a simple insertion sort using
3362 * pointers and back pointers to sort the Active
3363 * Edge Table.
3364 *
3365 */
3366
3367static int InsertionSort(EdgeTableEntry *AET)
3368{
3369 EdgeTableEntry *pETEchase;
3370 EdgeTableEntry *pETEinsert;
3371 EdgeTableEntry *pETEchaseBackTMP;
3372 int changed = 0;
3373
3374 AET = AET->next;
3375 while (AET) {
3376 pETEinsert = AET;
3377 pETEchase = AET;
3378 while (pETEchase->back->bres.minor_axis > AET->bres.minor_axis)
3379 pETEchase = pETEchase->back;
3380
3381 AET = AET->next;
3382 if (pETEchase != pETEinsert) {
3383 pETEchaseBackTMP = pETEchase->back;
3384 pETEinsert->back->next = AET;
3385 if (AET)
3386 AET->back = pETEinsert->back;
3387 pETEinsert->next = pETEchase;
3388 pETEchase->back->next = pETEinsert;
3389 pETEchase->back = pETEinsert;
3390 pETEinsert->back = pETEchaseBackTMP;
3391 changed = 1;
3392 }
3393 }
3394 return changed;
3395}
3396
3397/*
3398 * Clean up our act.
3399 */
3400static void FreeStorage(ScanLineListBlock *pSLLBlock)
3401{
3402 ScanLineListBlock *tmpSLLBlock;
3403
3404 while (pSLLBlock) {
3405 tmpSLLBlock = pSLLBlock->next;
3406 free(pSLLBlock);
3407 pSLLBlock = tmpSLLBlock;
3408 }
3409}
3410
3413 QRegionSpan(int x1_, int x2_) : x1(x1_), x2(x2_) {}
3414
3415 int x1;
3416 int x2;
3417 int width() const { return x2 - x1; }
3418};
3419
3421
3422static inline void flushRow(const QRegionSpan *spans, int y, int numSpans, QRegionPrivate *reg, int *lastRow, int *extendTo, bool *needsExtend)
3423{
3424 QRect *regRects = reg->rects.data() + *lastRow;
3425 bool canExtend = reg->rects.size() - *lastRow == numSpans
3426 && !(*needsExtend && *extendTo + 1 != y)
3427 && (*needsExtend || regRects[0].y() + regRects[0].height() == y);
3428
3429 for (int i = 0; i < numSpans && canExtend; ++i) {
3430 if (regRects[i].x() != spans[i].x1 || regRects[i].right() != spans[i].x2 - 1)
3431 canExtend = false;
3432 }
3433
3434 if (canExtend) {
3435 *extendTo = y;
3436 *needsExtend = true;
3437 } else {
3438 if (*needsExtend) {
3439 for (int i = 0; i < reg->rects.size() - *lastRow; ++i)
3440 regRects[i].setBottom(*extendTo);
3441 }
3442
3443 *lastRow = reg->rects.size();
3444 reg->rects.reserve(*lastRow + numSpans);
3445 for (int i = 0; i < numSpans; ++i)
3446 reg->rects << QRect(spans[i].x1, y, spans[i].width(), 1);
3447
3448 if (spans[0].x1 < reg->extents.left())
3449 reg->extents.setLeft(spans[0].x1);
3450
3451 if (spans[numSpans-1].x2 - 1 > reg->extents.right())
3452 reg->extents.setRight(spans[numSpans-1].x2 - 1);
3453
3454 *needsExtend = false;
3455 }
3456}
3457
3458/*
3459 * Create an array of rectangles from a list of points.
3460 * If indeed these things (POINTS, RECTS) are the same,
3461 * then this proc is still needed, because it allocates
3462 * storage for the array, which was allocated on the
3463 * stack by the calling procedure.
3464 *
3465 */
3466static void PtsToRegion(int numFullPtBlocks, int iCurPtBlock,
3467 POINTBLOCK *FirstPtBlock, QRegionPrivate *reg)
3468{
3469 int lastRow = 0;
3470 int extendTo = 0;
3471 bool needsExtend = false;
3472 QVarLengthArray<QRegionSpan> row;
3473 qsizetype rowSize = 0;
3474
3475 reg->extents.setLeft(INT_MAX);
3476 reg->extents.setRight(INT_MIN);
3477 reg->innerArea = -1;
3478
3479 POINTBLOCK *CurPtBlock = FirstPtBlock;
3480 for (; numFullPtBlocks >= 0; --numFullPtBlocks) {
3481 /* the loop uses 2 points per iteration */
3482 int i = NUMPTSTOBUFFER >> 1;
3483 if (!numFullPtBlocks)
3484 i = iCurPtBlock >> 1;
3485 if(i) {
3486 row.resize(qMax(row.size(), rowSize + i));
3487 for (QPoint *pts = CurPtBlock->pts; i--; pts += 2) {
3488 const int width = pts[1].x() - pts[0].x();
3489 if (width) {
3490 if (rowSize && row[rowSize-1].x2 == pts[0].x())
3491 row[rowSize-1].x2 = pts[1].x();
3492 else
3493 row[rowSize++] = QRegionSpan(pts[0].x(), pts[1].x());
3494 }
3495
3496 if (rowSize) {
3497 QPoint *next = i ? &pts[2] : (numFullPtBlocks && iCurPtBlock ? CurPtBlock->next->pts : nullptr);
3498
3499 if (!next || next->y() != pts[0].y()) {
3500 flushRow(row.data(), pts[0].y(), rowSize, reg, &lastRow, &extendTo, &needsExtend);
3501 rowSize = 0;
3502 }
3503 }
3504 }
3505 }
3506 CurPtBlock = CurPtBlock->next;
3507 }
3508
3509 if (needsExtend) {
3510 for (int i = lastRow; i < reg->rects.size(); ++i)
3511 reg->rects[i].setBottom(extendTo);
3512 }
3513
3514 reg->numRects = reg->rects.size();
3515
3516 if (reg->numRects) {
3517 reg->extents.setTop(reg->rects[0].top());
3518 reg->extents.setBottom(reg->rects[lastRow].bottom());
3519
3520 for (int i = 0; i < reg->rects.size(); ++i)
3521 reg->updateInnerRect(reg->rects[i]);
3522 } else {
3523 reg->extents.setCoords(0, 0, 0, 0);
3524 }
3525}
3526
3527/*
3528 * polytoregion
3529 *
3530 * Scan converts a polygon by returning a run-length
3531 * encoding of the resultant bitmap -- the run-length
3532 * encoding is in the form of an array of rectangles.
3533 *
3534 * Can return 0 in case of errors.
3535 */
3536static QRegionPrivate *PolygonRegion(const QPoint *Pts, int Count, int rule)
3537 //Point *Pts; /* the pts */
3538 //int Count; /* number of pts */
3539 //int rule; /* winding rule */
3540{
3541 QRegionPrivate *region;
3542 EdgeTableEntry *pAET; /* Active Edge Table */
3543 int y; /* current scanline */
3544 int iPts = 0; /* number of pts in buffer */
3545 EdgeTableEntry *pWETE; /* Winding Edge Table Entry*/
3546 ScanLineList *pSLL; /* current scanLineList */
3547 QPoint *pts; /* output buffer */
3548 EdgeTableEntry *pPrevAET; /* ptr to previous AET */
3549 EdgeTable ET; /* header node for ET */
3550 EdgeTableEntry *AET; /* header node for AET */
3551 EdgeTableEntry *pETEs; /* EdgeTableEntries pool */
3552 ScanLineListBlock SLLBlock; /* header for scanlinelist */
3553 int fixWAET = false;
3554 POINTBLOCK FirstPtBlock, *curPtBlock; /* PtBlock buffers */
3555 FirstPtBlock.pts = reinterpret_cast<QPoint *>(FirstPtBlock.data);
3556 FirstPtBlock.next = nullptr;
3557 POINTBLOCK *tmpPtBlock;
3558 int numFullPtBlocks = 0;
3559
3560 Q_ASSERT(Count > 1);
3561
3562 region = new QRegionPrivate;
3563
3564 /* special case a rectangle */
3565 if (((Count == 4) ||
3566 ((Count == 5) && (Pts[4].x() == Pts[0].x()) && (Pts[4].y() == Pts[0].y())))
3567 && (((Pts[0].y() == Pts[1].y()) && (Pts[1].x() == Pts[2].x()) && (Pts[2].y() == Pts[3].y())
3568 && (Pts[3].x() == Pts[0].x())) || ((Pts[0].x() == Pts[1].x())
3569 && (Pts[1].y() == Pts[2].y()) && (Pts[2].x() == Pts[3].x())
3570 && (Pts[3].y() == Pts[0].y())))) {
3571 int x = qMin(Pts[0].x(), Pts[2].x());
3572 region->extents.setLeft(x);
3573 int y = qMin(Pts[0].y(), Pts[2].y());
3574 region->extents.setTop(y);
3575 region->extents.setWidth(qMax(Pts[0].x(), Pts[2].x()) - x);
3576 region->extents.setHeight(qMax(Pts[0].y(), Pts[2].y()) - y);
3577 if ((region->extents.left() <= region->extents.right()) &&
3578 (region->extents.top() <= region->extents.bottom())) {
3579 region->numRects = 1;
3580 region->innerRect = region->extents;
3581 region->innerArea = region->innerRect.width() * region->innerRect.height();
3582 }
3583 return region;
3584 }
3585
3586 if (!(pETEs = static_cast<EdgeTableEntry *>(malloc(sizeof(EdgeTableEntry) * Count)))) {
3587 delete region;
3588 return nullptr;
3589 }
3590
3591 region->vectorize();
3592
3593 AET = new EdgeTableEntry;
3594 pts = FirstPtBlock.pts;
3595 CreateETandAET(Count, Pts, &ET, AET, pETEs, &SLLBlock);
3596
3597 pSLL = ET.scanlines.next;
3598 curPtBlock = &FirstPtBlock;
3599
3600 // sanity check that the region won't become too big...
3601 if (ET.ymax - ET.ymin > 100000) {
3602 // clean up region ptr
3603#ifndef QT_NO_DEBUG
3604 qWarning("QRegion: creating region from big polygon failed...!");
3605#endif
3606 delete AET;
3607 delete region;
3608 return nullptr;
3609 }
3610
3611
3612 QT_TRY {
3613 if (rule == EvenOddRule) {
3614 /*
3615 * for each scanline
3616 */
3617 for (y = ET.ymin; y < ET.ymax; ++y) {
3618
3619 /*
3620 * Add a new edge to the active edge table when we
3621 * get to the next edge.
3622 */
3623 if (pSLL && y == pSLL->scanline) {
3624 loadAET(AET, pSLL->edgelist);
3625 pSLL = pSLL->next;
3626 }
3627 pPrevAET = AET;
3628 pAET = AET->next;
3629
3630 /*
3631 * for each active edge
3632 */
3633 while (pAET) {
3634 pts->setX(pAET->bres.minor_axis);
3635 pts->setY(y);
3636 ++pts;
3637 ++iPts;
3638
3639 /*
3640 * send out the buffer
3641 */
3642 if (iPts == NUMPTSTOBUFFER) {
3643 tmpPtBlock = (POINTBLOCK *)malloc(sizeof(POINTBLOCK));
3644 Q_CHECK_PTR(tmpPtBlock);
3645 tmpPtBlock->pts = reinterpret_cast<QPoint *>(tmpPtBlock->data);
3646 curPtBlock->next = tmpPtBlock;
3647 curPtBlock = tmpPtBlock;
3648 pts = curPtBlock->pts;
3649 ++numFullPtBlocks;
3650 iPts = 0;
3651 }
3652 EVALUATEEDGEEVENODD(pAET, pPrevAET, y)
3653 }
3654 InsertionSort(AET);
3655 }
3656 } else {
3657 /*
3658 * for each scanline
3659 */
3660 for (y = ET.ymin; y < ET.ymax; ++y) {
3661 /*
3662 * Add a new edge to the active edge table when we
3663 * get to the next edge.
3664 */
3665 if (pSLL && y == pSLL->scanline) {
3666 loadAET(AET, pSLL->edgelist);
3667 computeWAET(AET);
3668 pSLL = pSLL->next;
3669 }
3670 pPrevAET = AET;
3671 pAET = AET->next;
3672 pWETE = pAET;
3673
3674 /*
3675 * for each active edge
3676 */
3677 while (pAET) {
3678 /*
3679 * add to the buffer only those edges that
3680 * are in the Winding active edge table.
3681 */
3682 if (pWETE == pAET) {
3683 pts->setX(pAET->bres.minor_axis);
3684 pts->setY(y);
3685 ++pts;
3686 ++iPts;
3687
3688 /*
3689 * send out the buffer
3690 */
3691 if (iPts == NUMPTSTOBUFFER) {
3692 tmpPtBlock = static_cast<POINTBLOCK *>(malloc(sizeof(POINTBLOCK)));
3693 tmpPtBlock->pts = reinterpret_cast<QPoint *>(tmpPtBlock->data);
3694 curPtBlock->next = tmpPtBlock;
3695 curPtBlock = tmpPtBlock;
3696 pts = curPtBlock->pts;
3697 ++numFullPtBlocks;
3698 iPts = 0;
3699 }
3700 pWETE = pWETE->nextWETE;
3701 }
3702 EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET)
3703 }
3704
3705 /*
3706 * recompute the winding active edge table if
3707 * we just resorted or have exited an edge.
3708 */
3709 if (InsertionSort(AET) || fixWAET) {
3710 computeWAET(AET);
3711 fixWAET = false;
3712 }
3713 }
3714 }
3715 } QT_CATCH(...) {
3716 FreeStorage(SLLBlock.next);
3717 PtsToRegion(numFullPtBlocks, iPts, &FirstPtBlock, region);
3718 for (curPtBlock = FirstPtBlock.next; --numFullPtBlocks >= 0;) {
3719 tmpPtBlock = curPtBlock->next;
3720 free(curPtBlock);
3721 curPtBlock = tmpPtBlock;
3722 }
3723 free(pETEs);
3724 return nullptr; // this function returns 0 in case of an error
3725 }
3726
3727 FreeStorage(SLLBlock.next);
3728 PtsToRegion(numFullPtBlocks, iPts, &FirstPtBlock, region);
3729 for (curPtBlock = FirstPtBlock.next; --numFullPtBlocks >= 0;) {
3730 tmpPtBlock = curPtBlock->next;
3731 free(curPtBlock);
3732 curPtBlock = tmpPtBlock;
3733 }
3734 delete AET;
3735 free(pETEs);
3736 return region;
3737}
3738// END OF PolyReg.c extract
3739
3740QRegionPrivate *qt_bitmapToRegion(const QBitmap& bitmap)
3741{
3742 const QImage image = bitmap.toImage();
3743
3744 QRegionPrivate *region = new QRegionPrivate;
3745
3746 QRect xr;
3747
3748#define AddSpan
3749 {
3750 xr.setCoords(prev1, y, x-1, y);
3751 UnionRectWithRegion(&xr, region, *region);
3752 }
3753
3754 const uchar zero = 0;
3755 bool little = image.format() == QImage::Format_MonoLSB;
3756
3757 int x,
3758 y;
3759 for (y = 0; y < image.height(); ++y) {
3760 const uchar *line = image.constScanLine(y);
3761 int w = image.width();
3762 uchar all = zero;
3763 int prev1 = -1;
3764 for (x = 0; x < w;) {
3765 uchar byte = line[x / 8];
3766 if (x > w - 8 || byte!=all) {
3767 if (little) {
3768 for (int b = 8; b > 0 && x < w; --b) {
3769 if (!(byte & 0x01) == !all) {
3770 // More of the same
3771 } else {
3772 // A change.
3773 if (all!=zero) {
3774 AddSpan
3775 all = zero;
3776 } else {
3777 prev1 = x;
3778 all = ~zero;
3779 }
3780 }
3781 byte >>= 1;
3782 ++x;
3783 }
3784 } else {
3785 for (int b = 8; b > 0 && x < w; --b) {
3786 if (!(byte & 0x80) == !all) {
3787 // More of the same
3788 } else {
3789 // A change.
3790 if (all != zero) {
3791 AddSpan
3792 all = zero;
3793 } else {
3794 prev1 = x;
3795 all = ~zero;
3796 }
3797 }
3798 byte <<= 1;
3799 ++x;
3800 }
3801 }
3802 } else {
3803 x += 8;
3804 }
3805 }
3806 if (all != zero) {
3807 AddSpan
3808 }
3809 }
3810#undef AddSpan
3811
3812 return region;
3813}
3814
3815QRegion::QRegion()
3816 : d(const_cast<QRegionData*>(&shared_empty))
3817{
3818}
3819
3820QRegion::QRegion(const QRect &r, RegionType t)
3821{
3822 if (r.isEmpty()) {
3823 d = const_cast<QRegionData*>(&shared_empty);
3824 } else {
3825 d = new QRegionData;
3826 if (t == Rectangle) {
3827 d->qt_rgn = new QRegionPrivate(r);
3828 } else if (t == Ellipse) {
3829 QPainterPath path;
3830 path.addEllipse(r.x(), r.y(), r.width(), r.height());
3831 QPolygon a = path.toSubpathPolygons().at(0).toPolygon();
3832 d->qt_rgn = PolygonRegion(a.constData(), a.size(), EvenOddRule);
3833 }
3834 }
3835}
3836
3837QRegion::QRegion(const QPolygon &a, Qt::FillRule fillRule)
3838{
3839 if (a.size() > 2) {
3840 QRegionPrivate *qt_rgn = PolygonRegion(a.constData(), a.size(),
3841 fillRule == Qt::WindingFill ? WindingRule : EvenOddRule);
3842 if (qt_rgn) {
3843 d = new QRegionData;
3844 d->qt_rgn = qt_rgn;
3845 } else {
3846 d = const_cast<QRegionData*>(&shared_empty);
3847 }
3848 } else {
3849 d = const_cast<QRegionData*>(&shared_empty);
3850 }
3851}
3852
3853QRegion::QRegion(const QRegion &r)
3854{
3855 d = r.d;
3856 d->ref.ref();
3857}
3858
3859
3860QRegion::QRegion(const QBitmap &bm)
3861{
3862 if (bm.isNull()) {
3863 d = const_cast<QRegionData*>(&shared_empty);
3864 } else {
3865 d = new QRegionData;
3866 d->qt_rgn = qt_bitmapToRegion(bm);
3867 }
3868}
3869
3870void QRegion::cleanUp(QRegion::QRegionData *x)
3871{
3872 delete x->qt_rgn;
3873 delete x;
3874}
3875
3876QRegion::~QRegion()
3877{
3878 if (!d->ref.deref())
3879 cleanUp(d);
3880}
3881
3882
3883QRegion &QRegion::operator=(const QRegion &r)
3884{
3885 r.d->ref.ref();
3886 if (!d->ref.deref())
3887 cleanUp(d);
3888 d = r.d;
3889 return *this;
3890}
3891
3892
3893/*!
3894 \internal
3895*/
3896QRegion QRegion::copy() const
3897{
3898 QRegion r;
3899 auto x = std::make_unique<QRegionData>();
3900 x->ref.initializeOwned();
3901 if (d->qt_rgn)
3902 x->qt_rgn = new QRegionPrivate(*d->qt_rgn);
3903 else
3904 x->qt_rgn = new QRegionPrivate;
3905 if (!r.d->ref.deref())
3906 cleanUp(r.d);
3907 r.d = x.release();
3908 return r;
3909}
3910
3911bool QRegion::isEmpty() const
3912{
3913 return d == &shared_empty || d->qt_rgn->numRects == 0;
3914}
3915
3916bool QRegion::isNull() const
3917{
3918 return d == &shared_empty || d->qt_rgn->numRects == 0;
3919}
3920
3921bool QRegion::contains(const QPoint &p) const
3922{
3923 return PointInRegion(d->qt_rgn, p.x(), p.y());
3924}
3925
3926bool QRegion::contains(const QRect &r) const
3927{
3928 return RectInRegion(d->qt_rgn, r.left(), r.top(), r.width(), r.height()) != RectangleOut;
3929}
3930
3931
3932
3933void QRegion::translate(int dx, int dy)
3934{
3935 if ((dx == 0 && dy == 0) || isEmptyHelper(d->qt_rgn))
3936 return;
3937
3938 detach();
3939 OffsetRegion(*d->qt_rgn, dx, dy);
3940}
3941
3942QRegion QRegion::united(const QRegion &r) const
3943{
3944 if (isEmptyHelper(d->qt_rgn))
3945 return r;
3946 if (isEmptyHelper(r.d->qt_rgn))
3947 return *this;
3948 if (d == r.d)
3949 return *this;
3950
3951 if (d->qt_rgn->contains(*r.d->qt_rgn)) {
3952 return *this;
3953 } else if (r.d->qt_rgn->contains(*d->qt_rgn)) {
3954 return r;
3955 } else if (d->qt_rgn->canAppend(r.d->qt_rgn)) {
3956 QRegion result(*this);
3957 result.detach();
3958 result.d->qt_rgn->append(r.d->qt_rgn);
3959 return result;
3960 } else if (d->qt_rgn->canPrepend(r.d->qt_rgn)) {
3961 QRegion result(*this);
3962 result.detach();
3963 result.d->qt_rgn->prepend(r.d->qt_rgn);
3964 return result;
3965 } else if (EqualRegion(d->qt_rgn, r.d->qt_rgn)) {
3966 return *this;
3967 } else {
3968 QRegion result;
3969 result.detach();
3970 UnionRegion(d->qt_rgn, r.d->qt_rgn, *result.d->qt_rgn);
3971 return result;
3972 }
3973}
3974
3975QRegion& QRegion::operator+=(const QRegion &r)
3976{
3977 if (isEmptyHelper(d->qt_rgn))
3978 return *this = r;
3979 if (isEmptyHelper(r.d->qt_rgn))
3980 return *this;
3981 if (d == r.d)
3982 return *this;
3983
3984 if (d->qt_rgn->contains(*r.d->qt_rgn)) {
3985 return *this;
3986 } else if (r.d->qt_rgn->contains(*d->qt_rgn)) {
3987 return *this = r;
3988 } else if (d->qt_rgn->canAppend(r.d->qt_rgn)) {
3989 detach();
3990 d->qt_rgn->append(r.d->qt_rgn);
3991 return *this;
3992 } else if (d->qt_rgn->canPrepend(r.d->qt_rgn)) {
3993 detach();
3994 d->qt_rgn->prepend(r.d->qt_rgn);
3995 return *this;
3996 } else if (EqualRegion(d->qt_rgn, r.d->qt_rgn)) {
3997 return *this;
3998 } else {
3999 detach();
4000 UnionRegion(d->qt_rgn, r.d->qt_rgn, *d->qt_rgn);
4001 return *this;
4002 }
4003}
4004
4005QRegion QRegion::united(const QRect &r) const
4006{
4007 if (isEmptyHelper(d->qt_rgn))
4008 return r;
4009 if (r.isEmpty())
4010 return *this;
4011
4012 if (d->qt_rgn->contains(r)) {
4013 return *this;
4014 } else if (d->qt_rgn->within(r)) {
4015 return r;
4016 } else if (d->qt_rgn->numRects == 1 && d->qt_rgn->extents == r) {
4017 return *this;
4018 } else if (d->qt_rgn->canAppend(&r)) {
4019 QRegion result(*this);
4020 result.detach();
4021 result.d->qt_rgn->append(&r);
4022 return result;
4023 } else if (d->qt_rgn->canPrepend(&r)) {
4024 QRegion result(*this);
4025 result.detach();
4026 result.d->qt_rgn->prepend(&r);
4027 return result;
4028 } else {
4029 QRegion result;
4030 result.detach();
4031 QRegionPrivate rp(r);
4032 UnionRegion(d->qt_rgn, &rp, *result.d->qt_rgn);
4033 return result;
4034 }
4035}
4036
4037QRegion& QRegion::operator+=(const QRect &r)
4038{
4039 if (isEmptyHelper(d->qt_rgn))
4040 return *this = r;
4041 if (r.isEmpty())
4042 return *this;
4043
4044 if (d->qt_rgn->contains(r)) {
4045 return *this;
4046 } else if (d->qt_rgn->within(r)) {
4047 return *this = r;
4048 } else if (d->qt_rgn->canAppend(&r)) {
4049 detach();
4050 d->qt_rgn->append(&r);
4051 return *this;
4052 } else if (d->qt_rgn->canPrepend(&r)) {
4053 detach();
4054 d->qt_rgn->prepend(&r);
4055 return *this;
4056 } else if (d->qt_rgn->numRects == 1 && d->qt_rgn->extents == r) {
4057 return *this;
4058 } else {
4059 detach();
4060 QRegionPrivate p(r);
4061 UnionRegion(d->qt_rgn, &p, *d->qt_rgn);
4062 return *this;
4063 }
4064}
4065
4066QRegion QRegion::intersected(const QRegion &r) const
4067{
4068 if (isEmptyHelper(d->qt_rgn) || isEmptyHelper(r.d->qt_rgn)
4069 || !EXTENTCHECK(&d->qt_rgn->extents, &r.d->qt_rgn->extents))
4070 return QRegion();
4071
4072 /* this is fully contained in r */
4073 if (r.d->qt_rgn->contains(*d->qt_rgn))
4074 return *this;
4075
4076 /* r is fully contained in this */
4077 if (d->qt_rgn->contains(*r.d->qt_rgn))
4078 return r;
4079
4080 if (r.d->qt_rgn->numRects == 1 && d->qt_rgn->numRects == 1) {
4081 const QRect rect = qt_rect_intersect_normalized(r.d->qt_rgn->extents,
4082 d->qt_rgn->extents);
4083 return QRegion(rect);
4084 } else if (r.d->qt_rgn->numRects == 1) {
4085 QRegion result(*this);
4086 result.detach();
4087 result.d->qt_rgn->intersect(r.d->qt_rgn->extents);
4088 return result;
4089 } else if (d->qt_rgn->numRects == 1) {
4090 QRegion result(r);
4091 result.detach();
4092 result.d->qt_rgn->intersect(d->qt_rgn->extents);
4093 return result;
4094 }
4095
4096 QRegion result;
4097 result.detach();
4098 miRegionOp(*result.d->qt_rgn, d->qt_rgn, r.d->qt_rgn, miIntersectO, nullptr, nullptr);
4099
4100 /*
4101 * Can't alter dest's extents before we call miRegionOp because
4102 * it might be one of the source regions and miRegionOp depends
4103 * on the extents of those regions being the same. Besides, this
4104 * way there's no checking against rectangles that will be nuked
4105 * due to coalescing, so we have to examine fewer rectangles.
4106 */
4107 miSetExtents(*result.d->qt_rgn);
4108 return result;
4109}
4110
4111QRegion QRegion::intersected(const QRect &r) const
4112{
4113 if (isEmptyHelper(d->qt_rgn) || r.isEmpty()
4114 || !EXTENTCHECK(&d->qt_rgn->extents, &r))
4115 return QRegion();
4116
4117 /* this is fully contained in r */
4118 if (d->qt_rgn->within(r))
4119 return *this;
4120
4121 /* r is fully contained in this */
4122 if (d->qt_rgn->contains(r))
4123 return r;
4124
4125 if (d->qt_rgn->numRects == 1) {
4126 const QRect rect = qt_rect_intersect_normalized(d->qt_rgn->extents,
4127 r.normalized());
4128 return QRegion(rect);
4129 }
4130
4131 QRegion result(*this);
4132 result.detach();
4133 result.d->qt_rgn->intersect(r);
4134 return result;
4135}
4136
4137QRegion QRegion::subtracted(const QRegion &r) const
4138{
4139 if (isEmptyHelper(d->qt_rgn) || isEmptyHelper(r.d->qt_rgn))
4140 return *this;
4141 if (r.d->qt_rgn->contains(*d->qt_rgn))
4142 return QRegion();
4143 if (!EXTENTCHECK(&d->qt_rgn->extents, &r.d->qt_rgn->extents))
4144 return *this;
4145 if (d == r.d || EqualRegion(d->qt_rgn, r.d->qt_rgn))
4146 return QRegion();
4147
4148#ifdef QT_REGION_DEBUG
4149 d->qt_rgn->selfTest();
4150 r.d->qt_rgn->selfTest();
4151#endif
4152
4153 QRegion result;
4154 result.detach();
4155 SubtractRegion(d->qt_rgn, r.d->qt_rgn, *result.d->qt_rgn);
4156#ifdef QT_REGION_DEBUG
4157 result.d->qt_rgn->selfTest();
4158#endif
4159 return result;
4160}
4161
4162QRegion QRegion::xored(const QRegion &r) const
4163{
4164 if (isEmptyHelper(d->qt_rgn)) {
4165 return r;
4166 } else if (isEmptyHelper(r.d->qt_rgn)) {
4167 return *this;
4168 } else if (!EXTENTCHECK(&d->qt_rgn->extents, &r.d->qt_rgn->extents)) {
4169 return (*this + r);
4170 } else if (d == r.d || EqualRegion(d->qt_rgn, r.d->qt_rgn)) {
4171 return QRegion();
4172 } else {
4173 QRegion result;
4174 result.detach();
4175 XorRegion(d->qt_rgn, r.d->qt_rgn, *result.d->qt_rgn);
4176 return result;
4177 }
4178}
4179
4180QRect QRegion::boundingRect() const noexcept
4181{
4182 if (isEmpty())
4183 return QRect();
4184 return d->qt_rgn->extents;
4185}
4186
4187/*! \internal
4188 Returns \c true if \a rect is guaranteed to be fully contained in \a region.
4189 A false return value does not guarantee the opposite.
4190*/
4191Q_GUI_EXPORT
4192bool qt_region_strictContains(const QRegion &region, const QRect &rect)
4193{
4194 if (isEmptyHelper(region.d->qt_rgn) || !rect.isValid())
4195 return false;
4196
4197#if 0 // TEST_INNERRECT
4198 static bool guard = false;
4199 if (guard)
4200 return false;
4201 guard = true;
4202 QRegion inner = region.d->qt_rgn->innerRect;
4203 Q_ASSERT((inner - region).isEmpty());
4204 guard = false;
4205
4206 int maxArea = 0;
4207 for (int i = 0; i < region.d->qt_rgn->numRects; ++i) {
4208 const QRect r = region.d->qt_rgn->rects.at(i);
4209 if (r.width() * r.height() > maxArea)
4210 maxArea = r.width() * r.height();
4211 }
4212
4213 if (maxArea > region.d->qt_rgn->innerArea) {
4214 qDebug() << "not largest rectangle" << region << region.d->qt_rgn->innerRect;
4215 }
4216 Q_ASSERT(maxArea <= region.d->qt_rgn->innerArea);
4217#endif
4218
4219 const QRect r1 = region.d->qt_rgn->innerRect;
4220 return (rect.left() >= r1.left() && rect.right() <= r1.right()
4221 && rect.top() >= r1.top() && rect.bottom() <= r1.bottom());
4222}
4223
4224QRegion::const_iterator QRegion::begin() const noexcept
4225{
4226 return d->qt_rgn ? d->qt_rgn->begin() : nullptr;
4227}
4228
4229QRegion::const_iterator QRegion::end() const noexcept
4230{
4231 return d->qt_rgn ? d->qt_rgn->end() : nullptr;
4232}
4233
4235void set_rects_warn(const char *what)
4236{
4237 qWarning("QRegion::setRects(): %s", what);
4238}
4239
4240void QRegion::setRects(const QRect *r, int n)
4241{
4242 if (!r && n) { // old setRects() allowed this, but QSpan doesn't
4243 set_rects_warn("passing num != 0 when rects == nullptr is deprecated.");
4244 n = 0;
4245 }
4246 setRects(QSpan<const QRect>(r, n));
4247}
4248
4249void QRegion::setRects(QSpan<const QRect> rects)
4250{
4251 const auto num = int(rects.size());
4252 if (num != rects.size()) {
4253 set_rects_warn("span size exceeds INT_MAX, ignoring");
4254 return;
4255 }
4256
4257 *this = QRegion();
4258 if (!rects.data() || num == 0 || (num == 1 && rects.front().isEmpty()))
4259 return;
4260
4261 detach();
4262
4263 d->qt_rgn->numRects = num;
4264 if (num == 1) {
4265 d->qt_rgn->extents = rects.front();
4266 d->qt_rgn->innerRect = rects.front();
4267 } else {
4268 d->qt_rgn->rects.resize(num);
4269
4270 int left = INT_MAX,
4271 right = INT_MIN,
4272 top = INT_MAX,
4273 bottom = INT_MIN;
4274 for (int i = 0; i < num; ++i) {
4275 const QRect &rect = rects[i];
4276 d->qt_rgn->rects[i] = rect;
4277 left = qMin(rect.left(), left);
4278 right = qMax(rect.right(), right);
4279 top = qMin(rect.top(), top);
4280 bottom = qMax(rect.bottom(), bottom);
4281 d->qt_rgn->updateInnerRect(rect);
4282 }
4283 d->qt_rgn->extents = QRect(QPoint(left, top), QPoint(right, bottom));
4284 }
4285}
4286
4287/*!
4288 \since 6.8
4289
4290 Returns a span of non-overlapping rectangles that make up the region. The
4291 span remains valid until the next call of a mutating (non-const) method on
4292 this region.
4293
4294 The union of all the rectangles is equal to the original region.
4295
4296 \note This functions existed in Qt 5, too, but returned QVector<QRect>
4297 instead.
4298
4299 \sa setRects()
4300*/
4301QSpan<const QRect> QRegion::rects() const noexcept
4302{
4303 return {begin(), end()};
4304};
4305
4306int QRegion::rectCount() const noexcept
4307{
4308 return (d->qt_rgn ? d->qt_rgn->numRects : 0);
4309}
4310
4311bool QRegion::operator==(const QRegion &r) const
4312{
4313 if (!d->qt_rgn)
4314 return r.isEmpty();
4315 if (!r.d->qt_rgn)
4316 return isEmpty();
4317
4318 if (d == r.d)
4319 return true;
4320 else
4321 return EqualRegion(d->qt_rgn, r.d->qt_rgn);
4322}
4323
4324bool QRegion::intersects(const QRect &rect) const
4325{
4326 if (isEmptyHelper(d->qt_rgn) || rect.isNull())
4327 return false;
4328
4329 const QRect r = rect.normalized();
4330 if (!rect_intersects(d->qt_rgn->extents, r))
4331 return false;
4332 if (d->qt_rgn->numRects == 1)
4333 return true;
4334
4335 for (const QRect &rect : *this) {
4336 if (rect_intersects(r, rect))
4337 return true;
4338 }
4339 return false;
4340}
4341
4342#if defined(Q_OS_WIN) || defined(Q_QDOC)
4343
4344static inline HRGN qt_RectToHRGN(const QRect &rc)
4345{
4346 return CreateRectRgn(rc.left(), rc.top(), rc.right() + 1, rc.bottom() + 1);
4347}
4348
4349/*!
4350 \since 6.0
4351
4352 Returns a HRGN that is equivalent to the given region.
4353*/
4354HRGN QRegion::toHRGN() const
4355{
4356 const int size = rectCount();
4357 if (size == 0)
4358 return nullptr;
4359
4360 HRGN resultRgn = nullptr;
4361 const auto rects = begin();
4362 resultRgn = qt_RectToHRGN(rects[0]);
4363 for (int i = 1; i < size; ++i) {
4364 HRGN tmpRgn = qt_RectToHRGN(rects[i]);
4365 int err = CombineRgn(resultRgn, resultRgn, tmpRgn, RGN_OR);
4366 if (err == ERROR)
4367 qWarning("Error combining HRGNs.");
4368 DeleteObject(tmpRgn);
4369 }
4370 return resultRgn;
4371}
4372
4373/*!
4374 \since 6.0
4375
4376 Returns a QRegion that is equivalent to the given \a hrgn.
4377 */
4378QRegion QRegion::fromHRGN(HRGN hrgn)
4379{
4380 DWORD regionDataSize = GetRegionData(hrgn, 0, nullptr);
4381 if (regionDataSize == 0)
4382 return QRegion();
4383
4384 auto regionData = reinterpret_cast<LPRGNDATA>(malloc(regionDataSize));
4385 if (!regionData)
4386 return QRegion();
4387
4388 QRegion region;
4389 if (GetRegionData(hrgn, regionDataSize, regionData) == regionDataSize) {
4390 auto pRect = reinterpret_cast<LPRECT>(regionData->Buffer);
4391 for (DWORD i = 0; i < regionData->rdh.nCount; ++i)
4392 region += QRect(pRect[i].left, pRect[i].top,
4393 pRect[i].right - pRect[i].left,
4394 pRect[i].bottom - pRect[i].top);
4395 }
4396
4397 free(regionData);
4398 return region;
4399}
4400#endif // Q_OS_WIN || Q_QDOC
4401
4402QT_END_NAMESPACE
\inmodule QtGui
\inmodule QtCore\reentrant
Definition qpoint.h:30
Combined button and popup list for selecting options.
#define AddSpan
#define QRGN_AND
Definition qregion.cpp:189
static bool canMergeFromBelow(const QRect *top, const QRect *bottom, const QRect *nextToTop, const QRect *nextToBottom)
Definition qregion.cpp:1196
#define QRGN_TRANSLATE
Definition qregion.cpp:187
static void miSubtractO(QRegionPrivate &dest, const QRect *r1, const QRect *r1End, const QRect *r2, const QRect *r2End, int y1, int y2)
Definition qregion.cpp:2485
Q_DECLARE_TYPEINFO(Segment, Q_PRIMITIVE_TYPE)
#define MERGERECT(r)
static bool isEmptyHelper(const QRegionPrivate *preg)
Definition qregion.cpp:1159
static void OffsetRegion(QRegionPrivate &region, int x, int y)
Definition qregion.cpp:1878
static bool canMergeFromLeft(const QRect *right, const QRect *left)
Definition qregion.cpp:1171
static QRect qt_rect_intersect_normalized(const QRect &r1, const QRect &r2)
Definition qregion.cpp:1234
#define SMALL_COORDINATE
Definition qregion.cpp:3111
static Q_DECL_COLD_FUNCTION void set_rects_warn(const char *what)
Definition qregion.cpp:4235
static bool canMergeFromRight(const QRect *left, const QRect *right)
Definition qregion.cpp:1164
#define LARGE_COORDINATE
Definition qregion.cpp:3110
#define RectangleOut
Definition qregion.cpp:1603
static bool EqualRegion(const QRegionPrivate *r1, const QRegionPrivate *r2)
Definition qregion.cpp:2641
static void XorRegion(QRegionPrivate *sra, QRegionPrivate *srb, QRegionPrivate &dest)
Definition qregion.cpp:2607
static int miCoalesce(QRegionPrivate &dest, int prevStart, int curStart)
Definition qregion.cpp:1974
static void CreateETandAET(int count, const QPoint *pts, EdgeTable *ET, EdgeTableEntry *AET, EdgeTableEntry *pETEs, ScanLineListBlock *pSLLBlock)
Definition qregion.cpp:3203
static bool PointInRegion(QRegionPrivate *pRegion, int x, int y)
Definition qregion.cpp:2672
#define EXTENTCHECK(r1, r2)
Definition qregion.cpp:1670
#define EvenOddRule
Definition qregion.cpp:1606
#define QRGN_SETELLIPSE
Definition qregion.cpp:184
static void flushRow(const QRegionSpan *spans, int y, int numSpans, QRegionPrivate *reg, int *lastRow, int *extendTo, bool *needsExtend)
Definition qregion.cpp:3422
#define QRGN_OR
Definition qregion.cpp:188
#define QRGN_SETPTARRAY_ALT
Definition qregion.cpp:185
#define EVALUATEEDGEEVENODD(pAET, pPrevAET, y)
Definition qregion.cpp:3045
#define QRGN_XOR
Definition qregion.cpp:191
static QRegionPrivate * PolygonRegion(const QPoint *Pts, int Count, int rule)
Definition qregion.cpp:3536
#define NUMPTSTOBUFFER
Definition qregion.cpp:1705
static bool RectInRegion(QRegionPrivate *region, int rx, int ry, uint rwidth, uint rheight)
Definition qregion.cpp:2699
static int InsertionSort(EdgeTableEntry *AET)
Definition qregion.cpp:3367
#define BRESINITPGON(dy, x1, x2, xStart, d, m, m1, incr1, incr2)
Definition qregion.cpp:2846
QRegionPrivate * qt_bitmapToRegion(const QBitmap &bitmap)
Definition qregion.cpp:3740
QDebug operator<<(QDebug s, const QRegion &r)
Definition qregion.cpp:357
static void loadAET(EdgeTableEntry *AET, EdgeTableEntry *ETEs)
Definition qregion.cpp:3289
static void miUnionO(QRegionPrivate &dest, const QRect *r1, const QRect *r1End, const QRect *r2, const QRect *r2End, int y1, int y2)
Definition qregion.cpp:2362
#define BRESINITPGONSTRUCT(dmaj, min1, min2, bres)
Definition qregion.cpp:2910
#define MEMCHECK(dest, rect, firstrect)
Definition qregion.cpp:1693
void(*) OverlapFunc(QRegionPrivate &dest, const QRect *r1, const QRect *r1End, const QRect *r2, const QRect *r2End, int y1, int y2)
Definition qregion.cpp:1592
#define BRESINCRPGONSTRUCT(bres)
Definition qregion.cpp:2914
static void miSubtractNonO1(QRegionPrivate &dest, const QRect *r, const QRect *rEnd, int y1, int y2)
Definition qregion.cpp:2451
#define SLLSPERBLOCK
Definition qregion.cpp:3000
bool rect_intersects(const QRect &r1, const QRect &r2)
Definition qregion.cpp:595
Q_DECLARE_TYPEINFO(QRegionSpan, Q_PRIMITIVE_TYPE)
#define QRGN_SETRECT
Definition qregion.cpp:183
static void UnionRectWithRegion(const QRect *rect, const QRegionPrivate *source, QRegionPrivate &dest)
Definition qregion.cpp:1796
static void UnionRegion(const QRegionPrivate *reg1, const QRegionPrivate *reg2, QRegionPrivate &dest)
Definition qregion.cpp:2408
static void PtsToRegion(int numFullPtBlocks, int iCurPtBlock, POINTBLOCK *FirstPtBlock, QRegionPrivate *reg)
Definition qregion.cpp:3466
static void computeWAET(EdgeTableEntry *AET)
Definition qregion.cpp:3333
#define QRGN_SETPTARRAY_WIND
Definition qregion.cpp:186
static void FreeStorage(ScanLineListBlock *pSLLBlock)
Definition qregion.cpp:3400
static void miSetExtents(QRegionPrivate &dest)
Definition qregion.cpp:1829
static void InsertEdgeInET(EdgeTable *ET, EdgeTableEntry *ETE, int scanline, ScanLineListBlock **SLLBlock, int *iSLLBlock)
Definition qregion.cpp:3122
#define QRGN_SUB
Definition qregion.cpp:190
#define QRGN_RECTS
Definition qregion.cpp:192
#define EVALUATEEDGEWINDING(pAET, pPrevAET, y, fixWAET)
Definition qregion.cpp:3022
static void SubtractRegion(QRegionPrivate *regM, QRegionPrivate *regS, QRegionPrivate &dest)
Definition qregion.cpp:2586
#define WindingRule
Definition qregion.cpp:1607
void(*) NonOverlapFunc(QRegionPrivate &dest, const QRect *r, const QRect *rEnd, int y1, int y2)
Definition qregion.cpp:1594
static void miUnionNonO(QRegionPrivate &dest, const QRect *r, const QRect *rEnd, int y1, int y2)
Definition qregion.cpp:2326
#define BRESINCRPGON(d, minval, m, m1, incr1, incr2)
Definition qregion.cpp:2872
Q_GUI_EXPORT bool qt_region_strictContains(const QRegion &region, const QRect &rect)
Definition qregion.cpp:4192
static void miIntersectO(QRegionPrivate &dest, const QRect *r1, const QRect *r1End, const QRect *r2, const QRect *r2End, int y1, int y2)
Definition qregion.cpp:1909
static void miRegionOp(QRegionPrivate &dest, const QRegionPrivate *reg1, const QRegionPrivate *reg2, OverlapFunc overlapFunc, NonOverlapFunc nonOverlap1Func, NonOverlapFunc nonOverlap2Func)
Definition qregion.cpp:2103
int minor_axis
Definition qregion.cpp:2903
ScanLineList scanlines
Definition qregion.cpp:2991
void prepend(const QRect *r)
Definition qregion.cpp:1475
bool canPrepend(const QRegionPrivate *r) const
Definition qregion.cpp:1546
constexpr QRegionPrivate()
Definition qregion.cpp:1080
bool mergeFromAbove(QRect *bottom, const QRect *top, const QRect *nextToBottom, const QRect *nextToTop)
Definition qregion.cpp:1222
const QRect * end() const noexcept
Definition qregion.cpp:1133
const QRect * begin() const noexcept
Definition qregion.cpp:1130
bool canAppend(const QRegionPrivate *r) const
Definition qregion.cpp:1524
bool within(const QRect &r1) const
Definition qregion.cpp:1108
bool contains(const QRect &r2) const
Definition qregion.cpp:1099
void append(const QRegionPrivate *r)
Definition qregion.cpp:1329
bool mergeFromRight(QRect *left, const QRect *right)
Definition qregion.cpp:1176
void updateInnerRect(const QRect &rect)
Definition qregion.cpp:1114
bool contains(const QRegionPrivate &r) const
Definition qregion.cpp:1095
void append(const QRect *r)
Definition qregion.cpp:1298
bool canAppend(const QRect *r) const
Definition qregion.cpp:1507
QRegionPrivate(const QRect &r)
Definition qregion.cpp:1081
bool mergeFromLeft(QRect *left, const QRect *right)
Definition qregion.cpp:1186
bool canPrepend(const QRect *r) const
Definition qregion.cpp:1529
bool mergeFromBelow(QRect *top, const QRect *bottom, const QRect *nextToTop, const QRect *nextToBottom)
Definition qregion.cpp:1210
QList< QRect > rects
Definition qregion.cpp:1076
void prepend(const QRegionPrivate *r)
Definition qregion.cpp:1402
void intersect(const QRect &r)
Definition qregion.cpp:1245
QRegionSpan(int x1_, int x2_)
Definition qregion.cpp:3413
int width() const
Definition qregion.cpp:3417
struct _EdgeTableEntry * nextWETE
Definition qregion.cpp:2977
struct _EdgeTableEntry * back
Definition qregion.cpp:2976
struct _EdgeTableEntry * next
Definition qregion.cpp:2975
char data[NUMPTSTOBUFFER *sizeof(QPoint)]
Definition qregion.cpp:1712
QPoint * pts
Definition qregion.cpp:1713
struct _POINTBLOCK * next
Definition qregion.cpp:1714
struct _ScanLineListBlock * next
Definition qregion.cpp:3004
ScanLineList SLLs[SLLSPERBLOCK]
Definition qregion.cpp:3003
EdgeTableEntry * edgelist
Definition qregion.cpp:2983
struct _ScanLineList * next
Definition qregion.cpp:2984