summaryrefslogtreecommitdiffstats
path: root/src/quick/items/qquickpositioners.cpp
blob: 38e89e78eb3614e96816965c8220f1b4d61f95b1 (plain)
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
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qquickpositioners_p.h"
#include "qquickpositioners_p_p.h"

#include <QtQml/qqml.h>
#include <QtQml/qqmlinfo.h>
#include <QtCore/qcoreapplication.h>

#include <QtQuick/private/qquickstate_p.h>
#include <QtQuick/private/qquickstategroup_p.h>
#include <private/qquickstatechangescript_p.h>
#include <QtQuick/private/qquicktransition_p.h>

QT_BEGIN_NAMESPACE

static const QQuickItemPrivate::ChangeTypes watchedChanges
    = QQuickItemPrivate::Geometry
    | QQuickItemPrivate::SiblingOrder
    | QQuickItemPrivate::Visibility
    | QQuickItemPrivate::Destroyed;

void QQuickBasePositionerPrivate::watchChanges(QQuickItem *other)
{
    QQuickItemPrivate *otherPrivate = QQuickItemPrivate::get(other);
    otherPrivate->addItemChangeListener(this, watchedChanges);
}

void QQuickBasePositionerPrivate::unwatchChanges(QQuickItem* other)
{
    QQuickItemPrivate *otherPrivate = QQuickItemPrivate::get(other);
    otherPrivate->removeItemChangeListener(this, watchedChanges);
}


QQuickBasePositioner::PositionedItem::PositionedItem(QQuickItem *i)
    : item(i)
    , transitionableItem(0)
    , index(-1)
    , isNew(false)
    , isVisible(true)
    , topPadding(0)
    , leftPadding(0)
    , rightPadding(0)
    , bottomPadding(0)
{
}

QQuickBasePositioner::PositionedItem::~PositionedItem()
{
    delete transitionableItem;
}

qreal QQuickBasePositioner::PositionedItem::itemX() const
{
    return transitionableItem ? transitionableItem->itemX() : item->x();
}

qreal QQuickBasePositioner::PositionedItem::itemY() const
{
    return transitionableItem ? transitionableItem->itemY() : item->y();
}

void QQuickBasePositioner::PositionedItem::moveTo(const QPointF &pos)
{
    if (transitionableItem)
        transitionableItem->moveTo(pos);
    else
        item->setPosition(pos);
}

void QQuickBasePositioner::PositionedItem::transitionNextReposition(QQuickItemViewTransitioner *transitioner, QQuickItemViewTransitioner::TransitionType type, bool asTarget)
{
    if (!transitioner)
        return;
    if (!transitionableItem)
        transitionableItem = new QQuickItemViewTransitionableItem(item);
    transitioner->transitionNextReposition(transitionableItem, type, asTarget);
}

bool QQuickBasePositioner::PositionedItem::prepareTransition(QQuickItemViewTransitioner *transitioner, const QRectF &viewBounds)
{
    return transitionableItem ? transitionableItem->prepareTransition(transitioner, index, viewBounds) : false;
}

void QQuickBasePositioner::PositionedItem::startTransition(QQuickItemViewTransitioner *transitioner)
{
    if (transitionableItem)
        transitionableItem->startTransition(transitioner, index);
}

void QQuickBasePositioner::PositionedItem::updatePadding(qreal lp, qreal tp, qreal rp, qreal bp)
{
    leftPadding = lp;
    topPadding = tp;
    rightPadding = rp;
    bottomPadding = bp;
}

QQuickBasePositioner::QQuickBasePositioner(PositionerType at, QQuickItem *parent)
    : QQuickImplicitSizeItem(*(new QQuickBasePositionerPrivate), parent)
{
    Q_D(QQuickBasePositioner);
    d->init(at);
}
/*!
    \internal
    \class QQuickBasePositioner
    \brief For specifying a base for QQuickGraphics layouts

    To create a QQuickGraphics Positioner, simply subclass QQuickBasePositioner and implement
    doLayout(), which is automatically called when the layout might need
    updating. In doLayout() use the setX and setY functions from QQuickBasePositioner, and the
    base class will apply the positions along with the appropriate transitions. The items to
    position are provided in order as the protected member positionedItems.

    You also need to set a PositionerType, to declare whether you are positioning the x, y or both
    for the child items. Depending on the chosen type, only x or y changes will be applied.

    Note that the subclass is responsible for adding the spacing in between items.

    Positioning is batched and synchronized with painting to reduce the number of
    calculations needed. This means that positioners may not reposition items immediately
    when changes occur, but it will have moved by the next frame.
*/

QQuickBasePositioner::QQuickBasePositioner(QQuickBasePositionerPrivate &dd, PositionerType at, QQuickItem *parent)
    : QQuickImplicitSizeItem(dd, parent)
{
    Q_D(QQuickBasePositioner);
    d->init(at);
}

QQuickBasePositioner::~QQuickBasePositioner()
{
    Q_D(QQuickBasePositioner);
    delete d->transitioner;
    for (int i = 0; i < positionedItems.count(); ++i)
        d->unwatchChanges(positionedItems.at(i).item);
    for (int i = 0; i < unpositionedItems.count(); ++i)
        d->unwatchChanges(unpositionedItems.at(i).item);
    clearPositionedItems(&positionedItems);
    clearPositionedItems(&unpositionedItems);
}

void QQuickBasePositioner::updatePolish()
{
    Q_D(QQuickBasePositioner);
    if (d->positioningDirty)
        prePositioning();
}

qreal QQuickBasePositioner::spacing() const
{
    Q_D(const QQuickBasePositioner);
    return d->spacing;
}

void QQuickBasePositioner::setSpacing(qreal s)
{
    Q_D(QQuickBasePositioner);
    if (s == d->spacing)
        return;
    d->spacing = s;
    d->setPositioningDirty();
    emit spacingChanged();
}

QQuickTransition *QQuickBasePositioner::populate() const
{
    Q_D(const QQuickBasePositioner);
    return d->transitioner ? d->transitioner->populateTransition : 0;
}

void QQuickBasePositioner::setPopulate(QQuickTransition *transition)
{
    Q_D(QQuickBasePositioner);
    if (!d->transitioner)
        d->transitioner = new QQuickItemViewTransitioner;
    if (d->transitioner->populateTransition != transition) {
        d->transitioner->populateTransition = transition;
        emit populateChanged();
    }
}

QQuickTransition *QQuickBasePositioner::move() const
{
    Q_D(const QQuickBasePositioner);
    return d->transitioner ? d->transitioner->displacedTransition : 0;
}

void QQuickBasePositioner::setMove(QQuickTransition *mt)
{
    Q_D(QQuickBasePositioner);
    if (!d->transitioner)
        d->transitioner = new QQuickItemViewTransitioner;
    if (mt == d->transitioner->displacedTransition)
        return;

    d->transitioner->displacedTransition = mt;
    emit moveChanged();
}

QQuickTransition *QQuickBasePositioner::add() const
{
    Q_D(const QQuickBasePositioner);
    return d->transitioner ? d->transitioner->addTransition : 0;
}

void QQuickBasePositioner::setAdd(QQuickTransition *add)
{
    Q_D(QQuickBasePositioner);
    if (!d->transitioner)
        d->transitioner = new QQuickItemViewTransitioner;
    if (add == d->transitioner->addTransition)
        return;

    d->transitioner->addTransition = add;
    emit addChanged();
}

void QQuickBasePositioner::componentComplete()
{
    Q_D(QQuickBasePositioner);
    QQuickItem::componentComplete();
    if (d->transitioner)
        d->transitioner->setPopulateTransitionEnabled(true);
    positionedItems.reserve(childItems().count());
    prePositioning();
    if (d->transitioner)
        d->transitioner->setPopulateTransitionEnabled(false);
}

void QQuickBasePositioner::itemChange(ItemChange change, const ItemChangeData &value)
{
    Q_D(QQuickBasePositioner);
    if (change == ItemChildAddedChange) {
        d->setPositioningDirty();
    } else if (change == ItemChildRemovedChange) {
        QQuickItem *child = value.item;
        QQuickBasePositioner::PositionedItem posItem(child);
        int idx = positionedItems.find(posItem);
        if (idx >= 0) {
            d->unwatchChanges(child);
            removePositionedItem(&positionedItems, idx);
        } else if ((idx = unpositionedItems.find(posItem)) >= 0) {
            d->unwatchChanges(child);
            removePositionedItem(&unpositionedItems, idx);
        }
        d->setPositioningDirty();
    }

    QQuickItem::itemChange(change, value);
}

void QQuickBasePositioner::prePositioning()
{
    Q_D(QQuickBasePositioner);
    if (!isComponentComplete())
        return;

    if (d->doingPositioning)
        return;

    d->positioningDirty = false;
    d->doingPositioning = true;
    //Need to order children by creation order modified by stacking order
    QList<QQuickItem *> children = childItems();

    QPODVector<PositionedItem,8> oldItems;
    positionedItems.copyAndClear(oldItems);
    for (int ii = 0; ii < unpositionedItems.count(); ii++)
        oldItems.append(unpositionedItems[ii]);
    unpositionedItems.clear();
    int addedIndex = -1;

    for (int ii = 0; ii < children.count(); ++ii) {
        QQuickItem *child = children.at(ii);
        if (QQuickItemPrivate::get(child)->isTransparentForPositioner())
            continue;
        QQuickItemPrivate *childPrivate = QQuickItemPrivate::get(child);
        PositionedItem posItem(child);
        int wIdx = oldItems.find(posItem);
        if (wIdx < 0) {
            d->watchChanges(child);
            posItem.isNew = true;
            if (!childPrivate->explicitVisible || !child->width() || !child->height()) {
                posItem.isVisible = false;
                posItem.index = -1;
                unpositionedItems.append(posItem);
            } else {
                posItem.index = positionedItems.count();
                positionedItems.append(posItem);

                if (d->transitioner) {
                    if (addedIndex < 0)
                        addedIndex = posItem.index;
                    PositionedItem *theItem = &positionedItems[positionedItems.count()-1];
                    if (d->transitioner->canTransition(QQuickItemViewTransitioner::PopulateTransition, true))
                        theItem->transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::PopulateTransition, true);
                    else if (!d->transitioner->populateTransitionEnabled())
                        theItem->transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::AddTransition, true);
                }
            }
        } else {
            PositionedItem *item = &oldItems[wIdx];
            // Items are only omitted from positioning if they are explicitly hidden
            // i.e. their positioning is not affected if an ancestor is hidden.
            if (!childPrivate->explicitVisible || !child->width() || !child->height()) {
                item->isVisible = false;
                item->index = -1;
                unpositionedItems.append(*item);
            } else if (!item->isVisible) {
                // item changed from non-visible to visible, treat it as a "new" item
                item->isVisible = true;
                item->isNew = true;
                item->index = positionedItems.count();
                positionedItems.append(*item);

                if (d->transitioner) {
                    if (addedIndex < 0)
                        addedIndex = item->index;
                    positionedItems[positionedItems.count()-1].transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::AddTransition, true);
                }
            } else {
                item->isNew = false;
                item->index = positionedItems.count();
                positionedItems.append(*item);
            }
        }
    }

    if (d->transitioner) {
        for (int i=0; i<positionedItems.count(); i++) {
            if (!positionedItems[i].isNew) {
                if (addedIndex >= 0) {
                    positionedItems[i].transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::AddTransition, false);
                } else {
                    // just queue the item for a move-type displace - if the item hasn't
                    // moved anywhere, it won't be transitioned anyway
                    positionedItems[i].transitionNextReposition(d->transitioner, QQuickItemViewTransitioner::MoveTransition, false);
                }
            }
        }
    }

    QSizeF contentSize(0,0);
    reportConflictingAnchors();
    if (!d->anchorConflict) {
        doPositioning(&contentSize);
        updateAttachedProperties();
    }

    if (d->transitioner) {
        QRectF viewBounds(QPointF(), contentSize);
        for (int i=0; i<positionedItems.count(); i++)
            positionedItems[i].prepareTransition(d->transitioner, viewBounds);
        for (int i=0; i<positionedItems.count(); i++)
            positionedItems[i].startTransition(d->transitioner);
        d->transitioner->resetTargetLists();
    }

    d->doingPositioning = false;

    //Set implicit size to the size of its children
    setImplicitSize(contentSize.width(), contentSize.height());
}

void QQuickBasePositioner::positionItem(qreal x, qreal y, PositionedItem *target)
{
    if ( target->itemX() != x || target->itemY() != y )
        target->moveTo(QPointF(x, y));
}

void QQuickBasePositioner::positionItemX(qreal x, PositionedItem *target)
{
    Q_D(QQuickBasePositioner);
    if (target->itemX() != x
            && (d->type == Horizontal || d->type == Both)) {
        target->moveTo(QPointF(x, target->itemY()));
    }
}

void QQuickBasePositioner::positionItemY(qreal y, PositionedItem *target)
{
    Q_D(QQuickBasePositioner);
    if (target->itemY() != y
            && (d->type == Vertical || d->type == Both)) {
        target->moveTo(QPointF(target->itemX(), y));
    }
}

/*
  Since PositionedItem values are stored by value, their internal transitionableItem pointers
  must be cleaned up when a PositionedItem is removed from a QPODVector, otherwise the pointer
  is never deleted since QPODVector doesn't invoke the destructor.
  */
void QQuickBasePositioner::removePositionedItem(QPODVector<PositionedItem,8> *items, int index)
{
    Q_ASSERT(index >= 0 && index < items->count());
    delete items->at(index).transitionableItem;
    items->remove(index);
}
void QQuickBasePositioner::clearPositionedItems(QPODVector<PositionedItem,8> *items)
{
    for (int i=0; i<items->count(); i++)
        delete items->at(i).transitionableItem;
    items->clear();
}

QQuickPositionerAttached *QQuickBasePositioner::qmlAttachedProperties(QObject *obj)
{
    return new QQuickPositionerAttached(obj);
}

void QQuickBasePositioner::updateAttachedProperties(QQuickPositionerAttached *specificProperty, QQuickItem *specificPropertyOwner) const
{
    // If this function is deemed too expensive or shows up in profiles, it could
    // be changed to run only when there are attached properties present. This
    // could be a flag in the positioner that is set by the attached property
    // constructor.
    QQuickPositionerAttached *prevLastProperty = 0;
    QQuickPositionerAttached *lastProperty = 0;

    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        const PositionedItem &child = positionedItems.at(ii);
        if (!child.item)
            continue;

        QQuickPositionerAttached *property = 0;

        if (specificProperty) {
            if (specificPropertyOwner == child.item) {
                property = specificProperty;
            }
        } else {
            property = static_cast<QQuickPositionerAttached *>(qmlAttachedPropertiesObject<QQuickBasePositioner>(child.item, false));
        }

        if (property) {
            property->setIndex(ii);
            property->setIsFirstItem(ii == 0);

            if (property->isLastItem()) {
                if (prevLastProperty)
                    prevLastProperty->setIsLastItem(false); // there can be only one last property
                prevLastProperty = property;
            }
        }

        lastProperty = property;
    }

    if (prevLastProperty && prevLastProperty != lastProperty)
        prevLastProperty->setIsLastItem(false);
    if (lastProperty)
        lastProperty->setIsLastItem(true);

    // clear attached properties for unpositioned items
    for (int ii = 0; ii < unpositionedItems.count(); ++ii) {
        const PositionedItem &child = unpositionedItems.at(ii);
        if (!child.item)
            continue;

        QQuickPositionerAttached *property = 0;

        if (specificProperty) {
            if (specificPropertyOwner == child.item) {
                property = specificProperty;
            }
        } else {
            property = static_cast<QQuickPositionerAttached *>(qmlAttachedPropertiesObject<QQuickBasePositioner>(child.item, false));
        }

        if (property) {
            property->setIndex(-1);
            property->setIsFirstItem(false);
            property->setIsLastItem(false);
        }
    }
}

qreal QQuickBasePositioner::padding() const
{
    Q_D(const QQuickBasePositioner);
    return d->padding();
}

void QQuickBasePositioner::setPadding(qreal padding)
{
    Q_D(QQuickBasePositioner);
    if (qFuzzyCompare(d->padding(), padding))
        return;

    d->extra.value().padding = padding;
    d->setPositioningDirty();
    emit paddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitTopPadding)
        emit topPaddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitLeftPadding)
        emit leftPaddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitRightPadding)
        emit rightPaddingChanged();
    if (!d->extra.isAllocated() || !d->extra->explicitBottomPadding)
        emit bottomPaddingChanged();
}

void QQuickBasePositioner::resetPadding()
{
    setPadding(0);
}

qreal QQuickBasePositioner::topPadding() const
{
    Q_D(const QQuickBasePositioner);
    if (d->extra.isAllocated() && d->extra->explicitTopPadding)
        return d->extra->topPadding;
    return d->padding();
}

void QQuickBasePositioner::setTopPadding(qreal padding)
{
    Q_D(QQuickBasePositioner);
    d->setTopPadding(padding);
}

void QQuickBasePositioner::resetTopPadding()
{
    Q_D(QQuickBasePositioner);
    d->setTopPadding(0, true);
}

qreal QQuickBasePositioner::leftPadding() const
{
    Q_D(const QQuickBasePositioner);
    if (d->extra.isAllocated() && d->extra->explicitLeftPadding)
        return d->extra->leftPadding;
    return d->padding();
}

void QQuickBasePositioner::setLeftPadding(qreal padding)
{
    Q_D(QQuickBasePositioner);
    d->setLeftPadding(padding);
}

void QQuickBasePositioner::resetLeftPadding()
{
    Q_D(QQuickBasePositioner);
    d->setLeftPadding(0, true);
}

qreal QQuickBasePositioner::rightPadding() const
{
    Q_D(const QQuickBasePositioner);
    if (d->extra.isAllocated() && d->extra->explicitRightPadding)
        return d->extra->rightPadding;
    return d->padding();
}

void QQuickBasePositioner::setRightPadding(qreal padding)
{
    Q_D(QQuickBasePositioner);
    d->setRightPadding(padding);
}

void QQuickBasePositioner::resetRightPadding()
{
    Q_D(QQuickBasePositioner);
    d->setRightPadding(0, true);
}

qreal QQuickBasePositioner::bottomPadding() const
{
    Q_D(const QQuickBasePositioner);
    if (d->extra.isAllocated() && d->extra->explicitBottomPadding)
        return d->extra->bottomPadding;
    return d->padding();
}

void QQuickBasePositioner::setBottomPadding(qreal padding)
{
    Q_D(QQuickBasePositioner);
    d->setBottomPadding(padding);
}

void QQuickBasePositioner::resetBottomPadding()
{
    Q_D(QQuickBasePositioner);
    d->setBottomPadding(0, true);
}

QQuickBasePositionerPrivate::ExtraData::ExtraData()
    : padding(0)
    , topPadding(0)
    , leftPadding(0)
    , rightPadding(0)
    , bottomPadding(0)
    , explicitTopPadding(false)
    , explicitLeftPadding(false)
    , explicitRightPadding(false)
    , explicitBottomPadding(false)
{
}

void QQuickBasePositionerPrivate::setTopPadding(qreal value, bool reset)
{
    Q_Q(QQuickBasePositioner);
    qreal oldPadding = q->topPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().topPadding = value;
        extra.value().explicitTopPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        setPositioningDirty();
        emit q->topPaddingChanged();
    }
}

void QQuickBasePositionerPrivate::setLeftPadding(qreal value, bool reset)
{
    Q_Q(QQuickBasePositioner);
    qreal oldPadding = q->leftPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().leftPadding = value;
        extra.value().explicitLeftPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        setPositioningDirty();
        emit q->leftPaddingChanged();
    }
}

void QQuickBasePositionerPrivate::setRightPadding(qreal value, bool reset)
{
    Q_Q(QQuickBasePositioner);
    qreal oldPadding = q->rightPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().rightPadding = value;
        extra.value().explicitRightPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        setPositioningDirty();
        emit q->rightPaddingChanged();
    }
}

void QQuickBasePositionerPrivate::setBottomPadding(qreal value, bool reset)
{
    Q_Q(QQuickBasePositioner);
    qreal oldPadding = q->bottomPadding();
    if (!reset || extra.isAllocated()) {
        extra.value().bottomPadding = value;
        extra.value().explicitBottomPadding = !reset;
    }
    if ((!reset && !qFuzzyCompare(oldPadding, value)) || (reset && !qFuzzyCompare(oldPadding, padding()))) {
        setPositioningDirty();
        emit q->bottomPaddingChanged();
    }
}

/*!
    \qmltype Positioner
    \instantiates QQuickPositionerAttached
    \inqmlmodule QtQuick
    \ingroup qtquick-positioners
    \brief Provides attached properties that contain details on where an item exists in a positioner

    An object of type Positioner is attached to the top-level child item within a
    Column, Row, Flow or Grid. It provides properties that allow a child item to determine
    where it exists within the layout of its parent Column, Row, Flow or Grid.

    For example, below is a \l Grid with 16 child rectangles, as created through a \l Repeater.
    Each \l Rectangle displays its index in the Grid using \l {Positioner::index}{Positioner.index}, and the first
    item is colored differently by taking \l {Positioner::isFirstItem}{Positioner.isFirstItem} into account:

    \code
    Grid {
        Repeater {
            model: 16

            Rectangle {
                id: rect
                width: 30; height: 30
                border.width: 1
                color: Positioner.isFirstItem ? "yellow" : "lightsteelblue"

                Text { text: rect.Positioner.index }
            }
        }
    }
    \endcode

    \image positioner-example.png
*/

QQuickPositionerAttached::QQuickPositionerAttached(QObject *parent) : QObject(parent), m_index(-1), m_isFirstItem(false), m_isLastItem(false)
{
    QQuickItem *attachedItem = qobject_cast<QQuickItem *>(parent);
    if (attachedItem) {
        QQuickBasePositioner *positioner = qobject_cast<QQuickBasePositioner *>(attachedItem->parent());
        if (positioner) {
            positioner->updateAttachedProperties(this, attachedItem);
        }
    }
}

/*!
    \qmlattachedproperty int QtQuick::Positioner::index

    This property allows the item to determine
    its index within the positioner.
*/
void QQuickPositionerAttached::setIndex(int index)
{
    if (m_index == index)
        return;
    m_index = index;
    emit indexChanged();
}

/*!
    \qmlattachedproperty bool QtQuick::Positioner::isFirstItem
    \qmlattachedproperty bool QtQuick::Positioner::isLastItem

    These properties allow the item to determine if it
    is the first or last item in the positioner, respectively.
*/
void QQuickPositionerAttached::setIsFirstItem(bool isFirstItem)
{
    if (m_isFirstItem == isFirstItem)
        return;
    m_isFirstItem = isFirstItem;
    emit isFirstItemChanged();
}

void QQuickPositionerAttached::setIsLastItem(bool isLastItem)
{
    if (m_isLastItem == isLastItem)
        return;
    m_isLastItem = isLastItem;
    emit isLastItemChanged();
}

/*!
    \qmltype Column
    \instantiates QQuickColumn
    \inqmlmodule QtQuick
    \inherits Item
    \ingroup qtquick-positioners
    \brief Positions its children in a column

    Column is a type that positions its child items along a single column.
    It can be used as a convenient way to vertically position a series of items without
    using \l {Positioning with Anchors}{anchors}.

    Below is a Column that contains three rectangles of various sizes:

    \snippet qml/column/vertical-positioner.qml document

    The Column automatically positions these items in a vertical formation, like this:

    \image verticalpositioner_example.png

    If an item within a Column is not \l {Item::}{visible}, or if it has a width or
    height of 0, the item will not be laid out and it will not be visible within the
    column. Also, since a Column automatically positions its children vertically, a child
    item within a Column should not set its \l {Item::y}{y} position or vertically
    anchor itself using the \l {Item::anchors.top}{top}, \l {Item::anchors.bottom}{bottom},
    \l {Item::anchors.verticalCenter}{anchors.verticalCenter}, \l {Item::anchors.fill}{fill}
    or \l {Item::anchors.centerIn}{centerIn} anchors. If you need to perform these actions,
    consider positioning the items without the use of a Column.

    Note that items in a Column can use the \l Positioner attached property to access
    more information about its position within the Column.

    For more information on using Column and other related positioner-types, see
    \l{Item Positioners}.


    \section1 Using Transitions

    A Column animate items using specific transitions when items are added to or moved
    within a Column.

    For example, the Column below sets the \l move property to a specific \l Transition:

    \snippet qml/column/column-transitions.qml document

    When the Space key is pressed, the \l {Item::visible}{visible} value of the green
    \l Rectangle is toggled. As it appears and disappears, the blue \l Rectangle moves within
    the Column, and the \l move transition is automatically applied to the blue \l Rectangle:

    \image verticalpositioner_transition.gif

    \sa Row, Grid, Flow, Positioner, ColumnLayout, {Qt Quick Examples - Positioners}
*/
/*!
    \since 5.6
    \qmlproperty real QtQuick::Column::padding
    \qmlproperty real QtQuick::Column::topPadding
    \qmlproperty real QtQuick::Column::leftPadding
    \qmlproperty real QtQuick::Column::bottomPadding
    \qmlproperty real QtQuick::Column::rightPadding

    These properties hold the padding around the content.
*/
/*!
    \qmlproperty Transition QtQuick::Column::populate

    This property holds the transition to be run for items that are part of
    this positioner at the time of its creation. The transition is run when the positioner
    is first created.

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Column::add

    This property holds the transition to be run for items that are added to this
    positioner. For a positioner, this applies to:

    \list
    \li Items that are created or reparented as a child of the positioner after the
        positioner has been created
    \li Child items that change their \l Item::visible property from false to true, and thus
       are now visible
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note This transition is not applied to the items that already part of the positioner
    at the time of its creation. In this case, the \l populate transition is applied instead.

    \sa populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Column::move

    This property holds the transition to run for items that have moved within the
    positioner. For a positioner, this applies to:

    \list
    \li Child items that move when they are displaced due to the addition, removal or
       rearrangement of other items in the positioner
    \li Child items that are repositioned due to the resizing of other items in the positioner
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being moved. Note, however, that for this move transition, the
    ViewTransition.targetIndexes and ViewTransition.targetItems lists are only set when
    this transition is triggered by the addition of other items in the positioner; in other
    cases, these lists will be empty.  See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
    positioner at the time of its creation. From \l {Qt Quick}{Qt Quick 2} onwards, positioners apply the
    \l populate transition to these items instead.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
  \qmlproperty real QtQuick::Column::spacing

  The spacing is the amount in pixels left empty between adjacent
  items. The default spacing is 0.

  \sa Grid::spacing
*/
QQuickColumn::QQuickColumn(QQuickItem *parent)
: QQuickBasePositioner(Vertical, parent)
{
}

void QQuickColumn::doPositioning(QSizeF *contentSize)
{
    //Precondition: All items in the positioned list have a valid item pointer and should be positioned
    qreal voffset = topPadding();
    const qreal padding = leftPadding() + rightPadding();
    contentSize->setWidth(qMax(contentSize->width(), padding));

    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        PositionedItem &child = positionedItems[ii];
        positionItem(child.itemX() + leftPadding() - child.leftPadding, voffset, &child);
        child.updatePadding(leftPadding(), topPadding(), rightPadding(), bottomPadding());
        contentSize->setWidth(qMax(contentSize->width(), child.item->width() + padding));

        voffset += child.item->height();
        voffset += spacing();
    }

    if (voffset - topPadding() != 0)//If we positioned any items, undo the spacing from the last item
        voffset -= spacing();
    contentSize->setHeight(voffset + bottomPadding());
}

void QQuickColumn::reportConflictingAnchors()
{
    QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        const PositionedItem &child = positionedItems.at(ii);
        if (child.item) {
            QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
            if (anchors) {
                QQuickAnchors::Anchors usedAnchors = anchors->usedAnchors();
                if (usedAnchors & QQuickAnchors::TopAnchor ||
                    usedAnchors & QQuickAnchors::BottomAnchor ||
                    usedAnchors & QQuickAnchors::VCenterAnchor ||
                    anchors->fill() || anchors->centerIn()) {
                    d->anchorConflict = true;
                    break;
                }
            }
        }
    }
    if (d->anchorConflict) {
        qmlInfo(this) << "Cannot specify top, bottom, verticalCenter, fill or centerIn anchors for items inside Column."
            << " Column will not function.";
    }
}
/*!
    \qmltype Row
    \instantiates QQuickRow
    \inqmlmodule QtQuick
    \inherits Item
    \ingroup qtquick-positioners
    \brief Positions its children in a row

    Row is a type that positions its child items along a single row.
    It can be used as a convenient way to horizontally position a series of items without
    using \l {Positioning with Anchors}{anchors}.

    Below is a Row that contains three rectangles of various sizes:

    \snippet qml/row/row.qml document

    The Row automatically positions these items in a horizontal formation, like this:

    \image horizontalpositioner_example.png

    If an item within a Row is not \l {Item::}{visible}, or if it has a width or
    height of 0, the item will not be laid out and it will not be visible within the
    row. Also, since a Row automatically positions its children horizontally, a child
    item within a Row should not set its \l {Item::x}{x} position or horizontally
    anchor itself using the \l {Item::anchors.left}{left}, \l {Item::anchors.right}{right},
    \l {Item::anchors.horizontalCenter}{anchors.horizontalCenter}, \l {Item::anchors.fill}{fill}
    or \l {Item::anchors.centerIn}{centerIn} anchors. If you need to perform these actions,
    consider positioning the items without the use of a Row.

    Note that items in a Row can use the \l Positioner attached property to access
    more information about its position within the Row.

    For more information on using Row and other related positioner-types, see
    \l{Item Positioners}.


    \sa Column, Grid, Flow, Positioner, RowLayout, {Qt Quick Examples - Positioners}
*/
/*!
    \since 5.6
    \qmlproperty real QtQuick::Row::padding
    \qmlproperty real QtQuick::Row::topPadding
    \qmlproperty real QtQuick::Row::leftPadding
    \qmlproperty real QtQuick::Row::bottomPadding
    \qmlproperty real QtQuick::Row::rightPadding

    These properties hold the padding around the content.
*/
/*!
    \qmlproperty Transition QtQuick::Row::populate

    This property holds the transition to be run for items that are part of
    this positioner at the time of its creation. The transition is run when the positioner
    is first created.

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Row::add

    This property holds the transition to be run for items that are added to this
    positioner. For a positioner, this applies to:

    \list
    \li Items that are created or reparented as a child of the positioner after the
        positioner has been created
    \li Child items that change their \l Item::visible property from false to true, and thus
       are now visible
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note This transition is not applied to the items that already part of the positioner
    at the time of its creation. In this case, the \l populate transition is applied instead.

    \sa populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Row::move

    This property holds the transition to run for items that have moved within the
    positioner. For a positioner, this applies to:

    \list
    \li Child items that move when they are displaced due to the addition, removal or
       rearrangement of other items in the positioner
    \li Child items that are repositioned due to the resizing of other items in the positioner
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being moved. Note, however, that for this move transition, the
    ViewTransition.targetIndexes and ViewTransition.targetItems lists are only set when
    this transition is triggered by the addition of other items in the positioner; in other
    cases, these lists will be empty.  See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
    positioner at the time of its creation. From \l {Qt Quick}{QtQuick 2} onwards, positioners apply the
    \l populate transition to these items instead.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
  \qmlproperty real QtQuick::Row::spacing

  The spacing is the amount in pixels left empty between adjacent
  items. The default spacing is 0.

  \sa Grid::spacing
*/

class QQuickRowPrivate : public QQuickBasePositionerPrivate
{
    Q_DECLARE_PUBLIC(QQuickRow)

public:
    QQuickRowPrivate()
        : QQuickBasePositionerPrivate()
    {}

    void effectiveLayoutDirectionChange()
    {
        Q_Q(QQuickRow);
        // For RTL layout the positioning changes when the width changes.
        if (getEffectiveLayoutDirection(q) == Qt::RightToLeft)
            addItemChangeListener(this, QQuickItemPrivate::Geometry);
        else
            removeItemChangeListener(this, QQuickItemPrivate::Geometry);
        // Don't postpone, as it might be the only trigger for visible changes.
        q->prePositioning();
        emit q->effectiveLayoutDirectionChanged();
    }
};

QQuickRow::QQuickRow(QQuickItem *parent)
: QQuickBasePositioner(*new QQuickRowPrivate, Horizontal, parent)
{
}
/*!
    \qmlproperty enumeration QtQuick::Row::layoutDirection

    This property holds the layoutDirection of the row.

    Possible values:

    \list
    \li Qt.LeftToRight (default) - Items are laid out from left to right. If the width of the row is explicitly set,
    the left anchor remains to the left of the row.
    \li Qt.RightToLeft - Items are laid out from right to left. If the width of the row is explicitly set,
    the right anchor remains to the right of the row.
    \endlist

    \sa Grid::layoutDirection, Flow::layoutDirection, {Qt Quick Examples - Right to Left}
*/

Qt::LayoutDirection QQuickRow::layoutDirection() const
{
    return QQuickBasePositionerPrivate::getLayoutDirection(this);
}

void QQuickRow::setLayoutDirection(Qt::LayoutDirection layoutDirection)
{
    QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate* >(QQuickBasePositionerPrivate::get(this));
    if (d->layoutDirection != layoutDirection) {
        d->layoutDirection = layoutDirection;
        emit layoutDirectionChanged();
        d->effectiveLayoutDirectionChange();
    }
}
/*!
    \qmlproperty enumeration QtQuick::Row::effectiveLayoutDirection
    This property holds the effective layout direction of the row.

    When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
    the visual layout direction of the row positioner will be mirrored. However, the
    property \l {Row::layoutDirection}{layoutDirection} will remain unchanged.

    \sa Row::layoutDirection, {LayoutMirroring}{LayoutMirroring}
*/

Qt::LayoutDirection QQuickRow::effectiveLayoutDirection() const
{
    return QQuickBasePositionerPrivate::getEffectiveLayoutDirection(this);
}

void QQuickRow::doPositioning(QSizeF *contentSize)
{
    //Precondition: All items in the positioned list have a valid item pointer and should be positioned
    QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate* >(QQuickBasePositionerPrivate::get(this));
    qreal hoffset1 = leftPadding();
    qreal hoffset2 = rightPadding();
    if (!d->isLeftToRight())
        qSwap(hoffset1, hoffset2);
    qreal hoffset = hoffset1;
    const qreal padding = topPadding() + bottomPadding();
    contentSize->setHeight(qMax(contentSize->height(), padding));

    QList<qreal> hoffsets;
    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        PositionedItem &child = positionedItems[ii];

        if (d->isLeftToRight()) {
            positionItem(hoffset, child.itemY() + topPadding() - child.topPadding, &child);
            child.updatePadding(leftPadding(), topPadding(), rightPadding(), bottomPadding());
        } else {
            hoffsets << hoffset;
        }

        contentSize->setHeight(qMax(contentSize->height(), child.item->height() + padding));

        hoffset += child.item->width();
        hoffset += spacing();
    }

    if (hoffset - hoffset1 != 0)//If we positioned any items, undo the extra spacing from the last item
        hoffset -= spacing();
    contentSize->setWidth(hoffset + hoffset2);

    if (d->isLeftToRight())
        return;

    //Right to Left layout
    qreal end = 0;
    if (!widthValid())
        end = contentSize->width();
    else
        end = width();

    int acc = 0;
    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        PositionedItem &child = positionedItems[ii];
        hoffset = end - hoffsets[acc++] - child.item->width();
        positionItem(hoffset, child.itemY() + topPadding() - child.topPadding, &child);
        child.updatePadding(leftPadding(), topPadding(), rightPadding(), bottomPadding());
    }
}

void QQuickRow::reportConflictingAnchors()
{
    QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        const PositionedItem &child = positionedItems.at(ii);
        if (child.item) {
            QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
            if (anchors) {
                QQuickAnchors::Anchors usedAnchors = anchors->usedAnchors();
                if (usedAnchors & QQuickAnchors::LeftAnchor ||
                    usedAnchors & QQuickAnchors::RightAnchor ||
                    usedAnchors & QQuickAnchors::HCenterAnchor ||
                    anchors->fill() || anchors->centerIn()) {
                    d->anchorConflict = true;
                    break;
                }
            }
        }
    }
    if (d->anchorConflict)
        qmlInfo(this) << "Cannot specify left, right, horizontalCenter, fill or centerIn anchors for items inside Row."
            << " Row will not function.";
}

/*!
    \qmltype Grid
    \instantiates QQuickGrid
    \inqmlmodule QtQuick
    \inherits Item
    \ingroup qtquick-positioners
    \brief Positions its children in grid formation

    Grid is a type that positions its child items in grid formation.

    A Grid creates a grid of cells that is large enough to hold all of its
    child items, and places these items in the cells from left to right
    and top to bottom. Each item is positioned at the top-left corner of its
    cell with position (0, 0).

    A Grid defaults to four columns, and creates as many rows as are necessary to
    fit all of its child items. The number of rows and columns can be constrained
    by setting the \l rows and \l columns properties.

    For example, below is a Grid that contains five rectangles of various sizes:

    \snippet qml/grid/grid.qml document

    The Grid automatically positions the child items in a grid formation:

    \image gridLayout_example.png

    If an item within a Grid is not \l {Item::}{visible}, or if it has a width or
    height of 0, the item will not be laid out and it will not be visible within the
    column. Also, since a Grid automatically positions its children, a child
    item within a Grid should not set its \l {Item::x}{x} or \l {Item::y}{y} positions
    or anchor itself with any of the \l {Item::anchors}{anchor} properties.

    For more information on using Grid and other related positioner-types, see
    \l{Item Positioners}.


    \sa Flow, Row, Column, Positioner, GridLayout, {Qt Quick Examples - Positioners}
*/
/*!
    \since 5.6
    \qmlproperty real QtQuick::Grid::padding
    \qmlproperty real QtQuick::Grid::topPadding
    \qmlproperty real QtQuick::Grid::leftPadding
    \qmlproperty real QtQuick::Grid::bottomPadding
    \qmlproperty real QtQuick::Grid::rightPadding

    These properties hold the padding around the content.
*/
/*!
    \qmlproperty Transition QtQuick::Grid::populate

    This property holds the transition to be run for items that are part of
    this positioner at the time of its creation. The transition is run when the positioner
    is first created.

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Grid::add

    This property holds the transition to be run for items that are added to this
    positioner. For a positioner, this applies to:

    \list
    \li Items that are created or reparented as a child of the positioner after the
        positioner has been created
    \li Child items that change their \l Item::visible property from false to true, and thus
       are now visible
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note This transition is not applied to the items that already part of the positioner
    at the time of its creation. In this case, the \l populate transition is applied instead.

    \sa populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Grid::move

    This property holds the transition to run for items that have moved within the
    positioner. For a positioner, this applies to:

    \list
    \li Child items that move when they are displaced due to the addition, removal or
       rearrangement of other items in the positioner
    \li Child items that are repositioned due to the resizing of other items in the positioner
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being moved. Note, however, that for this move transition, the
    ViewTransition.targetIndexes and ViewTransition.targetItems lists are only set when
    this transition is triggered by the addition of other items in the positioner; in other
    cases, these lists will be empty.  See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
    positioner at the time of its creation. From \l {Qt Quick}{QtQuick 2} onwards, positioners apply the
    \l populate transition to these items instead.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
  \qmlproperty qreal QtQuick::Grid::spacing

  The spacing is the amount in pixels left empty between adjacent
  items. The amount of spacing applied will be the same in the
  horizontal and vertical directions. The default spacing is 0.

  The below example places a Grid containing a red, a blue and a
  green rectangle on a gray background. The area the grid positioner
  occupies is colored white. The positioner on the left has the
  no spacing (the default), and the positioner on the right has
  a spacing of 6.

  \inlineimage qml-grid-no-spacing.png
  \inlineimage qml-grid-spacing.png

  \sa rows, columns
*/

class QQuickGridPrivate : public QQuickBasePositionerPrivate
{
    Q_DECLARE_PUBLIC(QQuickGrid)

public:
    QQuickGridPrivate()
        : QQuickBasePositionerPrivate()
    {}

    void effectiveLayoutDirectionChange()
    {
        Q_Q(QQuickGrid);
        // For RTL layout the positioning changes when the width changes.
        if (getEffectiveLayoutDirection(q) == Qt::RightToLeft)
            addItemChangeListener(this, QQuickItemPrivate::Geometry);
        else
            removeItemChangeListener(this, QQuickItemPrivate::Geometry);
        // Don't postpone, as it might be the only trigger for visible changes.
        q->prePositioning();
        emit q->effectiveLayoutDirectionChanged();
        emit q->effectiveHorizontalAlignmentChanged(q->effectiveHAlign());
    }
};

QQuickGrid::QQuickGrid(QQuickItem *parent)
    : QQuickBasePositioner(*new QQuickGridPrivate, Both, parent)
    , m_rows(-1)
    , m_columns(-1)
    , m_rowSpacing(-1)
    , m_columnSpacing(-1)
    , m_useRowSpacing(false)
    , m_useColumnSpacing(false)
    , m_flow(LeftToRight)
    , m_hItemAlign(AlignLeft)
    , m_vItemAlign(AlignTop)
{
}

/*!
    \qmlproperty int QtQuick::Grid::columns

    This property holds the number of columns in the grid. The default
    number of columns is 4.

    If the grid does not have enough items to fill the specified
    number of columns, some columns will be of zero width.
*/

/*!
    \qmlproperty int QtQuick::Grid::rows
    This property holds the number of rows in the grid.

    If the grid does not have enough items to fill the specified
    number of rows, some rows will be of zero width.
*/

void QQuickGrid::setColumns(const int columns)
{
    if (columns == m_columns)
        return;
    m_columns = columns;
    prePositioning();
    emit columnsChanged();
}

void QQuickGrid::setRows(const int rows)
{
    if (rows == m_rows)
        return;
    m_rows = rows;
    prePositioning();
    emit rowsChanged();
}

/*!
    \qmlproperty enumeration QtQuick::Grid::flow
    This property holds the flow of the layout.

    Possible values are:

    \list
    \li Grid.LeftToRight (default) - Items are positioned next to
       each other in the \l layoutDirection, then wrapped to the next line.
    \li Grid.TopToBottom - Items are positioned next to each
       other from top to bottom, then wrapped to the next column.
    \endlist
*/
QQuickGrid::Flow QQuickGrid::flow() const
{
    return m_flow;
}

void QQuickGrid::setFlow(Flow flow)
{
    if (m_flow != flow) {
        m_flow = flow;
        prePositioning();
        emit flowChanged();
    }
}

/*!
    \qmlproperty qreal QtQuick::Grid::rowSpacing

    This property holds the spacing in pixels between rows.

    If this property is not set, then spacing is used for the row spacing.

    By default this property is not set.

    \sa columnSpacing
    \since 5.0
*/
void QQuickGrid::setRowSpacing(const qreal rowSpacing)
{
    if (rowSpacing == m_rowSpacing)
        return;
    m_rowSpacing = rowSpacing;
    m_useRowSpacing = true;
    prePositioning();
    emit rowSpacingChanged();
}

/*!
    \qmlproperty qreal QtQuick::Grid::columnSpacing

    This property holds the spacing in pixels between columns.

    If this property is not set, then spacing is used for the column spacing.

    By default this property is not set.

    \sa rowSpacing
    \since 5.0
*/
void QQuickGrid::setColumnSpacing(const qreal columnSpacing)
{
    if (columnSpacing == m_columnSpacing)
        return;
    m_columnSpacing = columnSpacing;
    m_useColumnSpacing = true;
    prePositioning();
    emit columnSpacingChanged();
}

/*!
    \qmlproperty enumeration QtQuick::Grid::layoutDirection

    This property holds the layout direction of the layout.

    Possible values are:

    \list
    \li Qt.LeftToRight (default) - Items are positioned from the top to bottom,
    and left to right. The flow direction is dependent on the
    \l Grid::flow property.
    \li Qt.RightToLeft - Items are positioned from the top to bottom,
    and right to left. The flow direction is dependent on the
    \l Grid::flow property.
    \endlist

    \sa Flow::layoutDirection, Row::layoutDirection, {Qt Quick Examples - Right to Left}
*/
Qt::LayoutDirection QQuickGrid::layoutDirection() const
{
    return QQuickBasePositionerPrivate::getLayoutDirection(this);
}

void QQuickGrid::setLayoutDirection(Qt::LayoutDirection layoutDirection)
{
    QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
    if (d->layoutDirection != layoutDirection) {
        d->layoutDirection = layoutDirection;
        emit layoutDirectionChanged();
        d->effectiveLayoutDirectionChange();
    }
}

/*!
    \qmlproperty enumeration QtQuick::Grid::effectiveLayoutDirection
    This property holds the effective layout direction of the grid.

    When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
    the visual layout direction of the grid positioner will be mirrored. However, the
    property \l {Grid::layoutDirection}{layoutDirection} will remain unchanged.

    \sa Grid::layoutDirection, {LayoutMirroring}{LayoutMirroring}
*/
Qt::LayoutDirection QQuickGrid::effectiveLayoutDirection() const
{
    return QQuickBasePositionerPrivate::getEffectiveLayoutDirection(this);
}

/*!
    \qmlproperty enumeration QtQuick::Grid::horizontalItemAlignment
    \qmlproperty enumeration QtQuick::Grid::verticalItemAlignment
    \qmlproperty enumeration QtQuick::Grid::effectiveHorizontalItemAlignment

    Sets the horizontal and vertical alignment of items in the Grid. By default,
    the items are vertically aligned to the top. Horizontal
    alignment follows the layoutDirection of the Grid, for example when having a layoutDirection
    from LeftToRight, the items will be aligned on the left.

    The valid values for \c horizontalItemAlignment are, \c Grid.AlignLeft, \c Grid.AlignRight and
    \c Grid.AlignHCenter.

    The valid values for \c verticalItemAlignment are \c Grid.AlignTop, \c Grid.AlignBottom
    and \c Grid.AlignVCenter.

    The below images show three examples of how to align items.

    \table
    \row
        \li
        \li \inlineimage gridLayout_aligntopleft.png
        \li \inlineimage gridLayout_aligntop.png
        \li \inlineimage gridLayout_aligncenter.png
    \row
        \li Horizontal alignment
        \li AlignLeft
        \li AlignHCenter
        \li AlignHCenter
    \row
        \li Vertical alignment
        \li AlignTop
        \li AlignTop
        \li AlignVCenter
    \endtable


    When mirroring the layout using either the attached property LayoutMirroring::enabled or
    by setting the layoutDirection, the horizontal alignment of items will be mirrored as well.
    However, the property \c horizontalItemAlignment will remain unchanged.
    To query the effective horizontal alignment of items, use the read-only property
    \c effectiveHorizontalItemAlignment.

    \sa Grid::layoutDirection, {LayoutMirroring}{LayoutMirroring}
*/
QQuickGrid::HAlignment QQuickGrid::hItemAlign() const
{
    return m_hItemAlign;
}
void QQuickGrid::setHItemAlign(HAlignment align)
{
    if (m_hItemAlign != align) {
        m_hItemAlign = align;
        prePositioning();
        emit horizontalAlignmentChanged(align);
        emit effectiveHorizontalAlignmentChanged(effectiveHAlign());
    }
}

QQuickGrid::HAlignment QQuickGrid::effectiveHAlign() const
{
    HAlignment effectiveAlignment = m_hItemAlign;
    if (effectiveLayoutDirection() == Qt::RightToLeft) {
        switch (hItemAlign()) {
        case AlignLeft:
            effectiveAlignment = AlignRight;
            break;
        case AlignRight:
            effectiveAlignment = AlignLeft;
            break;
        default:
            break;
        }
    }
    return effectiveAlignment;
}


QQuickGrid::VAlignment QQuickGrid::vItemAlign() const
{
    return m_vItemAlign;
}
void QQuickGrid::setVItemAlign(VAlignment align)
{
    if (m_vItemAlign != align) {
        m_vItemAlign = align;
        prePositioning();
        emit verticalAlignmentChanged(align);
    }
}

void QQuickGrid::doPositioning(QSizeF *contentSize)
{
    //Precondition: All items in the positioned list have a valid item pointer and should be positioned
    QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
    int c = m_columns;
    int r = m_rows;
    int numVisible = positionedItems.count();

    if (m_columns <= 0 && m_rows <= 0) {
        c = 4;
        r = (numVisible+3)/4;
    } else if (m_rows <= 0) {
        r = (numVisible+(m_columns-1))/m_columns;
    } else if (m_columns <= 0) {
        c = (numVisible+(m_rows-1))/m_rows;
    }

    if (r == 0 || c == 0) {
        contentSize->setHeight(topPadding() + bottomPadding());
        contentSize->setWidth(leftPadding() + rightPadding());
        return; //Nothing else to do
    }

    QList<qreal> maxColWidth;
    QList<qreal> maxRowHeight;
    int childIndex =0;
    if (m_flow == LeftToRight) {
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (j == 0)
                    maxRowHeight << 0;
                if (i == 0)
                    maxColWidth << 0;

                if (childIndex == numVisible)
                    break;

                const PositionedItem &child = positionedItems.at(childIndex++);
                if (child.item->width() > maxColWidth[j])
                    maxColWidth[j] = child.item->width();
                if (child.item->height() > maxRowHeight[i])
                    maxRowHeight[i] = child.item->height();
            }
        }
    } else {
        for (int j = 0; j < c; j++) {
            for (int i = 0; i < r; i++) {
                if (j == 0)
                    maxRowHeight << 0;
                if (i == 0)
                    maxColWidth << 0;

                if (childIndex == numVisible)
                    break;

                const PositionedItem &child = positionedItems.at(childIndex++);
                if (child.item->width() > maxColWidth[j])
                    maxColWidth[j] = child.item->width();
                if (child.item->height() > maxRowHeight[i])
                    maxRowHeight[i] = child.item->height();
            }
        }
    }

    qreal columnSpacing = m_useColumnSpacing ? m_columnSpacing : spacing();
    qreal rowSpacing = m_useRowSpacing ? m_rowSpacing : spacing();

    qreal widthSum = 0;
    for (int j = 0; j < maxColWidth.size(); j++) {
        if (j)
            widthSum += columnSpacing;
        widthSum += maxColWidth[j];
    }
    widthSum += leftPadding() + rightPadding();

    qreal heightSum = 0;
    for (int i = 0; i < maxRowHeight.size(); i++) {
        if (i)
            heightSum += rowSpacing;
        heightSum += maxRowHeight[i];
    }
    heightSum += topPadding() + bottomPadding();

    contentSize->setHeight(heightSum);
    contentSize->setWidth(widthSum);

    int end = 0;
    if (widthValid())
        end = width();
    else
        end = widthSum;

    qreal xoffset = leftPadding();
    if (!d->isLeftToRight())
        xoffset = end - rightPadding();
    qreal yoffset = topPadding();
    int curRow =0;
    int curCol =0;
    for (int i = 0; i < positionedItems.count(); ++i) {
        PositionedItem &child = positionedItems[i];
        qreal childXOffset = xoffset;

        if (effectiveHAlign() == AlignRight)
            childXOffset += maxColWidth[curCol] - child.item->width();
        else if (hItemAlign() == AlignHCenter)
            childXOffset += (maxColWidth[curCol] - child.item->width())/2.0;

        if (!d->isLeftToRight())
            childXOffset -= maxColWidth[curCol];

        qreal alignYOffset = yoffset;
        if (m_vItemAlign == AlignVCenter)
            alignYOffset += (maxRowHeight[curRow] - child.item->height())/2.0;
        else if (m_vItemAlign == AlignBottom)
            alignYOffset += maxRowHeight[curRow] - child.item->height();

        positionItem(childXOffset, alignYOffset, &child);
        child.updatePadding(leftPadding(), topPadding(), rightPadding(), bottomPadding());

        if (m_flow == LeftToRight) {
            if (d->isLeftToRight())
                xoffset += maxColWidth[curCol]+columnSpacing;
            else
                xoffset -= maxColWidth[curCol]+columnSpacing;
            curCol++;
            curCol %= c;
            if (!curCol) {
                yoffset += maxRowHeight[curRow]+rowSpacing;
                if (d->isLeftToRight())
                    xoffset = leftPadding();
                else
                    xoffset = end - rightPadding();
                curRow++;
                if (curRow>=r)
                    break;
            }
        } else {
            yoffset += maxRowHeight[curRow]+rowSpacing;
            curRow++;
            curRow %= r;
            if (!curRow) {
                if (d->isLeftToRight())
                    xoffset += maxColWidth[curCol]+columnSpacing;
                else
                    xoffset -= maxColWidth[curCol]+columnSpacing;
                yoffset = topPadding();
                curCol++;
                if (curCol>=c)
                    break;
            }
        }
    }
}

void QQuickGrid::reportConflictingAnchors()
{
    QQuickBasePositionerPrivate *d = static_cast<QQuickBasePositionerPrivate*>(QQuickBasePositionerPrivate::get(this));
    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        const PositionedItem &child = positionedItems.at(ii);
        if (child.item) {
            QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
            if (anchors && (anchors->usedAnchors() || anchors->fill() || anchors->centerIn())) {
                d->anchorConflict = true;
                break;
            }
        }
    }
    if (d->anchorConflict)
        qmlInfo(this) << "Cannot specify anchors for items inside Grid." << " Grid will not function.";
}

/*!
    \qmltype Flow
    \instantiates QQuickFlow
    \inqmlmodule QtQuick
    \inherits Item
    \ingroup qtquick-positioners
    \brief Positions its children side by side, wrapping as necessary

    The Flow item positions its child items like words on a page, wrapping them
    to create rows or columns of items.

    Below is a Flow that contains various \l Text items:

    \snippet qml/flow.qml flow item

    The Flow item automatically positions the child \l Text items side by
    side, wrapping as necessary:

    \image qml-flow-snippet.png

    If an item within a Flow is not \l {Item::}{visible}, or if it has a width or
    height of 0, the item will not be laid out and it will not be visible within the
    Flow. Also, since a Flow automatically positions its children, a child
    item within a Flow should not set its \l {Item::x}{x} or \l {Item::y}{y} positions
    or anchor itself with any of the \l {Item::anchors}{anchor} properties.

    For more information on using Flow and other related positioner-types, see
    \l{Item Positioners}.

  \sa Column, Row, Grid, Positioner, {Qt Quick Examples - Positioners}
*/
/*!
    \since 5.6
    \qmlproperty real QtQuick::Flow::padding
    \qmlproperty real QtQuick::Flow::topPadding
    \qmlproperty real QtQuick::Flow::leftPadding
    \qmlproperty real QtQuick::Flow::bottomPadding
    \qmlproperty real QtQuick::Flow::rightPadding

    These properties hold the padding around the content.
*/
/*!
    \qmlproperty Transition QtQuick::Flow::populate

    This property holds the transition to be run for items that are part of
    this positioner at the time of its creation. The transition is run when the positioner
    is first created.

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Flow::add

    This property holds the transition to be run for items that are added to this
    positioner. For a positioner, this applies to:

    \list
    \li Items that are created or reparented as a child of the positioner after the
        positioner has been created
    \li Child items that change their \l Item::visible property from false to true, and thus
       are now visible
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being added. See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note This transition is not applied to the items that already part of the positioner
    at the time of its creation. In this case, the \l populate transition is applied instead.

    \sa populate, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
    \qmlproperty Transition QtQuick::Flow::move

    This property holds the transition to run for items that have moved within the
    positioner. For a positioner, this applies to:

    \list
    \li Child items that move when they are displaced due to the addition, removal or
       rearrangement of other items in the positioner
    \li Child items that are repositioned due to the resizing of other items in the positioner
    \endlist

    The transition can use the \l ViewTransition property to access more details about
    the item that is being moved. Note, however, that for this move transition, the
    ViewTransition.targetIndexes and ViewTransition.targetItems lists are only set when
    this transition is triggered by the addition of other items in the positioner; in other
    cases, these lists will be empty.  See the \l ViewTransition documentation for more details
    and examples on using these transitions.

    \note In \l {Qt Quick 1}, this transition was applied to all items that were part of the
    positioner at the time of its creation. From \l {Qt Quick}{QtQuick 2} onwards, positioners apply the
    \l populate transition to these items instead.

    \sa add, ViewTransition, {Qt Quick Examples - Positioners}
*/
/*!
  \qmlproperty real QtQuick::Flow::spacing

  spacing is the amount in pixels left empty between each adjacent
  item, and defaults to 0.

  \sa Grid::spacing
*/

class QQuickFlowPrivate : public QQuickBasePositionerPrivate
{
    Q_DECLARE_PUBLIC(QQuickFlow)

public:
    QQuickFlowPrivate()
        : QQuickBasePositionerPrivate(), flow(QQuickFlow::LeftToRight)
    {}

    void effectiveLayoutDirectionChange()
    {
        Q_Q(QQuickFlow);
        // Don't postpone, as it might be the only trigger for visible changes.
        q->prePositioning();
        emit q->effectiveLayoutDirectionChanged();
    }

    QQuickFlow::Flow flow;
};

QQuickFlow::QQuickFlow(QQuickItem *parent)
: QQuickBasePositioner(*(new QQuickFlowPrivate), Both, parent)
{
    Q_D(QQuickFlow);
    // Flow layout requires relayout if its own size changes too.
    d->addItemChangeListener(d, QQuickItemPrivate::Geometry);
}

/*!
    \qmlproperty enumeration QtQuick::Flow::flow
    This property holds the flow of the layout.

    Possible values are:

    \list
    \li Flow.LeftToRight (default) - Items are positioned next to
    to each other according to the \l layoutDirection until the width of the Flow
    is exceeded, then wrapped to the next line.
    \li Flow.TopToBottom - Items are positioned next to each
    other from top to bottom until the height of the Flow is exceeded,
    then wrapped to the next column.
    \endlist
*/
QQuickFlow::Flow QQuickFlow::flow() const
{
    Q_D(const QQuickFlow);
    return d->flow;
}

void QQuickFlow::setFlow(Flow flow)
{
    Q_D(QQuickFlow);
    if (d->flow != flow) {
        d->flow = flow;
        prePositioning();
        emit flowChanged();
    }
}

/*!
    \qmlproperty enumeration QtQuick::Flow::layoutDirection

    This property holds the layout direction of the layout.

    Possible values are:

    \list
    \li Qt.LeftToRight (default) - Items are positioned from the top to bottom,
    and left to right. The flow direction is dependent on the
    \l Flow::flow property.
    \li Qt.RightToLeft - Items are positioned from the top to bottom,
    and right to left. The flow direction is dependent on the
    \l Flow::flow property.
    \endlist

    \sa Grid::layoutDirection, Row::layoutDirection, {Qt Quick Examples - Right to Left}
*/

Qt::LayoutDirection QQuickFlow::layoutDirection() const
{
    Q_D(const QQuickFlow);
    return d->layoutDirection;
}

void QQuickFlow::setLayoutDirection(Qt::LayoutDirection layoutDirection)
{
    Q_D(QQuickFlow);
    if (d->layoutDirection != layoutDirection) {
        d->layoutDirection = layoutDirection;
        emit layoutDirectionChanged();
        d->effectiveLayoutDirectionChange();
    }
}

/*!
    \qmlproperty enumeration QtQuick::Flow::effectiveLayoutDirection
    This property holds the effective layout direction of the flow.

    When using the attached property \l {LayoutMirroring::enabled}{LayoutMirroring::enabled} for locale layouts,
    the visual layout direction of the grid positioner will be mirrored. However, the
    property \l {Flow::layoutDirection}{layoutDirection} will remain unchanged.

    \sa Flow::layoutDirection, {LayoutMirroring}{LayoutMirroring}
*/

Qt::LayoutDirection QQuickFlow::effectiveLayoutDirection() const
{
    return QQuickBasePositionerPrivate::getEffectiveLayoutDirection(this);
}

void QQuickFlow::doPositioning(QSizeF *contentSize)
{
    //Precondition: All items in the positioned list have a valid item pointer and should be positioned
    Q_D(QQuickFlow);

    qreal hoffset1 = leftPadding();
    qreal hoffset2 = rightPadding();
    if (!d->isLeftToRight())
        qSwap(hoffset1, hoffset2);
    qreal hoffset = hoffset1;
    const qreal voffset1 = topPadding();
    qreal voffset = voffset1;
    qreal linemax = 0;
    QList<qreal> hoffsets;
    contentSize->setWidth(qMax(contentSize->width(), hoffset1 + hoffset2));
    contentSize->setHeight(qMax(contentSize->height(), voffset + bottomPadding()));

    for (int i = 0; i < positionedItems.count(); ++i) {
        PositionedItem &child = positionedItems[i];

        if (d->flow == LeftToRight)  {
            if (widthValid() && hoffset != hoffset1 && hoffset + child.item->width() + hoffset2 > width()) {
                hoffset = hoffset1;
                voffset += linemax + spacing();
                linemax = 0;
            }
        } else {
            if (heightValid() && voffset != voffset1 && voffset + child.item->height() + bottomPadding() > height()) {
                voffset = voffset1;
                hoffset += linemax + spacing();
                linemax = 0;
            }
        }

        if (d->isLeftToRight()) {
            positionItem(hoffset, voffset, &child);
            child.updatePadding(leftPadding(), topPadding(), rightPadding(), bottomPadding());
        } else {
            hoffsets << hoffset;
            positionItemY(voffset, &child);
            child.topPadding = topPadding();
            child.bottomPadding = bottomPadding();
        }

        contentSize->setWidth(qMax(contentSize->width(), hoffset + child.item->width() + hoffset2));
        contentSize->setHeight(qMax(contentSize->height(), voffset + child.item->height() + bottomPadding()));

        if (d->flow == LeftToRight)  {
            hoffset += child.item->width();
            hoffset += spacing();
            linemax = qMax(linemax, child.item->height());
        } else {
            voffset += child.item->height();
            voffset += spacing();
            linemax = qMax(linemax, child.item->width());
        }
    }

    if (d->isLeftToRight())
        return;

    qreal end;
    if (widthValid())
        end = width();
    else
        end = contentSize->width();
    int acc = 0;
    for (int i = 0; i < positionedItems.count(); ++i) {
        PositionedItem &child = positionedItems[i];
        hoffset = end - hoffsets[acc++] - child.item->width();
        positionItemX(hoffset, &child);
        child.leftPadding = leftPadding();
        child.rightPadding = rightPadding();
    }
}

void QQuickFlow::reportConflictingAnchors()
{
    Q_D(QQuickFlow);
    for (int ii = 0; ii < positionedItems.count(); ++ii) {
        const PositionedItem &child = positionedItems.at(ii);
        if (child.item) {
            QQuickAnchors *anchors = QQuickItemPrivate::get(static_cast<QQuickItem *>(child.item))->_anchors;
            if (anchors && (anchors->usedAnchors() || anchors->fill() || anchors->centerIn())) {
                d->anchorConflict = true;
                break;
            }
        }
    }
    if (d->anchorConflict)
        qmlInfo(this) << "Cannot specify anchors for items inside Flow." << " Flow will not function.";
}

QT_END_NAMESPACE