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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
/****************************************************************************
**
** This file is part of the LibreCAD project, a 2D CAD program
**
** Copyright (C) 2025 Dongxu Li (github.com/dxli)
** Copyright (C) 2010 R. van Twisk (librecad@rvt.dds.nl)
** Copyright (C) 2001-2003 RibbonSoft. All rights reserved.
**
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file gpl-2.0.txt included in the
** packaging of this file.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
** This copyright notice MUST APPEAR in all copies of the script!
**
**********************************************************************/

#include <cmath>
#include <iostream>
#include <set>

#include <QList>
#include <QObject>

#include "lc_containertraverser.h"
#include "lc_looputils.h"
#include "qg_dialogfactory.h"
#include "rs_constructionline.h"
#include "rs_debug.h"
#include "rs_dialogfactory.h"
#include "rs_dimension.h"
#include "rs_ellipse.h"
#include "rs_entitycontainer.h"
#include "rs_information.h"
#include "rs_insert.h"
#include "rs_layer.h"
#include "rs_line.h"
#include "rs_painter.h"
#include "rs_solid.h"
#include "rs_vector.h"

class RS_Dimension;

namespace {

// the tolerance used to check topology of contours in hatching
    constexpr double contourTolerance = 1e-8;

// For validate hatch contours, whether an entity in the contour is a closed
// loop itself
    bool isClosedLoop(RS_Entity &entity) {
        switch (entity.rtti()) {
            case RS2::EntityCircle:
                // Sub containers are always closed
            case RS2::EntityContainer:
                return true;
            case RS2::EntityEllipse:
                return !static_cast<RS_Ellipse *>(&entity)->isArc();
            default:
                return false;
        }
    }

// Find the nearest distance between the endpoints of an entity to a given point
    double endPointDistance(const RS_Vector &point, const RS_Entity &entity) {
        double distance = RS_MAXDOUBLE;
        entity.getNearestEndpoint(point, &distance);
        return distance;
    }
}

/**
 * Default constructor.
 *
 * @param owner True if we own and also delete the entities.
 */
RS_EntityContainer::RS_EntityContainer(RS_EntityContainer *parent,  bool owner):
    RS_Entity(parent){
    autoDelete = owner;
    //    RS_DEBUG->print("RS_EntityContainer::RS_EntityContainer: "
    //                    "owner: %d", (int)owner);
    subContainer = nullptr;
    //autoUpdateBorders = true;
    entIdx = -1;
}
/**
 * Copy constructor. Makes a deep copy of all entities.
 */

RS_EntityContainer::RS_EntityContainer(const RS_EntityContainer& other):
    RS_Entity{other}
    , subContainer{other.subContainer}
    , m_entities{other.m_entities}
    , m_autoUpdateBorders{other.m_autoUpdateBorders}
    , entIdx{other.entIdx}
    , autoDelete{other.autoDelete}{
    if (autoDelete) { // fixme - sand - check this logic, looks suspicious!
        for(auto it = begin(); it != end(); ++it) {
            if ((*it)->isContainer()) {
                *it = (*it)->clone();
            }
        }
    }
}

RS_EntityContainer::RS_EntityContainer(const RS_EntityContainer& other, bool copyChildren) :
    RS_Entity{other}{
    subContainer = nullptr;
    m_autoUpdateBorders = other.m_autoUpdateBorders;
    entIdx = other.entIdx;
    autoDelete = other.autoDelete;
    if (copyChildren) {
        m_entities = other.m_entities;
        if (autoDelete) {  // fixme - sand - check this logic, looks suspicious!
            for(auto it = begin(); it != end(); ++it) {
                if ((*it)->isContainer()) {
                    *it = (*it)->clone();
                }
            }
        }
    }
}



RS_EntityContainer& RS_EntityContainer::operator = (const RS_EntityContainer& other){
    this->RS_Entity::operator = (other);
    subContainer=other.subContainer;
    m_entities = other.m_entities;
    m_autoUpdateBorders = other.m_autoUpdateBorders;
    entIdx = other.entIdx;
    autoDelete = other.autoDelete;
    if (autoDelete) {
        for(auto it = begin(); it != end(); ++it) {
            if ((*it)->isContainer()) {
                *it = (*it)->clone();
            }
        }
    }
    return *this;
}

RS_EntityContainer::RS_EntityContainer(RS_EntityContainer&& other):
    RS_Entity{other}
    , subContainer{other.subContainer}
    , m_entities{std::move(other.m_entities)}
    , m_autoUpdateBorders{other.m_autoUpdateBorders}
    , entIdx{other.entIdx}
    , autoDelete{other.autoDelete}{
}

RS_EntityContainer& RS_EntityContainer::operator = (RS_EntityContainer&& other){
    this->RS_Entity::operator = (other);
    subContainer=other.subContainer;
    m_entities = std::move(other.m_entities);
    m_autoUpdateBorders = other.m_autoUpdateBorders;
    entIdx = other.entIdx;
    autoDelete = other.autoDelete;
    return *this;
}

/**
 * Destructor.
 */
RS_EntityContainer::~RS_EntityContainer() {
    if (autoDelete) {
        while (!m_entities.isEmpty())
            delete m_entities.takeFirst();
    } else {
        m_entities.clear();
    }
}

RS_Entity *RS_EntityContainer::clone() const {
    RS_DEBUG->print("RS_EntityContainer::clone: ori autoDel: %d",autoDelete);

    auto *ec = new RS_EntityContainer(getParent(), isOwner());
    if (isOwner()) {
        for (const RS_Entity *entity: std::as_const(m_entities)) {
            if (entity != nullptr) {
                ec->m_entities.push_back(entity->clone());
            }
        }
    } else {
        ec->m_entities = m_entities;
    }

    RS_DEBUG->print("RS_EntityContainer::clone: clone autoDel: %d",ec->isOwner());

    ec->detach();
    return ec;
}

RS_Entity *RS_EntityContainer::cloneProxy() const {
    RS_DEBUG->print("RS_EntityContainer::cloneproxy: ori autoDel: %d", autoDelete);

    auto *ec = new RS_EntityContainer(getParent(), isOwner());
    if (isOwner()) {
        for (const RS_Entity *entity: std::as_const(m_entities)) {
            if (entity != nullptr) {
                ec->m_entities.push_back(entity->cloneProxy());
            }
        }
    } else {
        ec->m_entities = m_entities;
    }

    RS_DEBUG->print("RS_EntityContainer::cloneproxy: clone autoDel: %d", ec->isOwner());

    ec->detach();
    return ec;
}

/**
 * Detaches shallow copies and creates deep copies of all subentities.
 * This is called after cloning entity containers.
 */
void RS_EntityContainer::detach() {
    QList<RS_Entity *> tmp;
    bool autoDel = isOwner();
    RS_DEBUG->print("RS_EntityContainer::detach: autoDel: %d",(int) autoDel);
    setOwner(false);

    // make deep copies of all entities:
    for(RS_Entity* e: *this) {
        if (!e->getFlag(RS2::FlagTemp)) {
            tmp.append(e->clone());
        }
    }

    // clear shared pointers:
    clear();
    setOwner(autoDel);

    // point to new deep copies:
    for(RS_Entity* e: tmp) {
        push_back(e);
        e->reparent(this);
    }
}

void RS_EntityContainer::reparent(RS_EntityContainer *parent) {
    RS_Entity::reparent(parent);

    // All sub-entities:
    for (RS_Entity* e: *this) {
        e->reparent(parent);
    }
}

void RS_EntityContainer::setVisible(bool v) {
    //    RS_DEBUG->print("RS_EntityContainer::setVisible: %d", v);
    RS_Entity::setVisible(v);

    // All sub-entities:
    for (auto e: std::as_const(m_entities)) {
        //        RS_DEBUG->print("RS_EntityContainer::setVisible: subentity: %d", v);
        e->setVisible(v);
    }
}

/**
 * @return Total length of all m_entities in this container.
 */
double RS_EntityContainer::getLength() const {
    double ret = 0.0;

    for (RS_Entity* e: *this) {
        if (e->isVisible()) {
            double length = e->getLength();
            if (std::signbit(length)) {
                ret = -1.0;
                break;
            } else {
                ret += length;
            }
        }
    }

    return ret;
}

/**
 * Selects this entity.
 */
bool RS_EntityContainer::setSelected(bool select) {
    // This entity's select:
    if (RS_Entity::setSelected(select)) {
        // All sub-entity's select:
        for (RS_Entity* e: *this) {
            if (e->isVisible()) {
                e->setSelected(select);
            }
        }
        return true;
    }
    return false;
}

/**
 * Toggles select on this entity.
 */
bool RS_EntityContainer::toggleSelected() {
    // Toggle this entity's select:
    return RS_Entity::toggleSelected();
}

void RS_EntityContainer::setHighlighted(bool on){
    for (RS_Entity* e: *this) {
        e->setHighlighted(on);
    }
    RS_Entity::setHighlighted(on);
}

/**
 * Selects all entities within the given area.
 *
 * @param select True to select, False to invertSelectionOperation the entities.
 */
 // todo - sand - ucs - add method for selecting entities within rect that is rotated in wcs
 // Such method is needed for better support UCS with rotation and more precise selection of m_entities.
void RS_EntityContainer::selectWindow(
    enum RS2::EntityType typeToSelect, RS_Vector v1, RS_Vector v2,
    bool select, bool cross){
    for (RS_Entity* e: *this) {
        bool included = false;
        if (e->isVisible()) {
            if (e->isInWindow(v1, v2)) {
                //e->setSelected(select);
                included = true;
            } else if (cross) {
                RS_EntityContainer l;
                l.addRectangle(v1, v2);
                RS_VectorSolutions sol;

                if (e->isContainer()) {
                    auto *ec = (RS_EntityContainer *) e;
                    lc::LC_ContainerTraverser traverser{*ec, RS2::ResolveAll};
                    for (RS_Entity *se = traverser.first(); se != nullptr && !included; se = traverser.next()){
                        if (se->rtti() == RS2::EntitySolid) {
                            included = static_cast<RS_Solid *>(se)->isInCrossWindow(v1, v2);
                        } else {
                            for (RS_Entity* line: l) {
                                sol = RS_Information::getIntersection(se, line, true);
                                if (sol.hasValid()) {
                                    included = true;
                                    break;
                                }
                            }
                        }
                    }
                } else if (e->rtti() == RS2::EntitySolid) {
                    included = static_cast<RS_Solid *>(e)->isInCrossWindow(v1, v2);
                } else {
                    for (RS_Entity* line: l) {
                        sol = RS_Information::getIntersection(e, line, true);
                        if (sol.hasValid()) {
                            included = true;
                            break;
                        }
                    }
                }
            }
        }

        if (included) {
            if (typeToSelect != RS2::EntityType::EntityUnknown) {
                if (typeToSelect == e->rtti()) {
                    e->setSelected(select);
                } else {
                    //Do not select
                }
            } else {
                e->setSelected(select);
            }
        }
    }
}
/**
 * Selects all entities within the given area with given types.
 *
 * @param select True to select, False to invertSelectionOperation the entities.
 */
void RS_EntityContainer::selectWindow(
    const QList<RS2::EntityType> &typesToSelect, RS_Vector v1, RS_Vector v2,
    bool select, bool cross){
    for (RS_Entity* e: *this) {
        if (!typesToSelect.contains(e->rtti())){
            continue;
        }
        bool included = false;
        if (e->isVisible()) {
            if (e->isInWindow(v1, v2)) {
                //e->setSelected(select);
                included = true;
            } else if (cross) {
                RS_EntityContainer l;
                l.addRectangle(v1, v2);
                RS_VectorSolutions sol;

                if (e->isContainer()) {
                    auto *ec = (RS_EntityContainer *) e;
                    lc::LC_ContainerTraverser traverser{*ec, RS2::ResolveAll};
                    for (RS_Entity* se = traverser.first(); se != nullptr && !included; se = traverser.next()) {
                        if (se->rtti() == RS2::EntitySolid) {
                            included = dynamic_cast<RS_Solid *>(se)->isInCrossWindow(v1, v2);
                        } else {
                            for (auto line: l) {
                                sol = RS_Information::getIntersection(
                                    se, line, true);
                                if (sol.hasValid()) {
                                    included = true;
                                    break;
                                }
                            }
                        }
                    }
                } else if (e->rtti() == RS2::EntitySolid) {
                    included = dynamic_cast<RS_Solid *>(e)->isInCrossWindow(v1, v2);
                } else {
                    for (auto line: l) {
                        sol = RS_Information::getIntersection(e, line, true);
                        if (sol.hasValid()) {
                            included = true;
                            break;
                        }
                    }
                }
            }
        }

        if (included) {
          /*  if (typeToSelect != RS2::EntityType::EntityUnknown) {
                if (typeToSelect == e->rtti()) {
                    e->setSelected(select);
                } else {
                    //Do not select
                }
            } else {*/
                e->setSelected(select);
//            }
        }
    }
}

/**
 * Adds a entity to this container and updates the borders of this
 * entity-container if autoUpdateBorders is true.
 */
void RS_EntityContainer::addEntity(RS_Entity *entity) {
    /*
       if (isDocument()) {
           RS_LayerList* lst = getDocument()->getLayerList();
           if (lst) {
               RS_Layer* l = lst->getActive();
               if (l && l->isLocked()) {
                   return;
               }
           }
       }
    */

    if (entity == nullptr) {
        return;
    }
    if (entity->rtti() == RS2::EntityImage || entity->rtti() == RS2::EntityHatch) {
        m_entities.prepend(entity);
    } else {
        m_entities.append(entity);
    }
    adjustBordersIfNeeded(entity);
}

/**
 * Insert a entity at the end of entities list and updates the
 * borders of this entity-container if autoUpdateBorders is true.
 */
void RS_EntityContainer::appendEntity(RS_Entity *entity) {
    if (entity == nullptr) {
        return;
    }
    m_entities.append(entity);
    adjustBordersIfNeeded(entity);
}

/**
 * Insert a entity at the start of entities list and updates the
 * borders of this entity-container if autoUpdateBorders is true.
 */
void RS_EntityContainer::prependEntity(RS_Entity *entity) {
    if (entity == nullptr) {
        return;
    }
    m_entities.prepend(entity);
    adjustBordersIfNeeded(entity);
}

/**
 * Move a entity list in this container at the given position,
 * the borders of this entity-container if autoUpdateBorders is true.
 */
void RS_EntityContainer::moveEntity(int index, QList<RS_Entity *> &entList) {
    if (entList.isEmpty()) {
        return;
    }
    int ci = 0; //current index for insert without invert order
    bool into = false;
    RS_Entity *mid = nullptr;
    if (index < 1) {
        ci = 0;
    } else if (index >= m_entities.size()) {
        ci = m_entities.size() - entList.size();
    } else {
        into = true;
        mid = m_entities.at(index);
    }

    for (int i = 0; i < entList.size(); ++i) {
        RS_Entity *e = entList.at(i);
        bool ret = m_entities.removeOne(e);
        //if e not exist in entities list remove from entList
        if (!ret) {
            entList.removeAt(i);
        }
    }
    if (into) {
        ci = m_entities.indexOf(mid);
    }

    for (auto e: entList) {
        m_entities.insert(ci++, e);
    }
}

void RS_EntityContainer::adjustBordersIfNeeded(RS_Entity* entity) {
    if (m_autoUpdateBorders) {
        adjustBorders(entity);
    }
}

/**
 * Inserts a entity to this container at the given position and updates
 * the borders of this entity-container if autoUpdateBorders is true.
 */
void RS_EntityContainer::insertEntity(int index, RS_Entity *entity) {
    if (entity == nullptr) {
        return;
    }

    m_entities.insert(index, entity);
    adjustBordersIfNeeded(entity);
}
/**
 * Removes an entity from this container and updates the borders of
 * this entity-container if autoUpdateBorders is true.
 */
bool RS_EntityContainer::removeEntity(RS_Entity *entity) {
    //RLZ TODO: in Q3PtrList if 'entity' is nullptr remove the current item-> at.(entIdx)
    //    and sets 'entIdx' in next() or last() if 'entity' is the last item in the list.
    //    in LibreCAD is never called with nullptr
    bool ret = m_entities.removeOne(entity);

    if (autoDelete && ret) {
        delete entity;
    }
    calculateBordersIfNeeded();
    return ret;
}

/**
 * Erases all entities in this container and resets the borders..
 */
void RS_EntityContainer::clear() {
    if (autoDelete) {
        while (!m_entities.isEmpty()) {
            RS_Entity * en = m_entities.takeFirst();
            delete en;
        }
    } else {
        m_entities.clear();
    }
    resetBorders();
}

unsigned int RS_EntityContainer::count() const {
    return m_entities.size();
}

/**
 * Counts all entities (leaves of the tree).
 */
unsigned int RS_EntityContainer::countDeep() const {
    unsigned int c = 0;
    for (auto t: *this) {
        c += t->countDeep();
    }
    return c;
}

/**
 * Counts the selected entities in this container.
 */
unsigned RS_EntityContainer::countSelected(bool deep, QList<RS2::EntityType> const &types) {
    unsigned count = 0;
    std::set<RS2::EntityType> type{types.cbegin(), types.cend()};

    for (RS_Entity *entity: *this) {
        if (entity->isSelected()) {
            if (!types.size() || type.count(entity->rtti())) {
                count++;
            }
        }
        if (entity->isContainer()) {
            count += dynamic_cast<RS_EntityContainer *>(entity)->countSelected(deep); // fixme - hm... - what about entity types there? and deep flag?
        }
    }
    return count;
}

void RS_EntityContainer::collectSelected(std::vector<RS_Entity*> &collect, bool deep, QList<RS2::EntityType> const &types) {    
    std::set<RS2::EntityType> type{types.cbegin(), types.cend()};
    for (RS_Entity *e: std::as_const(m_entities)) {
        if (e != nullptr) {
            if (e->isSelected()) {
                if (types.empty() || type.count(e->rtti())) {
                    collect.push_back(e);
                }
                if (deep && e->isContainer()) {
                    auto *container = dynamic_cast<RS_EntityContainer *>(e);
                    container->collectSelected(collect, false); // todo - check whether we need deep and types?
                }
            }
        }
    }
}
// fixme - sand - avoid usage in actions as it enumerates all entities. Rework or rely on entities list!!!!
RS_EntityContainer::LC_SelectionInfo RS_EntityContainer::getSelectionInfo(/*bool deep, */const QList<RS2::EntityType> &types) {
    LC_SelectionInfo result;
    std::set<RS2::EntityType> type{types.cbegin(), types.cend()};
    for (RS_Entity *e: *this) {
        if (e != nullptr) {
            if (e->isSelected()) {
                if (types.empty() || type.count(e->rtti())) {
                    result.count ++;
                    double entityLength = e->getLength();
                    if (entityLength >= 0.) {
                        result.length += entityLength;
                    }
                }
            }
        }
    }

    return result;
}

// fixme - sand - avoid usage in actions as it enumerates all entities. Rework or rely on entities list!!!!
/**
 * Counts the selected entities in this container.
 */
double RS_EntityContainer::totalSelectedLength() {
    double ret(0.0);
    for (RS_Entity *e: *this) {
        if (e->isVisible() && e->isSelected()) {
            double l = e->getLength();
            if (l >= 0.) {
                ret += l;
            }
        }
    }
    return ret;
}

/**
 * Adjusts the borders of this graphic (max/min values)
 */
void RS_EntityContainer::adjustBorders(RS_Entity *entity) {
    //RS_DEBUG->print("RS_EntityContainer::adjustBorders");
    //resetBorders();

    if (entity) {
        // make sure a container is not empty (otherwise the border
        //   would get extended to 0/0):
        if (!entity->isContainer() || entity->count() > 0) {
            minV = RS_Vector::minimum(entity->getMin(), minV);
            maxV = RS_Vector::maximum(entity->getMax(), maxV);
        }

        // Notify parents. The border for the parent might
        // also change TODO: Check for efficiency
        //if(parent) {
        //parent->adjustBorders(this);
        //}
    }
}

/**
 * Recalculates the borders of this entity container.
 */
void RS_EntityContainer::calculateBorders() {
    RS_DEBUG->print("RS_EntityContainer::calculateBorders");

    resetBorders();
    for (RS_Entity *e: *this) {
        //        RS_DEBUG->print("RS_EntityContainer::calculateBorders: "
        //                        "isVisible: %d", (int)e->isVisible());

        if (e != nullptr && e->isVisible()) {
            e->calculateBorders();
            adjustBorders(e);
        }
    }

    RS_DEBUG->print("RS_EntityContainer::calculateBorders: size 1: %f,%f",
                    getSize().x, getSize().y);

    // needed for correcting corrupt data (PLANS.dxf)
    if (minV.x > maxV.x || minV.x > RS_MAXDOUBLE || maxV.x > RS_MAXDOUBLE
        || minV.x < RS_MINDOUBLE || maxV.x < RS_MINDOUBLE) {
        minV.x = 0.0;
        maxV.x = 0.0;
    }
    if (minV.y > maxV.y || minV.y > RS_MAXDOUBLE || maxV.y > RS_MAXDOUBLE
        || minV.y < RS_MINDOUBLE || maxV.y < RS_MINDOUBLE) {
        minV.y = 0.0;
        maxV.y = 0.0;
    }

    RS_DEBUG->print("RS_EntityContainer::calculateBorders: size: %f,%f",
                    getSize().x, getSize().y);

    //RS_DEBUG->print("  borders: %f/%f %f/%f", minV.x, minV.y, maxV.x, maxV.y);

    //printf("borders: %lf/%lf  %lf/%lf\n", minV.x, minV.y, maxV.x, maxV.y);
    //RS_Entity::calculateBorders();
}

/**
 * Recalculates the borders of this entity container including
 * invisible entities.
 */
void RS_EntityContainer::forcedCalculateBorders() {
    //RS_DEBUG->print("RS_EntityContainer::calculateBorders");
    resetBorders();
    for (RS_Entity* e : *this) {
        if (e->isContainer()) {
            auto container = static_cast<RS_EntityContainer*>(e);
            container->forcedCalculateBorders();
        }
        else {
            e->calculateBorders();
        }
        adjustBorders(e);
    }

    // needed for correcting corrupt data (PLANS.dxf)
    if (minV.x > maxV.x || minV.x > RS_MAXDOUBLE || maxV.x > RS_MAXDOUBLE
        || minV.x < RS_MINDOUBLE || maxV.x < RS_MINDOUBLE) {

        minV.x = 0.0;
        maxV.x = 0.0;
    }
    if (minV.y > maxV.y || minV.y > RS_MAXDOUBLE || maxV.y > RS_MAXDOUBLE
        || minV.y < RS_MINDOUBLE || maxV.y < RS_MINDOUBLE) {

        minV.y = 0.0;
        maxV.y = 0.0;
    }

    //RS_DEBUG->print("  borders: %f/%f %f/%f", minV.x, minV.y, maxV.x, maxV.y);

    //printf("borders: %lf/%lf  %lf/%lf\n", minV.x, minV.y, maxV.x, maxV.y);
    //RS_Entity::calculateBorders();
}

/**
 * Updates all Dimension entities in this container and / or
 * reposition their labels.
 *
 * @param autoText Automatically reposition the text label bool autoText=true
 */
int RS_EntityContainer::updateDimensions(bool autoText) {
    RS_DEBUG->print("RS_EntityContainer::updateDimensions()");
    int updatedDimsCount = 0;

    for (RS_Entity *e: *this) {
        if (e->isUndone()) {
            continue;
        }
        if (e->rtti() == RS2::EntityDimLeader) {
            updatedDimsCount ++;
            e->update();
        }
        if (RS_Information::isDimension(e->rtti())) {
            auto dimension = static_cast<RS_Dimension*>(e);
            // update and reposition label:
            // dimension->updateDim(autoText);
            dimension->update();
            updatedDimsCount ++;
        }
        else if (e->isContainer()) {
            auto container = static_cast<RS_EntityContainer*>(e);
            updatedDimsCount += container->updateDimensions(autoText);
        }
    }

    RS_DEBUG->print("RS_EntityContainer::updateDimensions() OK");
    return updatedDimsCount;
}

int RS_EntityContainer::updateVisibleDimensions(bool autoText) {
    RS_DEBUG->print("RS_EntityContainer::updateVisibleDimensions()");
    int updatedDimsCount = 0;
    for (RS_Entity *e: *this) {
        if (e->isVisible()) {
            if (e->rtti() == RS2::EntityDimLeader) {
                e->update();
                updatedDimsCount ++;
            }
            else if (RS_Information::isDimension(e->rtti())) {
                auto dimension = static_cast<RS_Dimension*>(e);
                // update and reposition label:
                dimension->updateDim(autoText);
                updatedDimsCount ++;
            }
            else if (e->isContainer()) {
                auto container = static_cast<RS_EntityContainer*>(e);
                updatedDimsCount += container->updateVisibleDimensions(autoText);
            }
        }
    }

    RS_DEBUG->print("RS_EntityContainer::updateVisibleDimensions() OK");
    return updatedDimsCount;
}

/**
 * Updates all Insert entities in this container.
 */
void RS_EntityContainer::updateInserts() {
    std::string idTypeId = std::to_string(getId()) + "/" + std::to_string(rtti());
    RS_DEBUG->print("RS_EntityContainer::updateInserts() ID/type: %s", idTypeId.c_str());

    for (RS_Entity *e: std::as_const(*this)) {
        //// Only update our own inserts and not inserts of inserts
        if (e != nullptr && e->getId() != 0 && e->rtti() == RS2::EntityInsert  /*&& e->getParent()==this*/) {
            static_cast<RS_Insert*>(e)->update();

            RS_DEBUG->print("RS_EntityContainer::updateInserts: updated ID/type: %s", idTypeId.c_str());
        } else if (e != nullptr && e->isContainer()) {
            if (e->rtti() == RS2::EntityHatch) {
                RS_DEBUG->print(RS_Debug::D_DEBUGGING, "RS_EntityContainer::updateInserts: skip hatch ID/type: %s",
                                idTypeId.c_str());
            } else {
                RS_DEBUG->print("RS_EntityContainer::updateInserts: update container ID/type: %s", idTypeId.c_str());

                static_cast<RS_EntityContainer*>(e)->updateInserts();
            }
        } else {
            RS_DEBUG->print(RS_Debug::D_DEBUGGING, "RS_EntityContainer::updateInserts: skip entity ID/type: %s",
                            idTypeId.c_str());
        }
    }
    RS_DEBUG->print("RS_EntityContainer::updateInserts() ID/type: %s", idTypeId.c_str());
}

/**
 * Renames all inserts with name 'oldName' to 'newName'. This is
 *   called after a block was rename to update the inserts.
 */
void RS_EntityContainer::renameInserts(const QString &oldName,const QString &newName) {
    RS_DEBUG->print("RS_EntityContainer::renameInserts()");
    for (RS_Entity *e: std::as_const(m_entities)) {
        if (e->rtti() == RS2::EntityInsert) {
            auto *i = static_cast<RS_Insert*>(e);
            if (i->getName() == oldName) {
                i->setName(newName);
            }
        }
        if (e->isContainer()) {
            auto container = static_cast<RS_EntityContainer*>(e);
            container->renameInserts(oldName, newName);
        }
    }
    RS_DEBUG->print("RS_EntityContainer::renameInserts() OK");
}

/**
 * Updates all Spline entities in this container.
 */
void RS_EntityContainer::updateSplines() {
    RS_DEBUG->print("RS_EntityContainer::updateSplines()");
    for (RS_Entity *e: *this) {
        //// Only update our own inserts and not inserts of inserts
        if (e->rtti() == RS2::EntitySpline  /*&& e->getParent()==this*/) {
            e->update();
        } else if (e->isContainer() && e->rtti() != RS2::EntityHatch) {
            static_cast<RS_EntityContainer *>(e)->updateSplines();
        }
    }
    RS_DEBUG->print("RS_EntityContainer::updateSplines() OK");
}

/**
 * Updates the sub entities of this container.
 */
void RS_EntityContainer::update() {
    for (RS_Entity *e: *this) {
        e->update();
    }
}

void RS_EntityContainer::addRectangle(RS_Vector const &v0, RS_Vector const &v1) {
    addEntity(new RS_Line{this, v0, {v1.x, v0.y}});
    addEntity(new RS_Line{this, {v1.x, v0.y}, v1});
    addEntity(new RS_Line{this, v1, {v0.x, v1.y}});
    addEntity(new RS_Line{this, {v0.x, v1.y}, v0});
}

void RS_EntityContainer::addRectangle(RS_Vector const& v0, RS_Vector const& v1,RS_Vector const& v2, RS_Vector const& v3){
    addEntity(new RS_Line(this, v0, v1));
    addEntity(new RS_Line(this, v1, v2));
    addEntity(new RS_Line(this, v2, v3));
    addEntity(new RS_Line(this, v3, v0));
}

/**
 * Returns the first entity or nullptr if this graphic is empty.
 * @param level
 */
RS_Entity *RS_EntityContainer::firstEntity(RS2::ResolveLevel level) const {
    RS_Entity *e = nullptr;
    entIdx = -1;
    switch (level) {
        case RS2::ResolveNone: {
            if (!m_entities.isEmpty()) {
                entIdx = 0;
                return m_entities.first();
            }
            break;
        }
        case RS2::ResolveAllButInserts: {
            subContainer = nullptr;
            if (!m_entities.isEmpty()) {
                entIdx = 0;
                e = m_entities.first();
            }
            if (e && e->isContainer() && e->rtti() != RS2::EntityInsert) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->firstEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = nextEntity(level);
                }
            }
            return e;
        }
        case RS2::ResolveAllButTextImage:
        case RS2::ResolveAllButTexts: {
            subContainer = nullptr;
            if (!m_entities.isEmpty()) {
                entIdx = 0;
                e = m_entities.first();
            }
            if (e != nullptr && e->isContainer() && e->rtti() != RS2::EntityText && e->rtti() != RS2::EntityMText) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->firstEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = nextEntity(level);
                }
            }
            return e;
        }
        case RS2::ResolveAll: {
            subContainer = nullptr;
            if (!m_entities.isEmpty()) {
                entIdx = 0;
                e = m_entities.first();
            }
            if (e != nullptr && e->isContainer()) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->firstEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = nextEntity(level);
                }
            }
            return e;
        }
    }
    return nullptr;
}

/**
 * Returns the last entity or \p nullptr if this graphic is empty.
 *
 * @param level \li \p 0 Groups are not resolved
 *              \li \p 1 (default) only Groups are resolved
 *              \li \p 2 all Entity Containers are resolved
 */
RS_Entity *RS_EntityContainer::lastEntity(RS2::ResolveLevel level) const {
    RS_Entity *e = nullptr;
    if (m_entities.empty()) {
        return nullptr;
    }
    entIdx = m_entities.size() - 1;
    switch (level) {
        case RS2::ResolveNone: {
            if (!m_entities.isEmpty()) {
                return m_entities.last();
            }
            break;
        }
        case RS2::ResolveAllButInserts: {
            if (!m_entities.isEmpty()) {
                e = m_entities.last();
            }
            subContainer = nullptr;
            if (e != nullptr && e->isContainer() && e->rtti() != RS2::EntityInsert) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->lastEntity(level);
            }
            return e;
        }
        case RS2::ResolveAllButTextImage:
        case RS2::ResolveAllButTexts: {
            if (!m_entities.isEmpty()) {
                e = m_entities.last();
            }
            subContainer = nullptr;
            if (e != nullptr && e->isContainer() && e->rtti() != RS2::EntityText && e->rtti() != RS2::EntityMText) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->lastEntity(level);
            }
            return e;
        }
        case RS2::ResolveAll: {
            if (!m_entities.isEmpty()) {
                e = m_entities.last();
            }
            subContainer = nullptr;
            if (e != nullptr && e->isContainer()) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->lastEntity(level);
            }
            return e;
        }
    }
    return nullptr;
}

/**
 * Returns the next entity or container or \p nullptr if the last entity
 * returned by \p next() was the last entity in the container.
 */
RS_Entity *RS_EntityContainer::nextEntity(RS2::ResolveLevel level) const {
    //set entIdx pointing in next entity and check if is out of range
    ++entIdx;
    switch (level) {
        case RS2::ResolveNone: {
            if (entIdx < m_entities.size()) {
                return m_entities.at(entIdx);
            }
            break;
        }
        case RS2::ResolveAllButInserts: {
            RS_Entity *e = nullptr;
            if (subContainer) {
                e = subContainer->nextEntity(level);
                if (e != nullptr) {
                    --entIdx; //return a sub-entity, index not advanced
                    return e;
                } else {
                    if (entIdx < m_entities.size()) {
                        e = m_entities.at(entIdx);
                    }
                }
            } else {
                if (entIdx < m_entities.size()) {
                    e = m_entities.at(entIdx);
                }
            }
            if (e != nullptr && e->isContainer() && e->rtti() != RS2::EntityInsert) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->firstEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = nextEntity(level);
                }
            }
            return e;
        }
            break;

        case RS2::ResolveAllButTextImage:
        case RS2::ResolveAllButTexts: {
            RS_Entity *e = nullptr;
            if (subContainer) {
                e = subContainer->nextEntity(level);
                if (e != nullptr) {
                    --entIdx; //return a sub-entity, index not advanced
                    return e;
                } else {
                    if (entIdx < m_entities.size()) {
                        e = m_entities.at(entIdx);
                    }
                }
            } else {
                if (entIdx < m_entities.size()) {
                    e = m_entities.at(entIdx);
                }
            }
            if (e != nullptr && e->isContainer() && e->rtti() != RS2::EntityText && e->rtti() != RS2::EntityMText) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->firstEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = nextEntity(level);
                }
            }
            return e;
        }
        case RS2::ResolveAll: {
            RS_Entity *e = nullptr;
            if (subContainer) {
                e = subContainer->nextEntity(level);
                if (e != nullptr) {
                    --entIdx; //return a sub-entity, index not advanced
                    return e;
                } else {
                    if (entIdx < m_entities.size()) {
                        e = m_entities.at(entIdx);
                    }
                }
            } else {
                if (entIdx < m_entities.size()) {
                    e = m_entities.at(entIdx);
                }
            }
            if (e != nullptr && e->isContainer()) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->firstEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = nextEntity(level);
                }
            }
            return e;
        }
    }
    return nullptr;
}

/**
 * Returns the prev entity or container or \p nullptr if the last entity
 * returned by \p prev() was the first entity in the container.
 */
RS_Entity *RS_EntityContainer::prevEntity(RS2::ResolveLevel level) const {
    //set entIdx pointing in prev entity and check if is out of range
    --entIdx;
    switch (level) {
        case RS2::ResolveNone: {
            if (entIdx >= 0) {
                return m_entities.at(entIdx);
            }
            break;
        }
        case RS2::ResolveAllButInserts: {
            RS_Entity *e = nullptr;
            if (subContainer) {
                e = subContainer->prevEntity(level);
                if (e != nullptr) {
                    return e;
                }
                else {
                    if (entIdx >= 0) {
                        e = m_entities.at(entIdx);
                    }
                }
            }
            else {
                if (entIdx >= 0) {
                    e = m_entities.at(entIdx);
                }
            }
            if (e != nullptr && e->isContainer() && e->rtti() != RS2::EntityInsert) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->lastEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = prevEntity(level);
                }
            }
            return e;
        }
        case RS2::ResolveAllButTextImage:
        case RS2::ResolveAllButTexts: {
            RS_Entity *e = nullptr;
            if (subContainer != nullptr) {
                e = subContainer->prevEntity(level);
                if (e != nullptr) {
                    return e;
                } else {
                    if (entIdx >= 0) {
                        e = m_entities.at(entIdx);
                    }
                }
            } else {
                if (entIdx >= 0) {
                    e = m_entities.at(entIdx);
                }
            }
            if (e != nullptr && e->isContainer() && e->rtti() != RS2::EntityText && e->rtti() != RS2::EntityMText) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->lastEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = prevEntity(level);
                }
            }
            return e;
        }
        case RS2::ResolveAll: {
            RS_Entity *e = nullptr;
            if (subContainer != nullptr) {
                e = subContainer->prevEntity(level);
                if (e != nullptr) {
                    ++entIdx; //return a sub-entity, index not advanced
                    return e;
                } else {
                    if (entIdx >= 0) {
                        e = m_entities.at(entIdx);
                    }
                }
            } else {
                if (entIdx >= 0) {
                    e = m_entities.at(entIdx);
                }
            }
            if (e != nullptr && e->isContainer()) {
                subContainer = static_cast<RS_EntityContainer*>(e);
                e = subContainer->lastEntity(level);
                // empty container:
                if (e == nullptr) {
                    subContainer = nullptr;
                    e = prevEntity(level);
                }
            }
            return e;
        }
    }
    return nullptr;
}

/**
 * @return Entity at the given index or nullptr if the index is out of range.
 */
RS_Entity *RS_EntityContainer::entityAt(int index) const{
    if (m_entities.size() > index && index >= 0) {
        return m_entities.at(index);
    }
    else {
        return nullptr;
    }
}

void RS_EntityContainer::setEntityAt(int index, RS_Entity *en) {
    if (autoDelete && m_entities.at(index)) {
        delete m_entities.at(index);
    }
    m_entities[index] = en;
}

/**
 * Finds the given entity and makes it the current entity if found.
 */
int RS_EntityContainer::findEntity(RS_Entity const *const entity) {
    entIdx = m_entities.indexOf(const_cast<RS_Entity *>(entity));
    return entIdx;
}

int RS_EntityContainer::findEntityIndex(RS_Entity const *const entity) {
    return m_entities.indexOf(const_cast<RS_Entity *>(entity));
}

bool  RS_EntityContainer::areNeighborsEntities(RS_Entity const *const  e1, RS_Entity const *const  e2) {
   return abs(m_entities.indexOf(e1) - m_entities.indexOf(e2)) <= 1;
}

/**
 * @return The point which is closest to 'coord'
 * (one of the vertices)
 */
RS_Vector RS_EntityContainer::getNearestEndpoint(const RS_Vector &coord,double *dist) const{
    double minDist = RS_MAXDOUBLE;  // minimum measured distance
    double curDist = 0.;                 // currently measured distance
    RS_Vector closestPoint(false);  // closest found endpoint
    RS_Vector point;                // endpoint found

    for(RS_Entity* en : *this) {
        if (en != nullptr && en->getId() != 0 && en->isVisible()){
            auto parent = en->getParent();
            bool checkForEndpoint = true;
            if (parent != nullptr){
                checkForEndpoint = !parent->ignoredOnModification();
            }
            if (checkForEndpoint) {//no end point for Insert, text, Dim
                point = en->getNearestEndpoint(coord, &curDist);
                if (point.valid && curDist < minDist) {
                    closestPoint = point;
                    minDist = curDist;
                    if (dist) {
                        *dist = minDist;
                    }
                }
            }
        }
    }
    return closestPoint;
}

/**
 * @return The point which is closest to 'coord'
 * (one of the vertices)
 */
RS_Vector RS_EntityContainer::getNearestEndpoint(const RS_Vector &coord,double *dist, RS_Entity **pEntity) const {
    double minDist = RS_MAXDOUBLE;  // minimum measured distance
    double curDist;                 // currently measured distance
    RS_Vector closestPoint(false);  // closest found endpoint
    RS_Vector point;                // endpoint found

    for (auto en: m_entities) {
        if (en->getParent() == nullptr || !en->getParent()->ignoredOnModification()) {//no end point for Insert, text, Dim
            //            std::cout<<"find nearest for entity "<<i0<<std::endl;
            point = en->getNearestEndpoint(coord, &curDist);
            if (point.valid && curDist < minDist) {
                closestPoint = point;
                minDist = curDist;
                if (dist) {
                    *dist = minDist;
                }
                if (pEntity) {
                    *pEntity = en;
                }
            }
        }
    }
    //    std::cout<<__FILE__<<" : "<<__func__<<" : line "<<__LINE__<<std::endl;
    //    std::cout<<"count()="<<const_cast<RS_EntityContainer*>(this)->count()<<"\tminDist= "<<minDist<<"\tclosestPoint="<<closestPoint;
    //    if(pEntity ) std::cout<<"\t*pEntity="<<*pEntity;
    //    std::cout<<std::endl;
    return closestPoint;
}

RS_Vector RS_EntityContainer::getNearestPointOnEntity(const RS_Vector &coord,bool onEntity, double *dist, RS_Entity **entity) const {
    RS_Vector point(false);
    RS_Entity *en = getNearestEntity(coord, dist, RS2::ResolveNone);
    if (en && en->isVisible() && !en->getParent()->ignoredSnap() ) {
        point = en->getNearestPointOnEntity(coord, onEntity, dist, entity);
    }
    return point;
}

RS_Vector RS_EntityContainer::getNearestCenter(const RS_Vector &coord,double *dist) const {
    double minDist = RS_MAXDOUBLE;  // minimum measured distance
    double curDist = RS_MAXDOUBLE;  // currently measured distance
    RS_Vector closestPoint(false);  // closest found endpoint
    RS_Vector point;                // endpoint found

    for (auto en: m_entities) {
        if (en != nullptr && en->getId() != 0 && en->isVisible() && !en->getParent()->ignoredSnap() ) {//no center point for spline, text, Dim
            point = en->getNearestCenter(coord, &curDist);
            if (point.valid && curDist < minDist) {
                closestPoint = point;
                minDist = curDist;
            }
        }
    }
    if (dist) {
        *dist = minDist;
    }
    return closestPoint;
}

/** @return the nearest of equidistant middle points of the line. */

RS_Vector RS_EntityContainer::getNearestMiddle(const RS_Vector &coord,double *dist,int middlePoints ) const {
    double minDist = RS_MAXDOUBLE;  // minimum measured distance
    double curDist = RS_MAXDOUBLE;  // currently measured distance
    RS_Vector closestPoint(false);  // closest found endpoint
    RS_Vector point;                // endpoint found

    for (auto en: m_entities) {
        if (en->isVisible() && !en->getParent()->ignoredSnap() ) {//no midle point for spline, text, Dim
            point = en->getNearestMiddle(coord, &curDist, middlePoints);
            if (point.valid && curDist < minDist) {
                closestPoint = point;
                minDist = curDist;
            }
        }
    }
    if (dist) {
        *dist = minDist;
    }
    return closestPoint;
}

RS_Vector RS_EntityContainer::getNearestDist(double distance,const RS_Vector &coord, double *dist) const {
    RS_Entity *closestEntity = getNearestEntity(coord, nullptr, RS2::ResolveNone);
    return (closestEntity != nullptr) ?  closestEntity->getNearestDist(distance, coord, dist)
                                      : RS_Vector{false};
}

/**
 * @return The intersection which is closest to 'coord'
 */
RS_Vector RS_EntityContainer::getNearestIntersection(const RS_Vector &coord, double *dist){
    double minDist = RS_MAXDOUBLE;  // minimum measured distance
    RS_Vector closestPoint(false);  // closest found endpoint
    RS_Entity* closestEntity = getNearestEntity(coord, nullptr, RS2::ResolveAllButTextImage);

    if (closestEntity) {
        // fixme - sand - why not via traverser?
        for (RS_Entity *en = firstEntity(RS2::ResolveAllButTextImage);en;en = nextEntity(RS2::ResolveAllButTextImage)) {
            auto parent = en->getParent();
            bool ignoredSnap = false;
            if (parent != nullptr) { // may be null in block editing?
                ignoredSnap = parent->ignoredSnap();
            }
            if (!en->isVisible() || ignoredSnap) {
                continue;
            }

            RS_VectorSolutions sol = RS_Information::getIntersection(closestEntity, en, true);
            double curDist = RS_MAXDOUBLE;  // currently measured distance
            RS_Vector point = sol.getClosest(coord, &curDist, nullptr);
            if (sol.getNumber() > 0 && curDist < minDist) {
                closestPoint = point;
                minDist = curDist;
            }
        }
    }
    if (dist && closestPoint.valid) {
        *dist = minDist;
    }
    return closestPoint;
}

RS_Vector RS_EntityContainer::getNearestVirtualIntersection(const RS_Vector &coord, const double &angle, double *dist) {
    RS_Entity* closestEntity = getNearestEntity(coord, nullptr, RS2::ResolveAllButTextImage);
    if (closestEntity != nullptr) {
        RS_Vector second_coord{angle};
        RS_ConstructionLineData data(coord, coord + second_coord);
        auto line = RS_ConstructionLine(nullptr, data);

        RS_VectorSolutions sol = RS_Information::getIntersection(closestEntity, &line, true);
        if (sol.getVector().empty()) {
            return coord;
        } else {
            return sol.getClosest(coord, dist, nullptr);
        }
    } else {
        return coord;
    }
}

RS_Vector RS_EntityContainer::getNearestRef(const RS_Vector &coord, double *dist) const {
    double minDist = RS_MAXDOUBLE;  // minimum measured distance
    double curDist;                 // currently measured distance
    RS_Vector closestPoint(false);  // closest found endpoint
    RS_Vector point;                // endpoint found

    for (RS_Entity* en: *this) {
        if (en->isVisible()) {
            point = en->getNearestRef(coord, &curDist);
            if (point.valid && curDist < minDist) {
                closestPoint = point;
                minDist = curDist;
                if (dist) {
                    *dist = minDist;
                }
            }
        }
    }
    return closestPoint;
}

RS_Vector RS_EntityContainer::getNearestSelectedRef(const RS_Vector &coord, double *dist) const{
    RefInfo info = getNearestSelectedRefInfo(coord, dist);
    return info.ref;
}

RS_EntityContainer::RefInfo RS_EntityContainer::getNearestSelectedRefInfo(const RS_Vector &coord, double *dist) const {
    double minDist = RS_MAXDOUBLE;  // minimum measured distance
    RS_Vector closestPoint(false);  // closest found endpoint
    RS_Entity *closestPointEntity = nullptr;

    for (RS_Entity* en: *this) { // fixme - sand - iteration of ver all entities
        if (en->isVisible() && en->isSelected() && !en->isParentSelected()) {
            double curDist = 0.;                 // currently measured distance
            RS_Vector point = en->getNearestSelectedRef(coord, &curDist);
            if (point.valid && curDist < minDist) {
                closestPoint = point;
                closestPointEntity = en;
                minDist = curDist;
                if (dist) {
                    *dist = minDist;
                }
            }
        }
    }
    RefInfo result {closestPoint, closestPointEntity};
    return result;
}

double RS_EntityContainer::getDistanceToPoint(const RS_Vector &coord,RS_Entity **entity,RS2::ResolveLevel level,double solidDist) const{
    RS_DEBUG->print("RS_EntityContainer::getDistanceToPoint");
    double minDist = RS_MAXDOUBLE;      // minimum measured distance
    double curDist = 0.;                     // currently measured distance
    RS_Entity *closestEntity = nullptr;    // closest entity found
    RS_Entity *subEntity = nullptr;

    for (RS_Entity* e: *this) {
        auto entityLayer = e->getLayer();
        if (e->isVisible() && (entityLayer == nullptr || !entityLayer->isLocked())) {
            RS_DEBUG->print("entity: getDistanceToPoint");
            RS_DEBUG->print("entity: %d", e->rtti());
            // bug#426, need to ignore Images to find nearest intersections
            if (level == RS2::ResolveAllButTextImage && e->rtti() == RS2::EntityImage) continue;
            curDist = e->getDistanceToPoint(coord, &subEntity, level, solidDist);

            RS_DEBUG->print("entity: getDistanceToPoint: OK");

            /*
             * By using '<=', we will prefer the *last* item in the container if there are multiple
             * entities that are *exactly* the same distance away, which should tend to be the one
             * drawn most recently, and the one most likely to be visible (as it is also the order
             * that the software draws the entities). This makes a difference when one entity is
             * drawn directly over top of another, and it's reasonable to assume that humans will
             * tend to want to reference entities that they see or have recently drawn as opposed
             * to deeper more forgotten and invisible ones...
             */
            if (curDist <= minDist) {
                switch (level) {
                case RS2::ResolveAll:
                case RS2::ResolveAllButTextImage:
                    closestEntity = subEntity;
                    break;
                default:
                    closestEntity = e;
                }
                minDist = curDist;
            }
        }
    }

    if (entity != nullptr) {
        *entity = closestEntity;
    }
    RS_DEBUG->print("RS_EntityContainer::getDistanceToPoint: OK");

    return minDist;
}

RS_Entity* RS_EntityContainer::getNearestEntity(const RS_Vector& coord,double* dist,RS2::ResolveLevel level) const {
    RS_DEBUG->print("RS_EntityContainer::getNearestEntity");

    RS_Entity *e = nullptr;

    // distance for points inside solids:
    double solidDist = RS_MAXDOUBLE;
    if (dist) {
        solidDist = *dist;
    }

    double d = getDistanceToPoint(coord, &e, level, solidDist);
    if (e != nullptr && e->isVisible() == false) {
        e = nullptr;
    }

    // if d is negative, use the default distance (used for points inside solids)
    if (dist != nullptr) {
        *dist = d;
    }
    RS_DEBUG->print("RS_EntityContainer::getNearestEntity: OK");
    return e;
}

/**
 * Rearranges the atomic entities in this container in a way that connected
 * entities are stored in the right order and direction.
 * Non-recoursive. Only affects atomic entities in this container.
 *
 * @retval true all contours were closed
 * @retval false at least one contour is not closed

 * to do: find closed contour by flood-fill
 */
bool RS_EntityContainer::optimizeContours() {
    //    std::cout<<"RS_EntityContainer::optimizeContours: begin"<<std::endl;
    //    DEBUG_HEADER
    //    std::cout<<"loop with count()="<<count()<<std::endl;
    RS_DEBUG->print("RS_EntityContainer::optimizeContours");

    RS_EntityContainer tmp;
    tmp.setAutoUpdateBorders(false);
    bool closed = true;

    /** accept all full circles **/
    QList<RS_Entity *> enList;
        for(RS_Entity* e1: *this) {
            if (!e1->isEdge() || e1->isContainer()) {
                enList << e1;
                continue;
            }

            //detect circles and whole ellipses
            switch (e1->rtti()) {
                case RS2::EntityEllipse: {
                    if (dynamic_cast<RS_Ellipse *>(e1)->isEllipticArc()) {
                        continue;
                    }
                    // fall-through
                    [[fallthrough]];
                }
                case RS2::EntityCircle: {
                    //directly detect circles, bug#3443277
                    tmp.addEntity(e1->clone());
                    enList << e1;
                    // fall-through
                    [[fallthrough]];
                }
                default:
                    continue;
            }
        }
    //    std::cout<<"RS_EntityContainer::optimizeContours: 1"<<std::endl;

    /** remove unsupported entities */
    for (RS_Entity *it: std::as_const(enList)) {
        removeEntity(it);
    }

    /** check and form a closed contour **/
    //    std::cout<<"RS_EntityContainer::optimizeContours: 2"<<std::endl;
    /** the first entity **/
    RS_Entity* current(nullptr);
    if (count() > 0) {
        current = entityAt(0)->clone();
        tmp.addEntity(current);
        removeEntity(entityAt(0));
    }
    else {
        if (tmp.count() == 0) {
            return false;
        }
    }
    //    std::cout<<"RS_EntityContainer::optimizeContours: 3"<<std::endl;
    RS_Vector vpStart;
    RS_Vector vpEnd;
    if (current) {
        vpStart = current->getStartpoint();
        vpEnd = current->getEndpoint();
    }
    RS_Entity *next = nullptr;
    //    std::cout<<"RS_EntityContainer::optimizeContours: 4"<<std::endl;
    /** connect entities **/
    const auto errMsg = QObject::tr("Hatch failed due to a gap=%1 between (%2, %3) and (%4, %5)");

    while (count() > 0) {
        double dist = 0.;
        RS_Vector vpTmp = getNearestEndpoint(vpEnd, &dist, &next);
        if (dist > contourTolerance) {
            if (vpEnd.squaredTo(vpStart) < contourTolerance) {
                RS_Entity *e2 = entityAt(0);
                tmp.addEntity(e2->clone());
                vpStart = e2->getStartpoint();
                vpEnd = e2->getEndpoint();
                removeEntity(e2);
                continue;
            } else {
                // fixme - sand - isn't it a really bad dependency? check later and remove
                QG_DIALOGFACTORY->commandMessage(errMsg.arg(dist).arg(vpTmp.x).arg(vpTmp.y).arg(vpEnd.x).arg(vpEnd.y));
                RS_DEBUG->print(RS_Debug::D_ERROR, "RS_EntityContainer::optimizeContours: hatch failed due to a gap");
                closed = false;
                break;
            }
        }
        if (!next) {      //workaround if next is nullptr
            //      	    std::cout<<"RS_EntityContainer::optimizeContours: next is nullptr" <<std::endl;
            RS_DEBUG->print("RS_EntityContainer::optimizeContours: next is nullptr");
            //			closed=false;	//workaround if next is nullptr
            break;   //workaround if next is nullptr
        }      //workaround if next is nullptr
        if (closed) {
            next->setProcessed(true);
            RS_Entity *eTmp = next->clone();
            if (vpEnd.squaredTo(eTmp->getStartpoint()) > vpEnd.squaredTo(eTmp->getEndpoint())) {
                eTmp->revertDirection();
            }
            vpEnd = eTmp->getEndpoint();
            tmp.addEntity(eTmp);
            removeEntity(next);
        }
    }
    //    DEBUG_HEADER
    //    if(vpEnd.valid && vpEnd.squaredTo(vpStart) > 1e-8) {
    //		QG_DIALOGFACTORY->commandMessage(errMsg.arg(vpEnd.distanceTo(vpStart))
    //											 .arg(vpStart.x).arg(vpStart.y).arg(vpEnd.x).arg(vpEnd.y));
    //        RS_DEBUG->print("RS_EntityContainer::optimizeContours: hatch failed due to a gap");
    //        closed=false;
    //    }
    //    std::cout<<"RS_EntityContainer::optimizeContours: 5"<<std::endl;


    // add new sorted entities:
    for (RS_Entity* en: tmp) {
        en->setProcessed(false);
        addEntity(en->clone());
        en->reparent(this);
    }
    //    std::cout<<"RS_EntityContainer::optimizeContours: 6"<<std::endl;

    if (closed) {
        RS_DEBUG->print("RS_EntityContainer::optimizeContours: OK");
    } else {
        RS_DEBUG->print("RS_EntityContainer::optimizeContours: bad");
    }
    //    std::cout<<"RS_EntityContainer::optimizeContours: end: count()="<<count()<<std::endl;
    //    std::cout<<"RS_EntityContainer::optimizeContours: closed="<<closed<<std::endl;
    return closed;
}

bool RS_EntityContainer::hasEndpointsWithinWindow(const RS_Vector &v1, const RS_Vector &v2) const{
    return std::any_of(cbegin(), cend(), [&v1, &v2](const RS_Entity* entity) {
        return entity->hasEndpointsWithinWindow(v1, v2);
    });
}

void RS_EntityContainer::move(const RS_Vector &offset) {
    moveBorders(offset);
    for (RS_Entity *e: *this) {
        e->move(offset);
        adjustBorders(e);
    }
    calculateBordersIfNeeded();
}

void RS_EntityContainer::rotate(const RS_Vector &center, double angle) {
    RS_EntityContainer::rotate(center, RS_Vector{angle});
}

void RS_EntityContainer::rotate(const RS_Vector &center, const RS_Vector &angleVector) {
    resetBorders();
    for (RS_Entity *e: *this) {
        e->rotate(center, angleVector);
        adjustBorders(e);
    }
    calculateBordersIfNeeded();
}

void RS_EntityContainer::scale(const RS_Vector &center, const RS_Vector &factor) {
    if (std::abs(factor.x) > RS_TOLERANCE && std::abs(factor.y) > RS_TOLERANCE) {
        scaleBorders(center, factor);
        for (RS_Entity* e: *this) {
            e->scale(center, factor);
            adjustBorders(e);
        }
        calculateBordersIfNeeded();
    }
}

void RS_EntityContainer::mirror(const RS_Vector &axisPoint1, const RS_Vector &axisPoint2) {
    if (axisPoint1.distanceTo(axisPoint2) > RS_TOLERANCE) {
        resetBorders();
        for (RS_Entity *e: *this) {
            e->mirror(axisPoint1, axisPoint2);
            adjustBorders(e);
        }
    }
}

RS_Entity &RS_EntityContainer::shear(double k) {
    for (RS_Entity *e: *this) {
        e->shear(k);
    }
    calculateBorders();
    return *this;
}

void RS_EntityContainer::stretch(const RS_Vector &firstCorner,const RS_Vector &secondCorner,const RS_Vector &offset) {
    if (getMin().isInWindow(firstCorner, secondCorner) && getMax().isInWindow(firstCorner, secondCorner)) {
        move(offset);
    } else {
        for (RS_Entity *e: *this) {
            e->stretch(firstCorner, secondCorner, offset);
        }
    }
    // some entitiycontainers might need an update (e.g. RS_Leader):
    update();
}

void RS_EntityContainer::calculateBordersIfNeeded() {
    if (m_autoUpdateBorders) {
        calculateBorders();
    }
}

void RS_EntityContainer::moveRef(const RS_Vector &ref,const RS_Vector &offset) {
    resetBorders();
    for (RS_Entity *e: *this) {
        e->moveRef(ref, offset);
        adjustBorders(e);
    }
    calculateBordersIfNeeded();
}

void RS_EntityContainer::moveSelectedRef(const RS_Vector &ref,const RS_Vector &offset) {
    resetBorders();
    for (RS_Entity *e: *this) {
        e->moveSelectedRef(ref, offset);
        adjustBorders(e);
    }
    calculateBordersIfNeeded();
}

void RS_EntityContainer::revertDirection() {
    // revert entity order in the container
    for (int k = 0; k < m_entities.size() / 2; ++k) {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))
        m_entities.swapItemsAt(k, m_entities.size() - 1 - k);
#else
        entities.swap(k, entities.size() - 1 - k);
#endif
    }

    // revert each entity itself
    for (RS_Entity *entity: std::as_const(m_entities)) {
        entity->revertDirection();
    }
}

/**
 * @brief draw m_entities in order
 * @param painter
 * @param view
 */
 void RS_EntityContainer::draw(RS_Painter *painter) {
    for(RS_Entity *e: *this){
        if (e!=nullptr && e->getId() != 0) {
            painter->drawEntity(e);
        }
    }
}

void RS_EntityContainer::drawAsChild(RS_Painter *painter) {
    for(RS_Entity *e: *this){
        if (e!=nullptr && e->getId() != 0) {
            painter->drawAsChild(e);
        }
    }
}

/**
 * @brief areaLineIntegral, line integral for contour area calculation by Green's Theorem
 * Contour Area =\oint x dy
 * @return line integral \oint x dy along the entity
 */
double RS_EntityContainer::areaLineIntegral() const {
    //TODO make sure all contour integral is by counter-clockwise
    double contourArea = 0.;
    //closed area is always positive
    double closedArea = 0.;
    double subArea = 0.;

    // edges:
    RS_Vector previousPoint(false);
    for (unsigned i = 0; i < count(); ++i) {
        RS_Entity *e = m_entities.at(i);
        if (isClosedLoop(*e)) {
            if (e->isContainer()) {
                subArea += e->areaLineIntegral();
            }
            else {
                closedArea += e->areaLineIntegral();
            }
            continue;
        }
        e->setLayer(getLayer());
        double lineIntegral = e->areaLineIntegral();
        RS_Vector startPoint = e->getStartpoint();
        RS_Vector endPoint = e->getEndpoint();
//        LC_ERR << e->getId() << ": int = " << lineIntegral << ": " << startPoint.x << " - " << endPoint.x;

        // the line integral is always by the direction: from the start point to the end point
        if (previousPoint.valid) {
            double distance = endPointDistance(previousPoint, *e);
            if (distance > contourTolerance)
                RS_DEBUG->print(RS_Debug::D_ERROR,
                                "%s(): contour area calculation maybe incorrect: gap of %lg found at (%lg, %lg)",
                                __func__, distance, previousPoint.x, previousPoint.y);
        }
        // assume the contour is a simple connected loop
        if (previousPoint.valid && endPoint.squaredTo(previousPoint) <= RS_TOLERANCE15) {
            contourArea -= lineIntegral;
            previousPoint = startPoint;
        } else {
            bool useEndPoint = true;
            if (!previousPoint.valid && i + 1 < count()) {
                auto currEntity = m_entities.at(i + 1);
                useEndPoint = endPointDistance(endPoint, *currEntity) < endPointDistance(startPoint, *currEntity);
            }
            contourArea += useEndPoint ? lineIntegral : -lineIntegral;
            previousPoint = useEndPoint ? endPoint : startPoint;
        }
    }
    return std::abs(contourArea) + closedArea - subArea;
}

bool RS_EntityContainer::ignoredOnModification() const {
    RS2::EntityType ownType = rtti();
    if (RS2::isDimensionalEntity(ownType) || RS2::isTextEntity(ownType) || ownType == RS2::EntityHatch){
        return true;
    }
    else {
        return isParentIgnoredOnModifications();
    }
}

bool RS_EntityContainer::ignoredSnap() const{
    // issue #652 , disable snap for hatch
    // TODO, should snapping on hatch be a feature enabled by settings?
    if (getParent() && getParent()->rtti() == RS2::EntityHatch) {
        return true;
    }
    return ignoredOnModification();
}

QList<RS_Entity *>::const_iterator RS_EntityContainer::begin() const{
    return m_entities.begin();
}

QList<RS_Entity *>::const_iterator RS_EntityContainer::end() const{
    return m_entities.end();
}

QList<RS_Entity *>::const_iterator RS_EntityContainer::cbegin() const{
    return m_entities.cbegin();
}

QList<RS_Entity *>::const_iterator RS_EntityContainer::cend() const{
    return m_entities.cend();
}

QList<RS_Entity *>::iterator RS_EntityContainer::begin(){
    return m_entities.begin();
}

QList<RS_Entity *>::iterator RS_EntityContainer::end() {
    return m_entities.end();
}

/**
 * Dumps the entities to stdout.
 */
std::ostream &operator<<(std::ostream &os, RS_EntityContainer &ec) {
    static int indent = 0;
    std::string tab(indent * 2, ' ');
    ++indent;
    unsigned long int id = ec.getId();
    os << tab << "EntityContainer[" << id << "]: \n";
    os << tab << "Borders[" << id << "]: "
       << ec.minV << " - " << ec.maxV << "\n";
    //os << tab << "Unit[" << id << "]: "
    //<< RS_Units::unit2string (ec.unit) << "\n";
    if (ec.getLayer()) {
        os << tab << "Layer[" << id << "]: "
           << ec.getLayer()->getName().toLatin1().data() << "\n";
    } else {
        os << tab << "Layer[" << id << "]: <nullptr>\n";
    }
    //os << ec.layerList << "\n";

    os << tab << " Flags[" << id << "]: "
       << (ec.getFlag(RS2::FlagVisible) ? "RS2::FlagVisible" : "");
    os << (ec.getFlag(RS2::FlagUndone) ? " RS2::FlagUndone" : "");
    os << (ec.getFlag(RS2::FlagSelected) ? " RS2::FlagSelected" : "");
    os << "\n";

    os << tab << "Entities[" << id << "]: \n";
    for(auto t: ec){
        switch (t->rtti()) {
            case RS2::EntityInsert:
                os << tab << *static_cast<RS_Insert*>(t);
                os << tab << *t;
                os << tab << *static_cast<RS_EntityContainer*>(t);
                break;
            default:
                if (t->isContainer()) {
                    os << tab << *static_cast<RS_EntityContainer*>(t);
                }
                else {
                    os << tab << *t;
                }
                break;
        }
    }
    os << tab << "\n\n";
    --indent;
    return os;
}

RS_Entity *RS_EntityContainer::first() const {
    return m_entities.first();
}

RS_Entity *RS_EntityContainer::last() const {
    return m_entities.last();
}

const QList<RS_Entity *> &RS_EntityContainer::getEntityList() {
    return m_entities;
}

std::vector<std::unique_ptr<RS_EntityContainer>> RS_EntityContainer::getLoops() const {
    if (m_entities.empty()) {
        return {};
    }
    std::vector<std::unique_ptr<RS_EntityContainer>> loops;
    RS_EntityContainer edges(nullptr, false);
    for(RS_Entity* en: *this){
        if (en != nullptr && en->isContainer()){
            if (en->isContainer()){
                auto subLoops = static_cast<RS_EntityContainer*>(en)->getLoops();
                for (auto& subLoop: subLoops) {
                    loops.push_back(std::move(subLoop));
                }
            }
            continue;
        }

        if (en == nullptr || !en->isEdge()) {
            continue;
        }

        //detect circles and whole ellipses
        switch (en->rtti()) {
            case RS2::EntityEllipse:
                if (static_cast<RS_Ellipse*>(en)->isEllipticArc()) {
                    edges.addEntity(en);
                    break;
                }
                [[fallthrough]];
            case RS2::EntityCircle: {
                auto ec = std::make_unique<RS_EntityContainer>(nullptr, false);
                ec->addEntity(en);
                loops.push_back(std::move(ec));
                break;
            }
            default:
                edges.addEntity(en);
        }
    }
    //find loops
    while (!edges.isEmpty()){
        LC_LoopUtils::LoopExtractor extractor{edges};
        auto subLoops = extractor.extract();
        for (auto& loop: subLoops) {
            loops.push_back(std::move(loop));
        }
    }
    return loops;
}