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
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QWidget>
#include <QLinkedList>
#include <QtCore/qstack.h>
#include "qgraphicsanchorlayout_p.h"
void ParallelAnchorData::updateChildrenSizes()
{
firstEdge->sizeAtMinimum = secondEdge->sizeAtMinimum = sizeAtMinimum;
firstEdge->sizeAtPreferred = secondEdge->sizeAtPreferred = sizeAtPreferred;
firstEdge->sizeAtMaximum = secondEdge->sizeAtMaximum = sizeAtMaximum;
firstEdge->updateChildrenSizes();
secondEdge->updateChildrenSizes();
}
void ParallelAnchorData::refreshSizeHints()
{
// ### should we warn if the parallel connection is invalid?
// e.g. 1-2-3 with 10-20-30, the minimum of the latter is
// bigger than the maximum of the former.
firstEdge->refreshSizeHints();
secondEdge->refreshSizeHints();
minSize = qMax(firstEdge->minSize, secondEdge->minSize);
maxSize = qMin(firstEdge->maxSize, secondEdge->maxSize);
prefSize = qMax(firstEdge->prefSize, secondEdge->prefSize);
prefSize = qMin(prefSize, maxSize);
sizeAtMinimum = prefSize;
sizeAtPreferred = prefSize;
sizeAtMaximum = prefSize;
}
void SequentialAnchorData::updateChildrenSizes()
{
qreal minFactor = sizeAtMinimum / minSize;
qreal prefFactor = sizeAtPreferred / prefSize;
qreal maxFactor = sizeAtMaximum / maxSize;
for (int i = 0; i < m_edges.count(); ++i) {
m_edges[i]->sizeAtMinimum = m_edges[i]->minSize * minFactor;
m_edges[i]->sizeAtPreferred = m_edges[i]->prefSize * prefFactor;
m_edges[i]->sizeAtMaximum = m_edges[i]->maxSize * maxFactor;
m_edges[i]->updateChildrenSizes();
}
}
void SequentialAnchorData::refreshSizeHints()
{
minSize = 0;
prefSize = 0;
maxSize = 0;
for (int i = 0; i < m_edges.count(); ++i) {
AnchorData *edge = m_edges.at(i);
edge->refreshSizeHints();
minSize += edge->minSize;
prefSize += edge->prefSize;
maxSize += edge->maxSize;
}
sizeAtMinimum = prefSize;
sizeAtPreferred = prefSize;
sizeAtMaximum = prefSize;
}
void AnchorData::dump(int indent) {
if (type == Parallel) {
qDebug("%*s type: parallel:", indent, "");
ParallelAnchorData *p = static_cast<ParallelAnchorData *>(this);
p->firstEdge->dump(indent+2);
p->secondEdge->dump(indent+2);
} else if (type == Sequential) {
SequentialAnchorData *s = static_cast<SequentialAnchorData *>(this);
int kids = s->m_edges.count();
qDebug("%*s type: sequential(%d):", indent, "", kids);
for (int i = 0; i < kids; ++i) {
s->m_edges.at(i)->dump(indent+2);
}
} else {
qDebug("%*s type: Normal:", indent, "");
}
}
QSimplexConstraint *GraphPath::constraint(const GraphPath &path) const
{
// Calculate
QSet<AnchorData *> cPositives;
QSet<AnchorData *> cNegatives;
QSet<AnchorData *> intersection;
cPositives = positives + path.negatives;
cNegatives = negatives + path.positives;
intersection = cPositives & cNegatives;
cPositives -= intersection;
cNegatives -= intersection;
// Fill
QSimplexConstraint *c = new QSimplexConstraint;
QSet<AnchorData *>::iterator i;
for (i = cPositives.begin(); i != cPositives.end(); ++i)
c->variables.insert(*i, 1.0);
for (i = cNegatives.begin(); i != cNegatives.end(); ++i)
c->variables.insert(*i, -1.0);
return c;
}
QString GraphPath::toString() const
{
QString string(QLatin1String("Path: "));
foreach(AnchorData *edge, positives)
string += QString::fromAscii(" (+++) %1").arg(edge->toString());
foreach(AnchorData *edge, negatives)
string += QString::fromAscii(" (---) %1").arg(edge->toString());
return string;
}
QGraphicsAnchorLayoutPrivate::QGraphicsAnchorLayoutPrivate()
: calculateGraphCacheDirty(1)
{
for (int i = 0; i < NOrientations; ++i)
spacing[i] = -1;
}
QGraphicsAnchorLayout::Edge QGraphicsAnchorLayoutPrivate::oppositeEdge(
QGraphicsAnchorLayout::Edge edge)
{
switch (edge) {
case QGraphicsAnchorLayout::Left:
edge = QGraphicsAnchorLayout::Right;
break;
case QGraphicsAnchorLayout::Right:
edge = QGraphicsAnchorLayout::Left;
break;
case QGraphicsAnchorLayout::Top:
edge = QGraphicsAnchorLayout::Bottom;
break;
case QGraphicsAnchorLayout::Bottom:
edge = QGraphicsAnchorLayout::Top;
break;
default:
break;
}
return edge;
}
/*!
* \internal
*
* helper function in order to avoid overflowing anchor sizes
* the returned size will never be larger than FLT_MAX
*
*/
inline static qreal checkAdd(qreal a, qreal b)
{
if (FLT_MAX - b < a)
return FLT_MAX;
return a + b;
}
/*!
* \internal
*
* Takes the sequence of vertices described by (\a before, \a vertices, \a after) and replaces
* all anchors connected to the vertices in \a vertices with one simplified anchor between
* \a before and \a after. The simplified anchor will be a placeholder for all the previous
* anchors between \a before and \a after, and can be restored back to the anchors it is a
* placeholder for.
*/
static void simplifySequentialChunk(Graph<AnchorVertex, AnchorData> *graph,
AnchorVertex *before,
const QVector<AnchorVertex*> &vertices,
AnchorVertex *after)
{
int i;
#if 0
QString strVertices;
for (i = 0; i < vertices.count(); ++i)
strVertices += QString::fromAscii("%1 - ").arg(vertices.at(i)->toString());
QString strPath = QString::fromAscii("%1 - %2%3").arg(before->toString(), strVertices, after->toString());
qDebug("simplifying [%s] to [%s - %s]", qPrintable(strPath), qPrintable(before->toString()), qPrintable(after->toString()));
#endif
qreal min = 0;
qreal pref = 0;
qreal max = 0;
SequentialAnchorData *sequence = new SequentialAnchorData;
AnchorVertex *prev = before;
AnchorData *data;
for (i = 0; i <= vertices.count(); ++i) {
AnchorVertex *next = (i < vertices.count()) ? vertices.at(i) : after;
data = graph->takeEdge(prev, next);
min += data->minSize;
pref += data->prefSize;
max = checkAdd(max, data->maxSize);
sequence->m_edges.append(data);
prev = next;
}
// insert new
sequence->minSize = min;
sequence->prefSize = pref;
sequence->maxSize = max;
// Unless these values are overhidden by the simplex solver later-on,
// anchors will keep their own preferred size.
sequence->sizeAtMinimum = pref;
sequence->sizeAtPreferred = pref;
sequence->sizeAtMaximum = pref;
sequence->setVertices(vertices);
sequence->origin = data->origin == vertices.last() ? before : after;
AnchorData *newAnchor = sequence;
if (AnchorData *oldAnchor = graph->takeEdge(before, after)) {
newAnchor = new ParallelAnchorData(oldAnchor, sequence);
min = qMax(oldAnchor->minSize, sequence->minSize);
max = qMin(oldAnchor->maxSize, sequence->maxSize);
pref = qMax(oldAnchor->prefSize, sequence->prefSize);
pref = qMin(pref, max);
newAnchor->minSize = min;
newAnchor->prefSize = pref;
newAnchor->maxSize = max;
// Same as above, by default, keep preferred size.
newAnchor->sizeAtMinimum = pref;
newAnchor->sizeAtPreferred = pref;
newAnchor->sizeAtMaximum = pref;
}
graph->createEdge(before, after, newAnchor);
}
/*!
* \internal
*
* The purpose of this function is to simplify the graph. The process of simplification can be
* described as:
*
* 1. Simplify all sequences of anchors into one anchor.
* If not first iteration and no further simplification was done, go to (3)
* 2. Simplify two parallel anchors into one anchor.
* If any simplification was done, go to (1)
* 3. Done
*
*
* The algorithm walks the graph in depth-first order, and only collects vertices that has two
* edges connected to it. If the vertex does not have two edges or if it is a layout edge,
* it will take all the previously collected vertices and try to create a simplified sequential
* anchor representing all the previously collected vertices.
* Once the simplified anchor is inserted, the collected list is cleared in order to find the next
* sequence to simplify.
* Note that there are some catches to this that are not covered by the above explanation.
*
*
* Notes:
* * The algorithm should not make a sequence of the layout edge anchors.
* => Make sure those edges are not traversed
* * A generic algorithm will make a sequential simplification node of a Left-HCenter-Right
* sequence. This is ok, but that sequence should not be affected by stretch factors.
*
*/
void QGraphicsAnchorLayoutPrivate::simplifyGraph(QGraphicsAnchorLayoutPrivate::Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
AnchorVertex *v = g.rootVertex();
if (!v)
return;
QSet<AnchorVertex*> visited;
QStack<AnchorVertex *> stack;
stack.push(v);
QVector<AnchorVertex*> candidates;
const QGraphicsAnchorLayout::Edge centerEdge = pickEdge(QGraphicsAnchorLayout::HCenter, orientation);
const QGraphicsAnchorLayout::Edge layoutEdge = oppositeEdge(v->m_edge);
// walk depth-first.
while (!stack.isEmpty()) {
v = stack.pop();
QList<AnchorVertex *> vertices = g.adjacentVertices(v);
const int count = vertices.count();
bool endOfSequence = (v->m_item == q && v->m_edge == layoutEdge) || count != 2;
if (count == 2 && v->m_item != q) {
candidates.append(v);
if (visited.contains(vertices.first()) && visited.contains(vertices.last())) {
// in case of a cycle
endOfSequence = true;
}
}
if (endOfSequence && candidates.count() >= 2) {
int i;
AnchorVertex *afterSequence= 0;
QList<AnchorVertex *> adjacentOfSecondLastVertex = g.adjacentVertices(candidates.last());
Q_ASSERT(adjacentOfSecondLastVertex.count() == 2);
if (adjacentOfSecondLastVertex.first() == candidates.at(candidates.count() - 2))
afterSequence = adjacentOfSecondLastVertex.last();
else
afterSequence = adjacentOfSecondLastVertex.first();
AnchorVertex *beforeSequence = 0;
QList<AnchorVertex *> adjacentOfSecondVertex = g.adjacentVertices(candidates.first());
Q_ASSERT(adjacentOfSecondVertex.count() == 2);
if (adjacentOfSecondVertex.first() == candidates.at(1))
beforeSequence = adjacentOfSecondVertex.last();
else
beforeSequence = adjacentOfSecondVertex.first();
// The complete path of the sequence to simplify is: beforeSequence, <candidates>, afterSequence
// where beforeSequence and afterSequence are the endpoints where the anchor is inserted
// between.
#if 0
// ### DEBUG
QString strCandidates;
for (i = 0; i < candidates.count(); ++i)
strCandidates += QString::fromAscii("%1 - ").arg(candidates.at(i)->toString());
QString strPath = QString::fromAscii("%1 - %2%3").arg(beforeSequence->toString(), strCandidates, afterSequence->toString());
qDebug("candidate list for sequential simplification:\n[%s]", qPrintable(strPath));
#endif
bool forward;
AnchorVertex *prev = beforeSequence;
int intervalFrom = 0;
// Check for directionality (origin). We don't want to destroy that information,
// thus we only combine anchors with the same direction.
// "i" is the index *including* the beforeSequence and afterSequence vertices.
for (i = 1; i <= candidates.count() + 1; ++i) {
bool atVertexAfter = i > candidates.count();
AnchorVertex *v1 = atVertexAfter ? afterSequence : candidates.at(i - 1);
AnchorData *data = g.edgeData(prev, v1);
Q_ASSERT(data);
if (i == 1) {
forward = (prev == data->origin ? true : false);
} else if (forward != (prev == data->origin) || atVertexAfter) {
int intervalTo = i;
if (forward != (prev == data->origin))
--intervalTo;
// intervalFrom and intervalTo should now be indices to the vertex before and
// after the sequential anchor.
if (intervalTo - intervalFrom >= 2) {
// simplify in the range [intervalFrom, intervalTo]
// Trim off internal center anchors (Left-Center/Center-Right) from the
// start and the end of the sequence. We never want to simplify internal
// center anchors where there is an external anchor connected to the center.
AnchorVertex *intervalVertexFrom = intervalFrom == 0 ? beforeSequence : candidates.at(intervalFrom - 1);
if (intervalVertexFrom->m_edge == centerEdge
&& intervalVertexFrom->m_item == candidates.at(intervalFrom)->m_item) {
++intervalFrom;
intervalVertexFrom = candidates.at(intervalFrom - 1);
}
AnchorVertex *intervalVertexTo = intervalTo <= candidates.count() ? candidates.at(intervalTo - 1) : afterSequence;
if (intervalVertexTo->m_edge == centerEdge
&& intervalVertexTo->m_item == candidates.at(intervalTo - 2)->m_item) {
--intervalTo;
intervalVertexTo = candidates.at(intervalTo - 1);
}
QVector<AnchorVertex*> subCandidates;
if (forward) {
subCandidates = candidates.mid(intervalFrom, intervalTo - intervalFrom - 1);
} else {
// reverse the order of the candidates.
qSwap(intervalVertexFrom, intervalVertexTo);
do {
++intervalFrom;
subCandidates.prepend(candidates.at(intervalFrom - 1));
} while (intervalFrom < intervalTo - 1);
}
simplifySequentialChunk(&g, intervalVertexFrom, subCandidates, intervalVertexTo);
// finished simplification of chunk with same direction
}
if (forward == (prev == data->origin))
--intervalTo;
intervalFrom = intervalTo;
forward = !forward;
}
prev = v1;
}
}
if (endOfSequence)
candidates.clear();
for (int i = 0; i < count; ++i) {
AnchorVertex *next = vertices.at(i);
if (next->m_item == q && next->m_edge == centerEdge)
continue;
if (visited.contains(next))
continue;
stack.push(next);
}
visited.insert(v);
}
}
static void restoreSimplifiedAnchor(Graph<AnchorVertex, AnchorData> &g,
AnchorData *edge,
AnchorVertex *before,
AnchorVertex *after)
{
Q_ASSERT(edge->type != AnchorData::Normal);
#if 0
static const char *anchortypes[] = {"Normal",
"Sequential",
"Parallel"};
qDebug("Restoring %s edge.", anchortypes[int(edge->type)]);
#endif
if (edge->type == AnchorData::Sequential) {
SequentialAnchorData* seqEdge = static_cast<SequentialAnchorData*>(edge);
// restore the sequential anchor
AnchorVertex *prev = before;
AnchorVertex *last = after;
if (edge->origin != prev)
qSwap(last, prev);
for (int i = 0; i < seqEdge->m_edges.count(); ++i) {
AnchorVertex *v1 = (i < seqEdge->m_children.count()) ? seqEdge->m_children.at(i) : last;
AnchorData *data = seqEdge->m_edges.at(i);
if (data->type != AnchorData::Normal) {
restoreSimplifiedAnchor(g, data, prev, v1);
} else {
g.createEdge(prev, v1, data);
}
prev = v1;
}
} else if (edge->type == AnchorData::Parallel) {
ParallelAnchorData* parallelEdge = static_cast<ParallelAnchorData*>(edge);
AnchorData *parallelEdges[2] = {parallelEdge->firstEdge,
parallelEdge->secondEdge};
for (int i = 0; i < 2; ++i) {
AnchorData *data = parallelEdges[i];
if (data->type == AnchorData::Normal) {
g.createEdge(before, after, data);
} else {
restoreSimplifiedAnchor(g, data, before, after);
}
}
}
}
void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
QList<QPair<AnchorVertex*, AnchorVertex*> > connections = g.connections();
for (int i = 0; i < connections.count(); ++i) {
AnchorVertex *v1 = connections.at(i).first;
AnchorVertex *v2 = connections.at(i).second;
AnchorData *edge = g.edgeData(v1, v2);
if (edge->type != AnchorData::Normal) {
AnchorData *oldEdge = g.takeEdge(v1, v2);
restoreSimplifiedAnchor(g, edge, v1, v2);
delete oldEdge;
}
}
}
QGraphicsAnchorLayoutPrivate::Orientation
QGraphicsAnchorLayoutPrivate::edgeOrientation(QGraphicsAnchorLayout::Edge edge)
{
return edge > QGraphicsAnchorLayout::Right ? Vertical : Horizontal;
}
/*!
\internal
Create internal anchors to connect the layout edges (Left to Right and
Top to Bottom).
These anchors doesn't have size restrictions, that will be enforced by
other anchors and items in the layout.
*/
void QGraphicsAnchorLayoutPrivate::createLayoutEdges()
{
Q_Q(QGraphicsAnchorLayout);
QGraphicsLayoutItem *layout = q;
// Horizontal
AnchorData *data = new AnchorData(0, 0, QWIDGETSIZE_MAX);
addAnchor(layout, QGraphicsAnchorLayout::Left, layout,
QGraphicsAnchorLayout::Right, data);
data->skipInPreferred = 1;
// Set the Layout Left edge as the root of the horizontal graph.
AnchorVertex *v = internalVertex(layout, QGraphicsAnchorLayout::Left);
graph[Horizontal].setRootVertex(v);
// Vertical
data = new AnchorData(0, 0, QWIDGETSIZE_MAX);
addAnchor(layout, QGraphicsAnchorLayout::Top, layout,
QGraphicsAnchorLayout::Bottom, data);
data->skipInPreferred = 1;
// Set the Layout Top edge as the root of the vertical graph.
v = internalVertex(layout, QGraphicsAnchorLayout::Top);
graph[Vertical].setRootVertex(v);
}
void QGraphicsAnchorLayoutPrivate::deleteLayoutEdges()
{
Q_Q(QGraphicsAnchorLayout);
Q_ASSERT(internalVertex(q, QGraphicsAnchorLayout::HCenter) == NULL);
Q_ASSERT(internalVertex(q, QGraphicsAnchorLayout::VCenter) == NULL);
removeAnchor(q, QGraphicsAnchorLayout::Left, q, QGraphicsAnchorLayout::Right);
removeAnchor(q, QGraphicsAnchorLayout::Top, q, QGraphicsAnchorLayout::Bottom);
}
void QGraphicsAnchorLayoutPrivate::createItemEdges(QGraphicsLayoutItem *item)
{
items.append(item);
// Horizontal
int minimumSize = item->minimumWidth();
int preferredSize = item->preferredWidth();
int maximumSize = item->maximumWidth();
AnchorData *data = new AnchorData(minimumSize, preferredSize, maximumSize);
addAnchor(item, QGraphicsAnchorLayout::Left, item,
QGraphicsAnchorLayout::Right, data);
// Vertical
minimumSize = item->minimumHeight();
preferredSize = item->preferredHeight();
maximumSize = item->maximumHeight();
data = new AnchorData(minimumSize, preferredSize, maximumSize);
addAnchor(item, QGraphicsAnchorLayout::Top, item,
QGraphicsAnchorLayout::Bottom, data);
}
/*!
\internal
By default, each item in the layout is represented internally as
a single anchor in each direction. For instance, from Left to Right.
However, to support anchorage of items to the center of items, we
must split this internal anchor into two half-anchors. From Left
to Center and then from Center to Right, with the restriction that
these anchors must have the same time at all times.
*/
void QGraphicsAnchorLayoutPrivate::createCenterAnchors(
QGraphicsLayoutItem *item, QGraphicsAnchorLayout::Edge centerEdge)
{
Orientation orientation;
switch (centerEdge) {
case QGraphicsAnchorLayout::HCenter:
orientation = Horizontal;
break;
case QGraphicsAnchorLayout::VCenter:
orientation = Vertical;
break;
default:
// Don't create center edges unless needed
return;
}
// Check if vertex already exists
if (internalVertex(item, centerEdge))
return;
// Orientation code
QGraphicsAnchorLayout::Edge firstEdge;
QGraphicsAnchorLayout::Edge lastEdge;
if (orientation == Horizontal) {
firstEdge = QGraphicsAnchorLayout::Left;
lastEdge = QGraphicsAnchorLayout::Right;
} else {
firstEdge = QGraphicsAnchorLayout::Top;
lastEdge = QGraphicsAnchorLayout::Bottom;
}
AnchorVertex *first = internalVertex(item, firstEdge);
AnchorVertex *last = internalVertex(item, lastEdge);
Q_ASSERT(first && last);
// Create new anchors
AnchorData *oldData = graph[orientation].edgeData(first, last);
int minimumSize = oldData->minSize / 2;
int preferredSize = oldData->prefSize / 2;
int maximumSize = oldData->maxSize / 2;
QSimplexConstraint *c = new QSimplexConstraint;
AnchorData *data = new AnchorData(minimumSize, preferredSize, maximumSize);
c->variables.insert(data, 1.0);
addAnchor(item, firstEdge, item, centerEdge, data);
data = new AnchorData(minimumSize, preferredSize, maximumSize);
c->variables.insert(data, -1.0);
addAnchor(item, centerEdge, item, lastEdge, data);
itemCenterConstraints[orientation].append(c);
// Remove old one
removeAnchor(item, firstEdge, item, lastEdge);
}
void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
QGraphicsLayoutItem *item, QGraphicsAnchorLayout::Edge centerEdge,
bool substitute)
{
Orientation orientation;
switch (centerEdge) {
case QGraphicsAnchorLayout::HCenter:
orientation = Horizontal;
break;
case QGraphicsAnchorLayout::VCenter:
orientation = Vertical;
break;
default:
// Don't remove edges that not the center ones
return;
}
// Orientation code
QGraphicsAnchorLayout::Edge firstEdge;
QGraphicsAnchorLayout::Edge lastEdge;
if (orientation == Horizontal) {
firstEdge = QGraphicsAnchorLayout::Left;
lastEdge = QGraphicsAnchorLayout::Right;
} else {
firstEdge = QGraphicsAnchorLayout::Top;
lastEdge = QGraphicsAnchorLayout::Bottom;
}
AnchorVertex *center = internalVertex(item, centerEdge);
if (!center)
return;
AnchorVertex *first = internalVertex(item, firstEdge);
AnchorVertex *last = internalVertex(item, lastEdge);
Q_ASSERT(first);
Q_ASSERT(center);
Q_ASSERT(last);
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
AnchorData *oldData = g.edgeData(first, center);
// Remove center constraint
for (int i = itemCenterConstraints[orientation].count() - 1; i >= 0; --i) {
if (itemCenterConstraints[orientation][i]->variables.contains(oldData)) {
delete itemCenterConstraints[orientation].takeAt(i);
break;
}
}
if (substitute) {
// Create the new anchor that should substitute the left-center-right anchors.
AnchorData *oldData = g.edgeData(first, center);
int minimumSize = oldData->minSize * 2;
int preferredSize = oldData->prefSize * 2;
int maximumSize = oldData->maxSize * 2;
AnchorData *data = new AnchorData(minimumSize, preferredSize, maximumSize);
addAnchor(item, firstEdge, item, lastEdge, data);
// Remove old anchors
removeAnchor(item, firstEdge, item, centerEdge);
removeAnchor(item, centerEdge, item, lastEdge);
} else {
// this is only called from removeAnchors()
// first, remove all non-internal anchors
QList<AnchorVertex*> adjacents = g.adjacentVertices(center);
for (int i = 0; i < adjacents.count(); ++i) {
AnchorVertex *v = adjacents.at(i);
if (v->m_item != item) {
removeAnchor(item, centerEdge, v->m_item, v->m_edge);
}
}
// when all non-internal anchors is removed it will automatically merge the
// center anchor into a left-right (or top-bottom) anchor. We must also delete that.
// by this time, the center vertex is deleted and merged into a non-centered internal anchor
removeAnchor(item, firstEdge, item, lastEdge);
}
}
void QGraphicsAnchorLayoutPrivate::removeCenterConstraints(QGraphicsLayoutItem *item,
Orientation orientation)
{
// Remove the item center constraints associated to this item
// ### This is a temporary solution. We should probably use a better
// data structure to hold items and/or their associated constraints
// so that we can remove those easily
AnchorVertex *first = internalVertex(item, orientation == Horizontal ?
QGraphicsAnchorLayout::Left :
QGraphicsAnchorLayout::Top);
AnchorVertex *center = internalVertex(item, orientation == Horizontal ?
QGraphicsAnchorLayout::HCenter :
QGraphicsAnchorLayout::VCenter);
// Skip if no center constraints exist
if (!center)
return;
Q_ASSERT(first);
AnchorData *internalAnchor = graph[orientation].edgeData(first, center);
// Look for our anchor in all item center constraints, then remove it
for (int i = 0; i < itemCenterConstraints[orientation].size(); ++i) {
if (itemCenterConstraints[orientation][i]->variables.contains(internalAnchor)) {
delete itemCenterConstraints[orientation].takeAt(i);
break;
}
}
}
/*!
* \internal
*
* Helper function that is called from the anchor functions in the public API.
* If \a spacing is 0, it will pick up the spacing defined by the style.
*/
void QGraphicsAnchorLayoutPrivate::anchor(QGraphicsLayoutItem *firstItem,
QGraphicsAnchorLayout::Edge firstEdge,
QGraphicsLayoutItem *secondItem,
QGraphicsAnchorLayout::Edge secondEdge,
qreal *spacing)
{
Q_Q(QGraphicsAnchorLayout);
if ((firstItem == 0) || (secondItem == 0)) {
qWarning("QGraphicsAnchorLayout::anchor(): "
"Cannot anchor NULL items");
return;
}
if (firstItem == secondItem) {
qWarning("QGraphicsAnchorLayout::anchor(): "
"Cannot anchor the item to itself");
return;
}
if (edgeOrientation(secondEdge) != edgeOrientation(firstEdge)) {
qWarning("QGraphicsAnchorLayout::anchor(): "
"Cannot anchor edges of different orientations");
return;
}
// In QGraphicsAnchorLayout, items are represented in its internal
// graph as four anchors that connect:
// - Left -> HCenter
// - HCenter-> Right
// - Top -> VCenter
// - VCenter -> Bottom
// Ensure that the internal anchors have been created for both items.
if (firstItem != q && !items.contains(firstItem)) {
createItemEdges(firstItem);
addChildLayoutItem(firstItem);
}
if (secondItem != q && !items.contains(secondItem)) {
createItemEdges(secondItem);
addChildLayoutItem(secondItem);
}
// Create center edges if needed
createCenterAnchors(firstItem, firstEdge);
createCenterAnchors(secondItem, secondEdge);
// Use heuristics to find out what the user meant with this anchor.
correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge);
AnchorData *data;
if (!spacing) {
// If firstItem or secondItem is the layout itself, the spacing will default to 0.
// Otherwise, the following matrix is used (questionmark means that the spacing
// is queried from the style):
// from
// to Left HCenter Right
// Left 0 0 ?
// HCenter 0 0 0
// Right ? 0 0
if (firstItem != q
&& secondItem != q
&& pickEdge(firstEdge, Horizontal) != QGraphicsAnchorLayout::HCenter
&& oppositeEdge(firstEdge) == secondEdge) {
data = new AnchorData; // ask the style later
} else {
data = new AnchorData(0); // spacing should be 0
}
addAnchor(firstItem, firstEdge, secondItem, secondEdge, data);
} else if (*spacing >= 0) {
data = new AnchorData(*spacing);
addAnchor(firstItem, firstEdge, secondItem, secondEdge, data);
} else {
data = new AnchorData(-*spacing);
addAnchor(secondItem, secondEdge, firstItem, firstEdge, data);
}
}
void QGraphicsAnchorLayoutPrivate::addAnchor(QGraphicsLayoutItem *firstItem,
QGraphicsAnchorLayout::Edge firstEdge,
QGraphicsLayoutItem *secondItem,
QGraphicsAnchorLayout::Edge secondEdge,
AnchorData *data)
{
// Is the Vertex (firstItem, firstEdge) already represented in our
// internal structure?
AnchorVertex *v1 = addInternalVertex(firstItem, firstEdge);
AnchorVertex *v2 = addInternalVertex(secondItem, secondEdge);
// Remove previous anchor
// ### Could we update the existing edgeData rather than creating a new one?
if (graph[edgeOrientation(firstEdge)].edgeData(v1, v2))
removeAnchor(firstItem, firstEdge, secondItem, secondEdge);
// Create a bi-directional edge in the sense it can be transversed both
// from v1 or v2. "data" however is shared between the two references
// so we still know that the anchor direction is from 1 to 2.
data->origin = v1;
data->name = QString::fromAscii("%1 --to--> %2").arg(v1->toString()).arg(v2->toString());
graph[edgeOrientation(firstEdge)].createEdge(v1, v2, data);
}
AnchorVertex *QGraphicsAnchorLayoutPrivate::addInternalVertex(QGraphicsLayoutItem *item,
QGraphicsAnchorLayout::Edge edge)
{
QPair<QGraphicsLayoutItem *, QGraphicsAnchorLayout::Edge> pair(item, edge);
QPair<AnchorVertex *, int> v = m_vertexList.value(pair);
if (!v.first) {
Q_ASSERT(v.second == 0);
v.first = new AnchorVertex(item, edge);
}
v.second++;
m_vertexList.insert(pair, v);
return v.first;
}
/**
* \internal
*
* returns the AnchorVertex that was dereferenced, also when it was removed.
* returns 0 if it did not exist.
*/
void QGraphicsAnchorLayoutPrivate::removeInternalVertex(QGraphicsLayoutItem *item,
QGraphicsAnchorLayout::Edge edge)
{
QPair<QGraphicsLayoutItem *, QGraphicsAnchorLayout::Edge> pair(item, edge);
QPair<AnchorVertex *, int> v = m_vertexList.value(pair);
if (!v.first) {
qWarning("This item with this edge is not in the graph");
return;
}
v.second--;
if (v.second == 0) {
// Remove reference and delete vertex
m_vertexList.remove(pair);
delete v.first;
} else {
// Update reference count
m_vertexList.insert(pair, v);
if ((v.second == 2) &&
((edge == QGraphicsAnchorLayout::HCenter) ||
(edge == QGraphicsAnchorLayout::VCenter))) {
removeCenterAnchors(item, edge, true);
}
}
}
void QGraphicsAnchorLayoutPrivate::removeAnchor(QGraphicsLayoutItem *firstItem,
QGraphicsAnchorLayout::Edge firstEdge,
QGraphicsLayoutItem *secondItem,
QGraphicsAnchorLayout::Edge secondEdge)
{
// Look for both vertices
AnchorVertex *v1 = internalVertex(firstItem, firstEdge);
AnchorVertex *v2 = internalVertex(secondItem, secondEdge);
Q_ASSERT(v1 && v2);
// Remove edge from graph
graph[edgeOrientation(firstEdge)].removeEdge(v1, v2);
// Decrease vertices reference count (may trigger a deletion)
removeInternalVertex(firstItem, firstEdge);
removeInternalVertex(secondItem, secondEdge);
}
void QGraphicsAnchorLayoutPrivate::removeVertex(QGraphicsLayoutItem *item, QGraphicsAnchorLayout::Edge edge)
{
if (AnchorVertex *v = internalVertex(item, edge)) {
Graph<AnchorVertex, AnchorData> &g = graph[edgeOrientation(edge)];
const QList<AnchorVertex *> allVertices = graph[edgeOrientation(edge)].adjacentVertices(v);
AnchorVertex *v2;
foreach (v2, allVertices) {
g.removeEdge(v, v2);
removeInternalVertex(item, edge);
removeInternalVertex(v2->m_item, v2->m_edge);
}
}
}
void QGraphicsAnchorLayoutPrivate::removeAnchors(QGraphicsLayoutItem *item)
{
// remove the center anchor first!!
removeCenterAnchors(item, QGraphicsAnchorLayout::HCenter, false);
removeVertex(item, QGraphicsAnchorLayout::Left);
removeVertex(item, QGraphicsAnchorLayout::Right);
removeCenterAnchors(item, QGraphicsAnchorLayout::VCenter, false);
removeVertex(item, QGraphicsAnchorLayout::Top);
removeVertex(item, QGraphicsAnchorLayout::Bottom);
}
/*!
\internal
Use heuristics to determine the correct orientation of a given anchor.
After API discussions, we decided we would like expressions like
anchor(A, Left, B, Right) to mean the same as anchor(B, Right, A, Left).
The problem with this is that anchors could become ambiguous, for
instance, what does the anchor A, B of size X mean?
"pos(B) = pos(A) + X" or "pos(A) = pos(B) + X" ?
To keep the API user friendly and at the same time, keep our algorithm
deterministic, we use an heuristic to determine a direction for each
added anchor and then keep it. The heuristic is based on the fact
that people usually avoid overlapping items, therefore:
"A, RIGHT to B, LEFT" means that B is to the LEFT of A.
"B, LEFT to A, RIGHT" is corrected to the above anchor.
Special correction is also applied when one of the items is the
layout. We handle Layout Left as if it was another items's Right
and Layout Right as another item's Left.
*/
void QGraphicsAnchorLayoutPrivate::correctEdgeDirection(QGraphicsLayoutItem *&firstItem,
QGraphicsAnchorLayout::Edge &firstEdge,
QGraphicsLayoutItem *&secondItem,
QGraphicsAnchorLayout::Edge &secondEdge)
{
Q_Q(QGraphicsAnchorLayout);
QGraphicsAnchorLayout::Edge effectiveFirst = firstEdge;
QGraphicsAnchorLayout::Edge effectiveSecond = secondEdge;
if (firstItem == q)
effectiveFirst = QGraphicsAnchorLayoutPrivate::oppositeEdge(firstEdge);
if (secondItem == q)
effectiveSecond = QGraphicsAnchorLayoutPrivate::oppositeEdge(secondEdge);
if (effectiveFirst < effectiveSecond) {
// ### DEBUG
/* printf("Swapping Anchor from %s %d --to--> %s %d\n",
firstItem->isLayout() ? "<layout>" :
qPrintable(static_cast<QGraphicsWidget *>(firstItem)->data(0).toString()),
firstEdge,
secondItem->isLayout() ? "<layout>" :
qPrintable(static_cast<QGraphicsWidget *>(secondItem)->data(0).toString()),
secondEdge);
*/
qSwap(firstItem, secondItem);
qSwap(firstEdge, secondEdge);
}
}
qreal QGraphicsAnchorLayoutPrivate::effectiveSpacing(Orientation orientation) const
{
Q_Q(const QGraphicsAnchorLayout);
qreal s = spacing[orientation];
if (s < 0) {
QGraphicsLayoutItem *parent = q->parentLayoutItem();
while (parent && parent->isLayout()) {
parent = parent->parentLayoutItem();
}
if (parent) {
QGraphicsItem *parentItem = parent->graphicsItem();
if (parentItem && parentItem->isWidget()) {
QGraphicsWidget *w = static_cast<QGraphicsWidget*>(parentItem);
s = w->style()->pixelMetric(orientation == Horizontal
? QStyle::PM_LayoutHorizontalSpacing
: QStyle::PM_LayoutVerticalSpacing);
}
}
}
return s;
}
/*!
\internal
Called on activation. Uses Linear Programming to define minimum, preferred
and maximum sizes for the layout. Also calculates the sizes that each item
should assume when the layout is in one of such situations.
*/
void QGraphicsAnchorLayoutPrivate::calculateGraphs()
{
if (!calculateGraphCacheDirty)
return;
//simplifyGraph(Horizontal);
//simplifyGraph(Vertical);
//Q_Q(QGraphicsAnchorLayout);
//q->dumpGraph();
//restoreSimplifiedGraph(Horizontal); // should not be here, but currently crashes if not
//restoreSimplifiedGraph(Vertical); // should not be here, but currently crashes if not
calculateGraphs(Horizontal);
calculateGraphs(Vertical);
calculateGraphCacheDirty = 0;
}
// ### remove me:
QList<AnchorData *> getVariables(QList<QSimplexConstraint *> constraints)
{
QSet<AnchorData *> variableSet;
for (int i = 0; i < constraints.count(); ++i) {
const QSimplexConstraint *c = constraints[i];
foreach (QSimplexVariable *var, c->variables.keys()) {
variableSet += static_cast<AnchorData *>(var);
}
}
return variableSet.toList();
}
/*!
\internal
Calculate graphs is the method that puts together all the helper routines
so that the AnchorLayout can calculate the sizes of each item.
In a nutshell it should do:
1) Update anchor nominal sizes, that is, the size that each anchor would
have if no other restrictions applied. This is done by quering the
layout style and the sizeHints of the items belonging to the layout.
2) Simplify the graph by grouping together parallel and sequential anchors
into "group anchors". These have equivalent minimum, preferred and maximum
sizeHints as the anchors they replace.
3) Check if we got to a trivial case. In some cases, the whole graph can be
simplified into a single anchor. If so, use this information. If not,
then call the Simplex solver to calculate the anchors sizes.
4) Once the root anchors had its sizes calculated, propagate that to the
anchors they represent.
*/
void QGraphicsAnchorLayoutPrivate::calculateGraphs(
QGraphicsAnchorLayoutPrivate::Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
// Reset the nominal sizes of each anchor based on the current item sizes
setAnchorSizeHintsFromItems(orientation);
// Reset the nominal sizes of each anchor based on the current item sizes
//setAnchorSizeHintsFromDefaults(orientation);
// Simplify the graph
// ### Ideally we would like to do that if, and only if, anchors had
// been added or removed since the last time this method was called.
// However, as the two setAnchorSizeHints methods above are not
// ready to be run on top of a simplified graph, we must simplify
// and restore it every time we get here.
//simplifyGraph(orientation);
// Traverse all graph edges and store the possible paths to each vertex
findPaths(orientation);
// From the paths calculated above, extract the constraints that the current
// anchor setup impose, to our Linear Programming problem.
constraintsFromPaths(orientation);
// Split the constraints and anchors into groups that should be fed to the
// simplex solver independently. Currently we find two groups:
//
// 1) The "trunk", that is, the set of anchors (items) that are connected
// to the two opposite sides of our layout, and thus need to stretch in
// order to fit in the current layout size.
//
// 2) The floating or semi-floating anchors (items) that are those which
// are connected to only one (or none) of the layout sides, thus are not
// influenced by the layout size.
QList<QList<QSimplexConstraint *> > parts;
parts = getGraphParts(orientation);
// Now run the simplex solver to calculate Minimum, Preferred and Maximum sizes
// of the "trunk" set of constraints and variables.
// ### does trunk always exist? empty = trunk is the layout left->center->right
QList<QSimplexConstraint *> trunkConstraints = parts[0];
QList<QSimplexConstraint *> sizeHintConstraints;
sizeHintConstraints = constraintsFromSizeHints(getVariables(trunkConstraints));
trunkConstraints += sizeHintConstraints;
// For minimum and maximum, use the path between the two layout sides as the
// objective function.
// Retrieve that path
AnchorVertex *v = internalVertex(q, pickEdge(QGraphicsAnchorLayout::Right, orientation));
GraphPath trunkPath = graphPaths[orientation].value(v);
if (!trunkConstraints.isEmpty()) {
// Solve min and max size hints for trunk
QPair<qreal, qreal> minMax = solveMinMax(trunkConstraints, trunkPath);
sizeHints[orientation][Qt::MinimumSize] = minMax.first;
sizeHints[orientation][Qt::MaximumSize] = minMax.second;
// Solve for preferred. The objective function is calculated from the constraints
// and variables internally.
solvePreferred(trunkConstraints);
// Calculate and set the preferred size for the layout from the edge sizes that
// were calculated above.
qreal pref(0.0);
foreach (const AnchorData *ad, trunkPath.positives) {
pref += ad->sizeAtPreferred;
}
foreach (const AnchorData *ad, trunkPath.negatives) {
pref -= ad->sizeAtPreferred;
}
sizeHints[orientation][Qt::PreferredSize] = pref;
} else {
// No Simplex is necessary because the path was simplified all the way to a single
// anchor.
Q_ASSERT(trunkPath.positives.count() == 1);
Q_ASSERT(trunkPath.negatives.count() == 0);
AnchorData *ad = trunkPath.positives.toList()[0];
ad->sizeAtMinimum = ad->minSize;
ad->sizeAtPreferred = ad->prefSize;
ad->sizeAtMaximum = ad->maxSize;
sizeHints[orientation][Qt::MinimumSize] = ad->sizeAtMinimum;
sizeHints[orientation][Qt::PreferredSize] = ad->sizeAtPreferred;
sizeHints[orientation][Qt::MaximumSize] = ad->sizeAtMaximum;
}
// Delete the constraints, we won't use them anymore.
qDeleteAll(sizeHintConstraints);
sizeHintConstraints.clear();
// For the other parts that not the trunk, solve only for the preferred size
// that is the size they will remain at, since they are not stretched by the
// layout.
// Solve the other only for preferred, skip trunk
for (int i = 1; i < parts.count(); ++i) {
QList<QSimplexConstraint *> partConstraints = parts[i];
QList<AnchorData *> partVariables = getVariables(partConstraints);
Q_ASSERT(!partVariables.isEmpty());
sizeHintConstraints = constraintsFromSizeHints(partVariables);
partConstraints += sizeHintConstraints;
solvePreferred(partConstraints);
// Propagate size at preferred to other sizes. Semi-floats
// always will be in their sizeAtPreferred.
for (int j = 0; j < partVariables.count(); ++j) {
AnchorData *ad = partVariables[j];
Q_ASSERT(ad);
ad->sizeAtMinimum = ad->sizeAtPreferred;
ad->sizeAtMaximum = ad->sizeAtPreferred;
}
// Delete the constraints, we won't use them anymore.
qDeleteAll(sizeHintConstraints);
sizeHintConstraints.clear();
}
// Clean up our data structures. They are not needed anymore since
// distribution uses just interpolation.
qDeleteAll(constraints[orientation]);
constraints[orientation].clear();
graphPaths[orientation].clear(); // ###
// Propagate the new sizes down the simplified graph, ie. tell the group anchors
// to set their children anchors sizes.
// ### Note that we can split the anchors into two categories:
// 1) Those that appeared in at least one constraint and so went through the
// Simplex solver. Either as a Trunk or Non-Trunk variable.
// 2) Those that did not go through the Simplex solver at all.
//
// Anchors of the type (1) had its effective sizes (ie. sizeAtMinimum/Pref/Max)
// properly set by the "solveMinMax" and "solvePreferred" methods.
//
// However, those of type (2), still need to have their effective sizes set,
// in that case, to their own nominal values.
//
// Due to the above reasons, we can't simply iterate on the variables that
// belong to a graph part. We have to iterate through _all_ root anchors
// in graph[orientation]. That's why we collect "allAnchors". We gotta make
// this better somehow.
// ### Did I say that's ugly?
QSet<AnchorData *> allAnchors;
QQueue<AnchorVertex *> queue;
queue << graph[orientation].rootVertex();
while (!queue.isEmpty()) {
AnchorVertex *vertex = queue.dequeue();
QList<AnchorVertex *> adjacentVertices = graph[orientation].adjacentVertices(vertex);
for (int i = 0; i < adjacentVertices.count(); ++i) {
AnchorData *edge = graph[orientation].edgeData(vertex, adjacentVertices[i]);
if (allAnchors.contains(edge))
continue;
allAnchors << edge;
queue << adjacentVertices[i];
}
}
// Ok, now that we have all anchors, actually propagate the sizes down its children.
// Note that for anchors that didn't have its effectiveSizes set yet, we use the
// nominal one instead.
QSet<AnchorData *>::const_iterator iter;
for (iter = allAnchors.constBegin(); iter != allAnchors.constEnd(); ++iter)
(*iter)->updateChildrenSizes();
// Restore the graph. See the ### note next to the simplifyGraph() call.
//restoreSimplifiedGraph(orientation);
}
void QGraphicsAnchorLayoutPrivate::setAnchorSizeHintsFromDefaults(Orientation orientation)
{
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
QSet<AnchorVertex *> setOfVertices = g.vertices();
for (QSet<AnchorVertex *>::const_iterator it = setOfVertices.begin(); it != setOfVertices.end(); ++it) {
AnchorVertex *v = *it;
QList<AnchorVertex *> adjacents = g.adjacentVertices(v);
for (int i = 0; i < adjacents.count(); ++i) {
AnchorVertex *v1 = adjacents.at(i);
AnchorData *data = g.edgeData(v, v1);
if (!data->hasSize) {
bool forward = data->origin == v;
if (forward) {
qreal s = effectiveSpacing(orientation);
data->minSize = s;
data->prefSize = s;
data->maxSize = s;
data->sizeAtMinimum = s;
data->sizeAtPreferred = s;
data->sizeAtMaximum = s;
}
}
}
}
}
/*!
\internal
For graph edges ("anchors") that represent items, this method updates their
intrinsic size restrictions, based on the item size hints.
################################################################################
### TODO: This method is not simplification ready. The fact that the graph may
have been simplified means that not all anchors exist in the graph.
This causes the Q_ASSERT(data) calls below to fail.
A possible approach is to use a recursive method that goes through
all edges in the graph updating their sizes based on their kind, i.e.:
- Anchors -> update their size based on the style defaults
- ItemAnchors -> update their size based on the item sizeHints
- SimplificationAnchors -> call "update()" on its children and then
calculate its own sizes
################################################################################
*/
void QGraphicsAnchorLayoutPrivate::setAnchorSizeHintsFromItems(Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
Graph<AnchorVertex, AnchorData> &g = graph[orientation];
QList<QPair<AnchorVertex*, AnchorVertex*> > conns = g.connections();
QGraphicsAnchorLayout::Edge centerEdge = pickEdge(QGraphicsAnchorLayout::HCenter, orientation);
QPair<QGraphicsLayoutItem *, QGraphicsAnchorLayout::Edge> beginningKey;
QPair<QGraphicsLayoutItem *, QGraphicsAnchorLayout::Edge> centerKey;
QPair<QGraphicsLayoutItem *, QGraphicsAnchorLayout::Edge> endKey;
if (orientation == Horizontal) {
beginningKey.second = QGraphicsAnchorLayout::Left;
centerKey.second = QGraphicsAnchorLayout::HCenter;
endKey.second = QGraphicsAnchorLayout::Right;
} else {
beginningKey.second = QGraphicsAnchorLayout::Top;
centerKey.second = QGraphicsAnchorLayout::VCenter;
endKey.second = QGraphicsAnchorLayout::Bottom;
}
for (int i = 0; i < conns.count(); ++i) {
AnchorVertex *from = conns.at(i).first;
AnchorVertex *to = conns.at(i).second;
QGraphicsLayoutItem *item = from->m_item;
qreal min, pref, max;
AnchorData *data = g.edgeData(from, to);
Q_ASSERT(data);
// Internal item anchor
if (item != q && item == to->m_item) {
// internal item anchor: get size from sizeHint
if (orientation == Horizontal) {
min = item->minimumWidth();
pref = item->preferredWidth();
max = item->maximumWidth();
} else {
min = item->minimumHeight();
pref = item->preferredHeight();
max = item->maximumHeight();
}
if (from->m_edge == centerEdge || to->m_edge == centerEdge) {
min /= 2;
pref /= 2;
max /= 2;
}
// Set the anchor nominal sizes to those of the corresponding item
data->minSize = min;
data->prefSize = pref;
data->maxSize = max;
// Set the anchor effective sizes to preferred.
// Note: The idea here is that all items should remain at
// their preferred size unless where that's impossible.
// In cases where the item is subject to restrictions
// (anchored to the layout edges, for instance), the
// simplex solver will be run to recalculate and override
// the values we set here.
data->sizeAtMinimum = pref;
data->sizeAtPreferred = pref;
data->sizeAtMaximum = pref;
} else if (data->type != AnchorData::Normal) {
data->refreshSizeHints();
} else {
// anchors between items, their sizes may depend on the style.
if (!data->hasSize) {
qreal s = effectiveSpacing(orientation);
data->minSize = s;
data->prefSize = s;
data->maxSize = s;
data->sizeAtMinimum = s;
data->sizeAtPreferred = s;
data->sizeAtMaximum = s;
}
}
}
}
/*!
\internal
This method walks the graph using a breadth-first search to find paths
between the root vertex and each vertex on the graph. The edges
directions in each path are considered and they are stored as a
positive edge (left-to-right) or negative edge (right-to-left).
The list of paths is used later to generate a list of constraints.
*/
void QGraphicsAnchorLayoutPrivate::findPaths(Orientation orientation)
{
QQueue<QPair<AnchorVertex *, AnchorVertex *> > queue;
QSet<AnchorData *> visited;
AnchorVertex *root = graph[orientation].rootVertex();
graphPaths[orientation].insert(root, GraphPath());
foreach (AnchorVertex *v, graph[orientation].adjacentVertices(root)) {
queue.enqueue(qMakePair(root, v));
}
while(!queue.isEmpty()) {
QPair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
if (visited.contains(edge))
continue;
visited.insert(edge);
GraphPath current = graphPaths[orientation].value(pair.first);
if (edge->origin == pair.first)
current.positives.insert(edge);
else
current.negatives.insert(edge);
graphPaths[orientation].insert(pair.second, current);
foreach (AnchorVertex *v,
graph[orientation].adjacentVertices(pair.second)) {
queue.enqueue(qMakePair(pair.second, v));
}
}
}
/*!
\internal
Each vertex on the graph that has more than one path to it
represents a contra int to the sizes of the items in these paths.
This method walks the list of paths to each vertex, generate
the constraints and store them in a list so they can be used later
by the Simplex solver.
*/
void QGraphicsAnchorLayoutPrivate::constraintsFromPaths(Orientation orientation)
{
foreach (AnchorVertex *vertex, graphPaths[orientation].uniqueKeys())
{
int valueCount = graphPaths[orientation].count(vertex);
if (valueCount == 1)
continue;
QList<GraphPath> pathsToVertex = graphPaths[orientation].values(vertex);
for (int i = 1; i < valueCount; ++i) {
constraints[orientation] += \
pathsToVertex[0].constraint(pathsToVertex[i]);
}
}
}
/*!
\internal
Create LP constraints for each anchor based on its minimum and maximum
sizes, as specified in its size hints
*/
QList<QSimplexConstraint *> QGraphicsAnchorLayoutPrivate::constraintsFromSizeHints(
const QList<AnchorData *> &anchors)
{
QList<QSimplexConstraint *> anchorConstraints;
for (int i = 0; i < anchors.size(); ++i) {
QSimplexConstraint *c = new QSimplexConstraint;
c->variables.insert(anchors[i], 1.0);
c->constant = anchors[i]->minSize;
c->ratio = QSimplexConstraint::MoreOrEqual;
anchorConstraints += c;
c = new QSimplexConstraint;
c->variables.insert(anchors[i], 1.0);
c->constant = anchors[i]->maxSize;
c->ratio = QSimplexConstraint::LessOrEqual;
anchorConstraints += c;
}
return anchorConstraints;
}
/*!
\Internal
*/
QList< QList<QSimplexConstraint *> >
QGraphicsAnchorLayoutPrivate::getGraphParts(Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
// Find layout vertices and edges for the current orientation.
AnchorVertex *layoutFirstVertex = \
internalVertex(q, pickEdge(QGraphicsAnchorLayout::Left, orientation));
AnchorVertex *layoutCentralVertex = \
internalVertex(q, pickEdge(QGraphicsAnchorLayout::HCenter, orientation));
AnchorVertex *layoutLastVertex = \
internalVertex(q, pickEdge(QGraphicsAnchorLayout::Right, orientation));
Q_ASSERT(layoutFirstVertex && layoutLastVertex);
AnchorData *edgeL1 = NULL;
AnchorData *edgeL2 = NULL;
// The layout may have a single anchor between Left and Right or two half anchors
// passing through the center
if (layoutCentralVertex) {
edgeL1 = graph[orientation].edgeData(layoutFirstVertex, layoutCentralVertex);
edgeL2 = graph[orientation].edgeData(layoutCentralVertex, layoutLastVertex);
} else {
edgeL1 = graph[orientation].edgeData(layoutFirstVertex, layoutLastVertex);
}
QLinkedList<QSimplexConstraint *> remainingConstraints;
for (int i = 0; i < constraints[orientation].count(); ++i) {
remainingConstraints += constraints[orientation][i];
}
for (int i = 0; i < itemCenterConstraints[orientation].count(); ++i) {
remainingConstraints += itemCenterConstraints[orientation][i];
}
QList<QSimplexConstraint *> trunkConstraints;
QSet<QSimplexVariable *> trunkVariables;
trunkVariables += edgeL1;
if (edgeL2)
trunkVariables += edgeL2;
bool dirty;
do {
dirty = false;
QLinkedList<QSimplexConstraint *>::iterator it = remainingConstraints.begin();
while (it != remainingConstraints.end()) {
QSimplexConstraint *c = *it;
bool match = false;
// Check if this constraint have some overlap with current
// trunk variables...
foreach (QSimplexVariable *ad, trunkVariables) {
if (c->variables.contains(ad)) {
match = true;
break;
}
}
// If so, we add it to trunk, and erase it from the
// remaining constraints.
if (match) {
trunkConstraints += c;
trunkVariables += QSet<QSimplexVariable *>::fromList(c->variables.keys());
it = remainingConstraints.erase(it);
dirty = true;
} else {
// Note that we don't erase the constraint if it's not
// a match, since in a next iteration of a do-while we
// can pass on it again and it will be a match.
//
// For example: if trunk share a variable with
// remainingConstraints[1] and it shares with
// remainingConstraints[0], we need a second iteration
// of the do-while loop to match both.
++it;
}
}
} while (dirty);
QList< QList<QSimplexConstraint *> > result;
result += trunkConstraints;
if (!remainingConstraints.isEmpty()) {
QList<QSimplexConstraint *> nonTrunkConstraints;
QLinkedList<QSimplexConstraint *>::iterator it = remainingConstraints.begin();
while (it != remainingConstraints.end()) {
nonTrunkConstraints += *it;
++it;
}
result += nonTrunkConstraints;
}
return result;
}
/*!
\internal
Use the current vertices distance to calculate and set the geometry of
each item.
*/
void QGraphicsAnchorLayoutPrivate::setItemsGeometries()
{
AnchorVertex *firstH, *secondH, *firstV, *secondV;
foreach (QGraphicsLayoutItem *item, items) {
firstH = internalVertex(item, QGraphicsAnchorLayout::Left);
secondH = internalVertex(item, QGraphicsAnchorLayout::Right);
firstV = internalVertex(item, QGraphicsAnchorLayout::Top);
secondV = internalVertex(item, QGraphicsAnchorLayout::Bottom);
QPointF topLeft(firstH->distance, firstV->distance);
QPointF bottomRight(secondH->distance, secondV->distance);
item->setGeometry(QRectF(topLeft, bottomRight));
}
}
/*!
\internal
Calculate the position of each vertex based on the paths to each of
them as well as the current edges sizes.
*/
void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(
QGraphicsAnchorLayoutPrivate::Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
QQueue<QPair<AnchorVertex *, AnchorVertex *> > queue;
QSet<AnchorVertex *> visited;
// Get root vertex
AnchorVertex *root = graph[orientation].rootVertex();
qreal widgetMargin;
qreal layoutMargin;
// Initialize the first vertex
if (orientation == Horizontal) {
widgetMargin = q->geometry().x();
q->getContentsMargins(&layoutMargin, 0, 0, 0);
} else {
// Root position is equal to the top margin
widgetMargin = q->geometry().y();
q->getContentsMargins(0, &layoutMargin, 0, 0);
}
root->distance = widgetMargin + layoutMargin;
visited.insert(root);
// Add initial edges to the queue
foreach (AnchorVertex *v, graph[orientation].adjacentVertices(root)) {
queue.enqueue(qMakePair(root, v));
}
// Do initial calculation required by "interpolateEdge()"
setupEdgesInterpolation(orientation);
// Traverse the graph and calculate vertex positions.
while (!queue.isEmpty()) {
QPair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
if (visited.contains(pair.second))
continue;
visited.insert(pair.second);
// The distance to the next vertex is equal the distance to the
// previous one plus (or less) the size of the edge between them.
qreal distance;
AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
if (edge->origin == pair.first) {
distance = pair.first->distance + interpolateEdge(edge);
} else {
distance = pair.first->distance - interpolateEdge(edge);
}
pair.second->distance = distance;
foreach (AnchorVertex *v,
graph[orientation].adjacentVertices(pair.second)) {
queue.enqueue(qMakePair(pair.second, v));
}
}
}
/*!
\internal
Calculate interpolation parameters based on current Layout Size.
Must once before calling "interpolateEdgeSize()" for each edge.
*/
void QGraphicsAnchorLayoutPrivate::setupEdgesInterpolation(
Orientation orientation)
{
Q_Q(QGraphicsAnchorLayout);
qreal lower, upper, current;
if (orientation == Horizontal) {
current = q->contentsRect().width();
} else {
current = q->contentsRect().height();
}
if (current < sizeHints[orientation][Qt::PreferredSize]) {
interpolationInterval[orientation] = MinToPreferred;
lower = sizeHints[orientation][Qt::MinimumSize];
upper = sizeHints[orientation][Qt::PreferredSize];
} else {
interpolationInterval[orientation] = PreferredToMax;
lower = sizeHints[orientation][Qt::PreferredSize];
upper = sizeHints[orientation][Qt::MaximumSize];
}
if (upper == lower) {
interpolationProgress[orientation] = 0;
} else {
interpolationProgress[orientation] = (current - lower) / (upper - lower);
}
}
/*!
\internal
Calculate the current Edge size based on the current Layout size and the
size the edge is supposed to have when:
- the layout is at its minimum size.
- the layout is at its preferred size.
- the layout is at its maximum size.
These three key values are calculated in advance using linear programming
(more expensive), then subsequential resizes of the parent layout require
a simple interpolation.
*/
qreal QGraphicsAnchorLayoutPrivate::interpolateEdge(AnchorData *edge)
{
qreal lower, upper;
Orientation orientation = edgeOrientation(edge->origin->m_edge);
if (interpolationInterval[orientation] == MinToPreferred) {
lower = edge->sizeAtMinimum;
upper = edge->sizeAtPreferred;
} else {
lower = edge->sizeAtPreferred;
upper = edge->sizeAtMaximum;
}
return (interpolationProgress[orientation] * (upper - lower)) + lower;
}
QPair<qreal, qreal>
QGraphicsAnchorLayoutPrivate::solveMinMax(QList<QSimplexConstraint *> constraints,
GraphPath path)
{
QSimplex simplex;
simplex.setConstraints(constraints);
// Obtain the objective constraint
QSimplexConstraint objective;
QSet<AnchorData *>::const_iterator iter;
for (iter = path.positives.constBegin(); iter != path.positives.constEnd(); ++iter)
objective.variables.insert(*iter, 1.0);
for (iter = path.negatives.constBegin(); iter != path.negatives.constEnd(); ++iter)
objective.variables.insert(*iter, -1.0);
simplex.setObjective(&objective);
// Calculate minimum values
qreal min = simplex.solveMin();
// Save sizeAtMinimum results
QList<QSimplexVariable *> variables = simplex.constraintsVariables();
for (int i = 0; i < variables.size(); ++i) {
AnchorData *ad = static_cast<AnchorData *>(variables[i]);
ad->sizeAtMinimum = ad->result;
}
// Calculate maximum values
qreal max = simplex.solveMax();
// Save sizeAtMaximum results
for (int i = 0; i < variables.size(); ++i) {
AnchorData *ad = static_cast<AnchorData *>(variables[i]);
ad->sizeAtMaximum = ad->result;
}
return qMakePair<qreal, qreal>(min, max);
}
void QGraphicsAnchorLayoutPrivate::solvePreferred(QList<QSimplexConstraint *> constraints)
{
QList<AnchorData *> variables = getVariables(constraints);
QList<QSimplexConstraint *> preferredConstraints;
QList<QSimplexVariable *> preferredVariables;
QSimplexConstraint objective;
// Fill the objective coefficients for this variable. In the
// end the objective function will be
//
// z = n * (A_shrink + B_shrink + ...) + (A_grower + B_grower + ...)
//
// where n is the number of variables that have
// slacks. Note that here we use the number of variables
// as coefficient, this is to mark the "shrinker slack
// variable" less likely to get value than the "grower
// slack variable".
// This will fill the values for the structural constraints
// and we now fill the values for the slack constraints (one per variable),
// which have this form (the constant A_pref was set when creating the slacks):
//
// A + A_shrinker - A_grower = A_pref
//
for (int i = 0; i < variables.size(); ++i) {
AnchorData *ad = static_cast<AnchorData *>(variables[i]);
if (ad->skipInPreferred)
continue;
QSimplexVariable *grower = new QSimplexVariable;
QSimplexVariable *shrinker = new QSimplexVariable;
QSimplexConstraint *c = new QSimplexConstraint;
c->variables.insert(ad, 1.0);
c->variables.insert(shrinker, 1.0);
c->variables.insert(grower, -1.0);
c->constant = ad->prefSize;
preferredConstraints += c;
preferredVariables += grower;
preferredVariables += shrinker;
objective.variables.insert(grower, 1.0);
objective.variables.insert(shrinker, variables.size());
}
QSimplex *simplex = new QSimplex;
simplex->setConstraints(constraints + preferredConstraints);
simplex->setObjective(&objective);
// Calculate minimum values
simplex->solveMin();
// Save sizeAtPreferred results
for (int i = 0; i < variables.size(); ++i) {
AnchorData *ad = static_cast<AnchorData *>(variables[i]);
ad->sizeAtPreferred = ad->result;
}
// Make sure we delete the simplex solver -before- we delete the
// constraints used by it.
delete simplex;
// Delete constraints and variables we created.
qDeleteAll(preferredConstraints);
qDeleteAll(preferredVariables);
}
|