summaryrefslogtreecommitdiffstats
path: root/examples/tutorials/widgets/nestedlayouts/main.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'examples/tutorials/widgets/nestedlayouts/main.cpp')
0 files changed, 0 insertions, 0 deletions
href='#n58'>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 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qgraphicsanchorlayout_p.h"

#include <QtWidgets/qwidget.h>
#include <QtWidgets/qapplication.h>
#include <QtCore/qstack.h>

#ifdef QT_DEBUG
#include <QtCore/qfile.h>
#endif

#include <numeric>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

// To ensure that all variables inside the simplex solver are non-negative,
// we limit the size of anchors in the interval [-limit, limit]. Then before
// sending them to the simplex solver we add "limit" as an offset, so that
// they are actually calculated in the interval [0, 2 * limit]
// To avoid numerical errors in platforms where we use single precision,
// we use a tighter limit for the variables range.
const qreal g_offset = (sizeof(qreal) == sizeof(double)) ? QWIDGETSIZE_MAX : QWIDGETSIZE_MAX / 32;

QGraphicsAnchorPrivate::QGraphicsAnchorPrivate(decltype(QObjectPrivateVersion) version)
    : QObjectPrivate(version), layoutPrivate(nullptr), data(nullptr),
      sizePolicy(QSizePolicy::Fixed), preferredSize(0),
      hasSize(true)
{
}

QGraphicsAnchorPrivate::~QGraphicsAnchorPrivate()
{
    if (data) {
        // The QGraphicsAnchor was already deleted at this moment. We must clean
        // the dangling pointer to avoid double deletion in the AnchorData dtor.
        data->graphicsAnchor = nullptr;

        layoutPrivate->removeAnchor(data->from, data->to);
    }
}

void QGraphicsAnchorPrivate::setSizePolicy(QSizePolicy::Policy policy)
{
    if (sizePolicy != policy) {
        sizePolicy = policy;
        layoutPrivate->q_func()->invalidate();
    }
}

void QGraphicsAnchorPrivate::setSpacing(qreal value)
{
    if (!data) {
        qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
        return;
    }

    if (hasSize && (preferredSize == value))
        return;

    // The anchor has an user-defined size
    hasSize = true;
    preferredSize = value;

    layoutPrivate->q_func()->invalidate();
}

void QGraphicsAnchorPrivate::unsetSpacing()
{
    if (!data) {
        qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
        return;
    }

    // Return to standard direction
    hasSize = false;

    layoutPrivate->q_func()->invalidate();
}

qreal QGraphicsAnchorPrivate::spacing() const
{
    if (!data) {
        qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
        return 0;
    }

    return preferredSize;
}


static void applySizePolicy(QSizePolicy::Policy policy,
                            qreal minSizeHint, qreal prefSizeHint, qreal maxSizeHint,
                            qreal *minSize, qreal *prefSize,
                            qreal *maxSize)
{
    // minSize, prefSize and maxSize are initialized
    // with item's preferred Size: this is QSizePolicy::Fixed.
    //
    // Then we check each flag to find the resultant QSizePolicy,
    // according to the following table:
    //
    //      constant               value
    // QSizePolicy::Fixed            0
    // QSizePolicy::Minimum       GrowFlag
    // QSizePolicy::Maximum       ShrinkFlag
    // QSizePolicy::Preferred     GrowFlag | ShrinkFlag
    // QSizePolicy::Ignored       GrowFlag | ShrinkFlag | IgnoreFlag

    if (policy & QSizePolicy::ShrinkFlag)
        *minSize = minSizeHint;
    else
        *minSize = prefSizeHint;

    if (policy & QSizePolicy::GrowFlag)
        *maxSize = maxSizeHint;
    else
        *maxSize = prefSizeHint;

    // Note that these two initializations are affected by the previous flags
    if (policy & QSizePolicy::IgnoreFlag)
        *prefSize = *minSize;
    else
        *prefSize = prefSizeHint;
}

AnchorData::~AnchorData()
{
    if (graphicsAnchor) {
        // Remove reference to ourself to avoid double removal in
        // QGraphicsAnchorPrivate dtor.
        QGraphicsAnchorPrivate::get(graphicsAnchor)->data = nullptr;

        delete graphicsAnchor;
    }
}


void AnchorData::refreshSizeHints(const QLayoutStyleInfo *styleInfo)
{
    QSizePolicy::Policy policy;
    qreal minSizeHint;
    qreal prefSizeHint;
    qreal maxSizeHint;

    if (item) {
        // It is an internal anchor, fetch size information from the item
        if (isLayoutAnchor) {
            minSize = 0;
            prefSize = 0;
            maxSize = QWIDGETSIZE_MAX;
            if (isCenterAnchor)
                maxSize /= 2;

            minPrefSize = prefSize;
            maxPrefSize = maxSize;
            return;
        } else {
            if (!isVertical) {
                policy = item->sizePolicy().horizontalPolicy();
                minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).width();
                prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).width();
                maxSizeHint = item->effectiveSizeHint(Qt::MaximumSize).width();
            } else {
                policy = item->sizePolicy().verticalPolicy();
                minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).height();
                prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).height();
                maxSizeHint = item->effectiveSizeHint(Qt::MaximumSize).height();
            }

            if (isCenterAnchor) {
                minSizeHint /= 2;
                prefSizeHint /= 2;
                maxSizeHint /= 2;
            }
        }
    } else {
        // It is a user-created anchor, fetch size information from the associated QGraphicsAnchor
        Q_ASSERT(graphicsAnchor);
        QGraphicsAnchorPrivate *anchorPrivate = QGraphicsAnchorPrivate::get(graphicsAnchor);

        // Policy, min and max sizes are straightforward
        policy = anchorPrivate->sizePolicy;
        minSizeHint = 0;
        maxSizeHint = QWIDGETSIZE_MAX;

        // Preferred Size
        if (anchorPrivate->hasSize) {
            // Anchor has user-defined size
            prefSizeHint = anchorPrivate->preferredSize;
        } else if (styleInfo) {
            // Fetch size information from style
            const Qt::Orientation orient = QGraphicsAnchorLayoutPrivate::edgeOrientation(from->m_edge);
            qreal s = styleInfo->defaultSpacing(orient);
            if (s < 0) {
                QSizePolicy::ControlType controlTypeFrom = from->m_item->sizePolicy().controlType();
                QSizePolicy::ControlType controlTypeTo = to->m_item->sizePolicy().controlType();
                s = styleInfo->perItemSpacing(controlTypeFrom, controlTypeTo, orient);

                // ### Currently we do not support negative anchors inside the graph.
                // To avoid those being created by a negative style spacing, we must
                // make this test.
                if (s < 0)
                    s = 0;
            }
            prefSizeHint = s;
        } else {
            prefSizeHint = 0;
        }
    }

    // Fill minSize, prefSize and maxSize based on policy and sizeHints
    applySizePolicy(policy, minSizeHint, prefSizeHint, maxSizeHint,
                    &minSize, &prefSize, &maxSize);

    minPrefSize = prefSize;
    maxPrefSize = maxSize;

    // 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.
    sizeAtMinimum = prefSize;
    sizeAtPreferred = prefSize;
    sizeAtMaximum = prefSize;
}

void ParallelAnchorData::updateChildrenSizes()
{
    firstEdge->sizeAtMinimum = sizeAtMinimum;
    firstEdge->sizeAtPreferred = sizeAtPreferred;
    firstEdge->sizeAtMaximum = sizeAtMaximum;

    if (secondForward()) {
        secondEdge->sizeAtMinimum = sizeAtMinimum;
        secondEdge->sizeAtPreferred = sizeAtPreferred;
        secondEdge->sizeAtMaximum = sizeAtMaximum;
    } else {
        secondEdge->sizeAtMinimum = -sizeAtMinimum;
        secondEdge->sizeAtPreferred = -sizeAtPreferred;
        secondEdge->sizeAtMaximum = -sizeAtMaximum;
    }

    firstEdge->updateChildrenSizes();
    secondEdge->updateChildrenSizes();
}

/*
  \internal

  Initialize the parallel anchor size hints using the sizeHint information from
  its children.

  Note that parallel groups can lead to unfeasibility, so during calculation, we can
  find out one unfeasibility. Because of that this method return boolean. This can't
  happen in sequential, so there the method is void.
 */
bool ParallelAnchorData::calculateSizeHints()
{
    // Normalize second child sizes.
    // A negative anchor of sizes min, minPref, pref, maxPref and max, is equivalent
    // to a forward anchor of sizes -max, -maxPref, -pref, -minPref, -min
    qreal secondMin;
    qreal secondMinPref;
    qreal secondPref;
    qreal secondMaxPref;
    qreal secondMax;

    if (secondForward()) {
        secondMin = secondEdge->minSize;
        secondMinPref = secondEdge->minPrefSize;
        secondPref = secondEdge->prefSize;
        secondMaxPref = secondEdge->maxPrefSize;
        secondMax = secondEdge->maxSize;
    } else {
        secondMin = -secondEdge->maxSize;
        secondMinPref = -secondEdge->maxPrefSize;
        secondPref = -secondEdge->prefSize;
        secondMaxPref = -secondEdge->minPrefSize;
        secondMax = -secondEdge->minSize;
    }

    minSize = qMax(firstEdge->minSize, secondMin);
    maxSize = qMin(firstEdge->maxSize, secondMax);

    // This condition means that the maximum size of one anchor being simplified is smaller than
    // the minimum size of the other anchor. The consequence is that there won't be a valid size
    // for this parallel setup.
    if (minSize > maxSize) {
        return false;
    }

    // Preferred size calculation
    // The calculation of preferred size is done as follows:
    //
    // 1) Check whether one of the child anchors is the layout structural anchor
    //    If so, we can simply copy the preferred information from the other child,
    //    after bounding it to our minimum and maximum sizes.
    //    If not, then we proceed with the actual calculations.
    //
    // 2) The whole algorithm for preferred size calculation is based on the fact
    //    that, if a given anchor cannot remain at its preferred size, it'd rather
    //    grow than shrink.
    //
    //    What happens though is that while this affirmative is true for simple
    //    anchors, it may not be true for sequential anchors that have one or more
    //    reversed anchors inside it. That happens because when a sequential anchor
    //    grows, any reversed anchors inside it may be required to shrink, something
    //    we try to avoid, as said above.
    //
    //    To overcome this, besides their actual preferred size "prefSize", each anchor
    //    exports what we call "minPrefSize" and "maxPrefSize". These two values define
    //    a surrounding interval where, if required to move, the anchor would rather
    //    remain inside.
    //
    //    For standard anchors, this area simply represents the region between
    //    prefSize and maxSize, which makes sense since our first affirmation.
    //    For composed anchors, these values are calculated as to reduce the global
    //    "damage", that is, to reduce the total deviation and the total amount of
    //    anchors that had to shrink.

    if (firstEdge->isLayoutAnchor) {
        prefSize = qBound(minSize, secondPref, maxSize);
        minPrefSize = qBound(minSize, secondMinPref, maxSize);
        maxPrefSize = qBound(minSize, secondMaxPref, maxSize);
    } else if (secondEdge->isLayoutAnchor) {
        prefSize = qBound(minSize, firstEdge->prefSize, maxSize);
        minPrefSize = qBound(minSize, firstEdge->minPrefSize, maxSize);
        maxPrefSize = qBound(minSize, firstEdge->maxPrefSize, maxSize);
    } else {
        // Calculate the intersection between the "preferred" regions of each child
        const qreal lowerBoundary =
            qBound(minSize, qMax(firstEdge->minPrefSize, secondMinPref), maxSize);
        const qreal upperBoundary =
            qBound(minSize, qMin(firstEdge->maxPrefSize, secondMaxPref), maxSize);
        const qreal prefMean =
            qBound(minSize, (firstEdge->prefSize + secondPref) / 2, maxSize);

        if (lowerBoundary < upperBoundary) {
            // If there is an intersection between the two regions, this intersection
            // will be used as the preferred region of the parallel anchor itself.
            // The preferred size will be the bounded average between the two preferred
            // sizes.
            prefSize = qBound(lowerBoundary, prefMean, upperBoundary);
            minPrefSize = lowerBoundary;
            maxPrefSize = upperBoundary;
        } else {
            // If there is no intersection, we have to attribute "damage" to at least
            // one of the children. The minimum total damage is achieved in points
            // inside the region that extends from (1) the upper boundary of the lower
            // region to (2) the lower boundary of the upper region.
            // Then, we expose this region as _our_ preferred region and once again,
            // use the bounded average as our preferred size.
            prefSize = qBound(upperBoundary, prefMean, lowerBoundary);
            minPrefSize = upperBoundary;
            maxPrefSize = lowerBoundary;
        }
    }

    // See comment in AnchorData::refreshSizeHints() about sizeAt* values
    sizeAtMinimum = prefSize;
    sizeAtPreferred = prefSize;
    sizeAtMaximum = prefSize;

    return true;
}

/*!
    \internal
    returns the factor in the interval [-1, 1].
    -1 is at Minimum
     0 is at Preferred
     1 is at Maximum
*/
static std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> getFactor(qreal value, qreal min,
                                                                          qreal minPref, qreal pref,
                                                                          qreal maxPref, qreal max)
{
    QGraphicsAnchorLayoutPrivate::Interval interval;
    qreal lower;
    qreal upper;

    if (value < minPref) {
        interval = QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred;
        lower = min;
        upper = minPref;
    } else if (value < pref) {
        interval = QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred;
        lower = minPref;
        upper = pref;
    } else if (value < maxPref) {
        interval = QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred;
        lower = pref;
        upper = maxPref;
    } else {
        interval = QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum;
        lower = maxPref;
        upper = max;
    }

    qreal progress;
    if (upper == lower) {
        progress = 0;
    } else {
        progress = (value - lower) / (upper - lower);
    }

    return std::pair(interval, progress);
}

static qreal interpolate(const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> &factor,
                         qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
{
    qreal lower = 0;
    qreal upper = 0;

    switch (factor.first) {
    case QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred:
        lower = min;
        upper = minPref;
        break;
    case QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred:
        lower = minPref;
        upper = pref;
        break;
    case QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred:
        lower = pref;
        upper = maxPref;
        break;
    case QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum:
        lower = maxPref;
        upper = max;
        break;
    }

    return lower + factor.second * (upper - lower);
}

void SequentialAnchorData::updateChildrenSizes()
{
    // Band here refers if the value is in the Minimum To Preferred
    // band (the lower band) or the Preferred To Maximum (the upper band).

    const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> minFactor =
        getFactor(sizeAtMinimum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
    const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> prefFactor =
        getFactor(sizeAtPreferred, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
    const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> maxFactor =
        getFactor(sizeAtMaximum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);

    // XXX This is not safe if Vertex simplification takes place after the sequential
    // anchor is created. In that case, "prev" will be a group-vertex, different from
    // "from" or "to", that _contains_ one of them.
    AnchorVertex *prev = from;

    for (AnchorData *e : m_edges) {
        const bool edgeIsForward = (e->from == prev);
        if (edgeIsForward) {
            e->sizeAtMinimum = interpolate(minFactor, e->minSize, e->minPrefSize,
                                           e->prefSize, e->maxPrefSize, e->maxSize);
            e->sizeAtPreferred = interpolate(prefFactor, e->minSize, e->minPrefSize,
                                           e->prefSize, e->maxPrefSize, e->maxSize);
            e->sizeAtMaximum = interpolate(maxFactor, e->minSize, e->minPrefSize,
                                           e->prefSize, e->maxPrefSize, e->maxSize);
            prev = e->to;
        } else {
            Q_ASSERT(prev == e->to);
            e->sizeAtMinimum = interpolate(minFactor, e->maxSize, e->maxPrefSize,
                                           e->prefSize, e->minPrefSize, e->minSize);
            e->sizeAtPreferred = interpolate(prefFactor, e->maxSize, e->maxPrefSize,
                                           e->prefSize, e->minPrefSize, e->minSize);
            e->sizeAtMaximum = interpolate(maxFactor, e->maxSize, e->maxPrefSize,
                                           e->prefSize, e->minPrefSize, e->minSize);
            prev = e->from;
        }

        e->updateChildrenSizes();
    }
}

void SequentialAnchorData::calculateSizeHints()
{
    minSize = 0;
    prefSize = 0;
    maxSize = 0;
    minPrefSize = 0;
    maxPrefSize = 0;

    AnchorVertex *prev = from;

    for (AnchorData *edge : m_edges) {
        const bool edgeIsForward = (edge->from == prev);
        if (edgeIsForward) {
            minSize += edge->minSize;
            prefSize += edge->prefSize;
            maxSize += edge->maxSize;
            minPrefSize += edge->minPrefSize;
            maxPrefSize += edge->maxPrefSize;
            prev = edge->to;
        } else {
            Q_ASSERT(prev == edge->to);
            minSize -= edge->maxSize;
            prefSize -= edge->prefSize;
            maxSize -= edge->minSize;
            minPrefSize -= edge->maxPrefSize;
            maxPrefSize -= edge->minPrefSize;
            prev = edge->from;
        }
    }

    // See comment in AnchorData::refreshSizeHints() about sizeAt* values
    sizeAtMinimum = prefSize;
    sizeAtPreferred = prefSize;
    sizeAtMaximum = prefSize;
}

#ifdef QT_DEBUG
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) {
        const auto *s = static_cast<SequentialAnchorData *>(this);
        qDebug("%*s type: sequential(%lld):", indent, "", qint64(s->m_edges.size()));
        for (AnchorData *e : s->m_edges)
            e->dump(indent + 2);
    } else {
        qDebug("%*s type: Normal:", indent, "");
    }
}

#endif

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;
}

#ifdef QT_DEBUG
QString GraphPath::toString() const
{
    QString string;
    string += "Path: "_L1;

    for (AnchorData *edge : positives)
        string += QString::fromLatin1(" (+++) %1").arg(edge->toString());

    for (AnchorData *edge : negatives)
        string += QString::fromLatin1(" (---) %1").arg(edge->toString());

    return string;
}
#endif

QGraphicsAnchorLayoutPrivate::QGraphicsAnchorLayoutPrivate()
    : calculateGraphCacheDirty(true), styleInfoDirty(true)
{
}

Qt::AnchorPoint QGraphicsAnchorLayoutPrivate::oppositeEdge(Qt::AnchorPoint edge)
{
    switch (edge) {
    case Qt::AnchorLeft:
        edge = Qt::AnchorRight;
        break;
    case Qt::AnchorRight:
        edge = Qt::AnchorLeft;
        break;
    case Qt::AnchorTop:
        edge = Qt::AnchorBottom;
        break;
    case Qt::AnchorBottom:
        edge = Qt::AnchorTop;
        break;
    default:
        break;
    }
    return edge;
}


/*!
    \internal

    Adds \a newAnchor to the graph.

    Returns the newAnchor itself if it could be added without further changes to the graph. If a
    new parallel anchor had to be created, then returns the new parallel anchor. If a parallel anchor
    had to be created and it results in an unfeasible setup, \a feasible is set to false, otherwise
    true.

    Note that in the case a new parallel anchor is created, it might also take over some constraints
    from its children anchors.
*/
AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *newAnchor, bool *feasible)
{
    const Qt::Orientation orientation = newAnchor->isVertical ? Qt::Vertical : Qt::Horizontal;
    Graph<AnchorVertex, AnchorData> &g = graph[orientation];
    *feasible = true;

    // If already exists one anchor where newAnchor is supposed to be, we create a parallel
    // anchor.
    if (AnchorData *oldAnchor = g.takeEdge(newAnchor->from, newAnchor->to)) {
        ParallelAnchorData *parallel = new ParallelAnchorData(oldAnchor, newAnchor);

        // The parallel anchor will "replace" its children anchors in
        // every center constraint that they appear.

        // ### If the dependent (center) anchors had reference(s) to their constraints, we
        // could avoid traversing all the itemCenterConstraints.
        QList<QSimplexConstraint *> &constraints = itemCenterConstraints[orientation];

        AnchorData *children[2] = { oldAnchor, newAnchor };
        QList<QSimplexConstraint *> *childrenConstraints[2] = { &parallel->m_firstConstraints,
                                                                &parallel->m_secondConstraints };

        for (int i = 0; i < 2; ++i) {
            AnchorData *child = children[i];
            QList<QSimplexConstraint *> *childConstraints = childrenConstraints[i];

            // We need to fix the second child constraints if the parallel group will have the
            // opposite direction of the second child anchor. For the point of view of external
            // entities, this anchor was reversed. So if at some point we say that the parallel
            // has a value of 20, this mean that the second child (when reversed) will be
            // assigned -20.
            const bool needsReverse = i == 1 && !parallel->secondForward();

            if (!child->isCenterAnchor)
                continue;

            parallel->isCenterAnchor = true;

            for (int j = 0; j < constraints.size(); ++j) {
                QSimplexConstraint *c = constraints[j];
                if (c->variables.contains(child)) {
                    childConstraints->append(c);
                    qreal v = c->variables.take(child);
                    if (needsReverse)
                        v *= -1;
                    c->variables.insert(parallel, v);
                }
            }
        }

        // At this point we can identify that the parallel anchor is not feasible, e.g. one
        // anchor minimum size is bigger than the other anchor maximum size.
        *feasible = parallel->calculateSizeHints();
        newAnchor = parallel;
    }

    g.createEdge(newAnchor->from, newAnchor->to, newAnchor);
    return newAnchor;
}

/*!
    \internal

    Takes the sequence of vertices described by (\a before, \a vertices, \a after) and removes
    all anchors connected to the vertices in \a vertices, returning one simplified anchor between
    \a before and \a after.

    Note that this function doesn't add the created anchor to the graph. This should be done by
    the caller.
*/
static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph, AnchorVertex *before,
                                  const QList<AnchorVertex *> &vertices, AnchorVertex *after)
{
#if defined(QT_DEBUG) && 0
    QString strVertices;
    for (int i = 0; i < vertices.count(); ++i) {
        strVertices += QString::fromLatin1("%1 - ").arg(vertices.at(i)->toString());
    }
    QString strPath = QString::fromLatin1("%1 - %2%3").arg(before->toString(), strVertices, after->toString());
    qDebug("simplifying [%s] to [%s - %s]", qPrintable(strPath), qPrintable(before->toString()), qPrintable(after->toString()));
#endif

    AnchorVertex *prev = before;
    QList<AnchorData *> edges;
    edges.reserve(vertices.size() + 1);

    const int numVertices = vertices.size();
    edges.reserve(numVertices + 1);
    // Take from the graph, the edges that will be simplificated
    for (int i = 0; i < numVertices; ++i) {
        AnchorVertex *next = vertices.at(i);
        AnchorData *ad = graph->takeEdge(prev, next);
        Q_ASSERT(ad);
        edges.append(ad);
        prev = next;
    }

    // Take the last edge (not covered in the loop above)
    AnchorData *ad = graph->takeEdge(vertices.last(), after);
    Q_ASSERT(ad);
    edges.append(ad);

    // Create sequence
    SequentialAnchorData *sequence = new SequentialAnchorData(vertices, edges);
    sequence->from = before;
    sequence->to = after;

    sequence->calculateSizeHints();

    return sequence;
}

/*!
   \internal

   The purpose of this function is to simplify the graph.
   Simplification serves two purposes:
   1. Reduce the number of edges in the graph, (thus the number of variables to the equation
      solver is reduced, and the solver performs better).
   2. Be able to do distribution of sequences of edges more intelligently (esp. with sequential
      anchors)

   It is essential that it must be possible to restore simplified anchors back to their "original"
   form. This is done by restoreSimplifiedAnchor().

   There are two types of simplification that can be done:
   1. Sequential simplification
      Sequential simplification means that all sequences of anchors will be merged into one single
      anchor. Only anhcors that points in the same direction will be merged.
   2. Parallel simplification
      If a simplified sequential anchor is about to be inserted between two vertices in the graph
      and there already exist an anchor between those two vertices, a parallel anchor will be
      created that serves as a placeholder for the sequential anchor and the anchor that was
      already between the two vertices.

   The process of simplification can be described as:

   1. Simplify all sequences of anchors into one anchor.
      If no further simplification was done, go to (3)
      - If there already exist an anchor where the sequential anchor is supposed to be inserted,
        take that anchor out of the graph
      - Then create a parallel anchor that holds the sequential anchor and the anchor just taken
        out of the graph.
   2. Go to (1)
   3. Done

   When creating the parallel anchors, the algorithm might identify unfeasible situations. In this
   case the simplification process stops and returns \c false. Otherwise returns \c true.
*/
bool QGraphicsAnchorLayoutPrivate::simplifyGraph(Qt::Orientation orientation)
{
    if (items.isEmpty())
        return true;

#if defined(QT_DEBUG) && 0
    qDebug("Simplifying Graph for %s",
           orientation == Horizontal ? "Horizontal" : "Vertical");

    static int count = 0;
    if (orientation == Horizontal) {
        count++;
        dumpGraph(QString::fromLatin1("%1-full").arg(count));
    }
#endif

    // Vertex simplification
    if (!simplifyVertices(orientation)) {
        restoreVertices(orientation);
        return false;
    }

    // Anchor simplification
    bool dirty;
    bool feasible = true;
    do {
        dirty = simplifyGraphIteration(orientation, &feasible);
    } while (dirty && feasible);

    // Note that if we are not feasible, we fallback and make sure that the graph is fully restored
    if (!feasible) {
        restoreSimplifiedGraph(orientation);
        restoreVertices(orientation);
        return false;
    }

#if defined(QT_DEBUG) && 0
    dumpGraph(QString::fromLatin1("%1-simplified-%2").arg(count).arg(
                  QString::fromLatin1(orientation == Horizontal ? "Horizontal" : "Vertical")));
#endif

    return true;
}

static AnchorVertex *replaceVertex_helper(AnchorData *data, AnchorVertex *oldV, AnchorVertex *newV)
{
    AnchorVertex *other;
    if (data->from == oldV) {
        data->from = newV;
        other = data->to;
    } else {
        data->to = newV;
        other = data->from;
    }
    return other;
}

bool QGraphicsAnchorLayoutPrivate::replaceVertex(Qt::Orientation orientation, AnchorVertex *oldV,
                                                 AnchorVertex *newV, const QList<AnchorData *> &edges)
{
    Graph<AnchorVertex, AnchorData> &g = graph[orientation];
    bool feasible = true;

    for (int i = 0; i < edges.size(); ++i) {
        AnchorData *ad = edges[i];
        AnchorVertex *otherV = replaceVertex_helper(ad, oldV, newV);

#if defined(QT_DEBUG)
        ad->name = QString::fromLatin1("%1 --to--> %2").arg(ad->from->toString(), ad->to->toString());
#endif

        bool newFeasible;
        AnchorData *newAnchor = addAnchorMaybeParallel(ad, &newFeasible);
        feasible &= newFeasible;

        if (newAnchor != ad) {
            // A parallel was created, we mark that in the list of anchors created by vertex
            // simplification. This is needed because we want to restore them in a separate step
            // from the restoration of anchor simplification.
            anchorsFromSimplifiedVertices[orientation].append(newAnchor);
        }

        g.takeEdge(oldV, otherV);
    }

    return feasible;
}

/*!
    \internal
*/
bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Qt::Orientation orientation)
{
    Q_Q(QGraphicsAnchorLayout);
    Graph<AnchorVertex, AnchorData> &g = graph[orientation];

    // We'll walk through vertices
    QStack<AnchorVertex *> stack;
    stack.push(layoutFirstVertex[orientation]);
    QSet<AnchorVertex *> visited;

    while (!stack.isEmpty()) {
        AnchorVertex *v = stack.pop();
        visited.insert(v);

        // Each adjacent of 'v' is a possible vertex to be merged. So we traverse all of
        // them. Since once a merge is made, we might add new adjacents, and we don't want to
        // pass two times through one adjacent. The 'index' is used to track our position.
        QList<AnchorVertex *> adjacents = g.adjacentVertices(v);
        int index = 0;

        while (index < adjacents.size()) {
            AnchorVertex *next = adjacents.at(index);
            index++;

            AnchorData *data = g.edgeData(v, next);
            const bool bothLayoutVertices = v->m_item == q && next->m_item == q;
            const bool zeroSized = !data->minSize && !data->maxSize;

            if (!bothLayoutVertices && zeroSized) {

                // Create a new vertex pair, note that we keep a list of those vertices so we can
                // easily process them when restoring the graph.
                AnchorVertexPair *newV = new AnchorVertexPair(v, next, data);
                simplifiedVertices[orientation].append(newV);

                // Collect the anchors of both vertices, the new vertex pair will take their place
                // in those anchors
                const QList<AnchorVertex *> &vAdjacents = g.adjacentVertices(v);
                const QList<AnchorVertex *> &nextAdjacents = g.adjacentVertices(next);

                for (int i = 0; i < vAdjacents.size(); ++i) {
                    AnchorVertex *adjacent = vAdjacents.at(i);
                    if (adjacent != next) {
                        AnchorData *ad = g.edgeData(v, adjacent);
                        newV->m_firstAnchors.append(ad);
                    }
                }

                for (int i = 0; i < nextAdjacents.size(); ++i) {
                    AnchorVertex *adjacent = nextAdjacents.at(i);
                    if (adjacent != v) {
                        AnchorData *ad = g.edgeData(next, adjacent);
                        newV->m_secondAnchors.append(ad);

                        // We'll also add new vertices to the adjacent list of the new 'v', to be
                        // created as a vertex pair and replace the current one.
                        if (!adjacents.contains(adjacent))
                            adjacents.append(adjacent);
                    }
                }

                // ### merge this loop into the ones that calculated m_firstAnchors/m_secondAnchors?
                // Make newV take the place of v and next
                bool feasible = replaceVertex(orientation, v, newV, newV->m_firstAnchors);
                feasible &= replaceVertex(orientation, next, newV, newV->m_secondAnchors);

                // Update the layout vertex information if one of the vertices is a layout vertex.
                AnchorVertex *layoutVertex = nullptr;
                if (v->m_item == q)
                    layoutVertex = v;
                else if (next->m_item == q)
                    layoutVertex = next;

                if (layoutVertex) {
                    // Layout vertices always have m_item == q...
                    newV->m_item = q;
                    changeLayoutVertex(orientation, layoutVertex, newV);
                }

                g.takeEdge(v, next);

                // If a non-feasibility is found, we leave early and cancel the simplification
                if (!feasible)
                    return false;

                v = newV;
                visited.insert(newV);

            } else if (!visited.contains(next) && !stack.contains(next)) {
                // If the adjacent is not fit for merge and it wasn't visited by the outermost
                // loop, we add it to the stack.
                stack.push(next);
            }
        }
    }

    return true;
}

/*!
    \internal

    One iteration of the simplification algorithm. Returns \c true if another iteration is needed.

    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, see
    the function comments for more details.
*/
bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(Qt::Orientation orientation,
                                                          bool *feasible)
{
    Q_Q(QGraphicsAnchorLayout);
    Graph<AnchorVertex, AnchorData> &g = graph[orientation];

    QSet<AnchorVertex *> visited;
    QStack<std::pair<AnchorVertex *, AnchorVertex *> > stack;
    stack.push(std::pair(static_cast<AnchorVertex *>(nullptr), layoutFirstVertex[orientation]));
    QList<AnchorVertex *> candidates;

    // Walk depth-first, in the stack we store start of the candidate sequence (beforeSequence)
    // and the vertex to be visited.
    while (!stack.isEmpty()) {
        std::pair<AnchorVertex *, AnchorVertex *> pair = stack.pop();
        AnchorVertex *beforeSequence = pair.first;
        AnchorVertex *v = pair.second;

        // The basic idea is to determine whether we found an end of sequence,
        // if that's the case, we stop adding vertices to the candidate list
        // and do a simplification step.
        //
        // A vertex can trigger an end of sequence if
        // (a) it is a layout vertex, we don't simplify away the layout vertices;
        // (b) it does not have exactly 2 adjacents;
        // (c) its next adjacent is already visited (a cycle in the graph).
        // (d) the next anchor is a center anchor.

        const QList<AnchorVertex *> &adjacents = g.adjacentVertices(v);
        const bool isLayoutVertex = v->m_item == q;
        AnchorVertex *afterSequence = v;
        bool endOfSequence = false;

        //
        // Identify the end cases.
        //

        // Identifies cases (a) and (b)
        endOfSequence = isLayoutVertex || adjacents.size() != 2;

        if (!endOfSequence) {
            // This is a tricky part. We peek at the next vertex to find out whether
            //
            // - we already visited the next vertex (c);
            // - the next anchor is a center (d).
            //
            // Those are needed to identify the remaining end of sequence cases. Note that unlike
            // (a) and (b), we preempt the end of sequence by looking into the next vertex.

            // Peek at the next vertex
            AnchorVertex *after;
            if (candidates.isEmpty())
                after = (beforeSequence == adjacents.last() ? adjacents.first() : adjacents.last());
            else
                after = (candidates.constLast() == adjacents.last() ? adjacents.first() : adjacents.last());

            // ### At this point we assumed that candidates will not contain 'after', this may not hold
            // when simplifying FLOATing anchors.
            Q_ASSERT(!candidates.contains(after));

            const AnchorData *data = g.edgeData(v, after);
            Q_ASSERT(data);
            const bool cycleFound = visited.contains(after);

            // Now cases (c) and (d)...
            endOfSequence = cycleFound || data->isCenterAnchor;

            if (!endOfSequence) {
                // If it's not an end of sequence, then the vertex didn't trigger neither of the
                // previously three cases, so it can be added to the candidates list.
                candidates.append(v);
            } else if (cycleFound && (beforeSequence != after)) {
                afterSequence = after;
                candidates.append(v);
            }
        }

        //
        // Add next non-visited vertices to the stack.
        //
        for (int i = 0; i < adjacents.size(); ++i) {
            AnchorVertex *next = adjacents.at(i);
            if (visited.contains(next))
                continue;

            // If current vertex is an end of sequence, and it'll reset the candidates list. So
            // the next vertices will build candidates lists with the current vertex as 'before'
            // vertex. If it's not an end of sequence, we keep the original 'before' vertex,
            // since we are keeping the candidates list.
            if (endOfSequence)
                stack.push(std::pair(v, next));
            else
                stack.push(std::pair(beforeSequence, next));
        }

        visited.insert(v);

        if (!endOfSequence || candidates.isEmpty())
            continue;

        //
        // Create a sequence for (beforeSequence, candidates, afterSequence).
        //

        // One restriction we have is to not simplify half of an anchor and let the other half
        // unsimplified. So we remove center edges before and after the sequence.
        const AnchorData *firstAnchor = g.edgeData(beforeSequence, candidates.constFirst());
        if (firstAnchor->isCenterAnchor) {
            beforeSequence = candidates.constFirst();
            candidates.remove(0);

            // If there's not candidates to be simplified, leave.
            if (candidates.isEmpty())
                continue;
        }

        const AnchorData *lastAnchor = g.edgeData(candidates.constLast(), afterSequence);
        if (lastAnchor->isCenterAnchor) {
            afterSequence = candidates.constLast();
            candidates.remove(candidates.size() - 1);

            if (candidates.isEmpty())
                continue;
        }

        //
        // Add the sequence to the graph.
        //

        AnchorData *sequence = createSequence(&g, beforeSequence, candidates, afterSequence);

        // If 'beforeSequence' and 'afterSequence' already had an anchor between them, we'll
        // create a parallel anchor between the new sequence and the old anchor.
        bool newFeasible;
        AnchorData *newAnchor = addAnchorMaybeParallel(sequence, &newFeasible);

        if (!newFeasible) {
            *feasible = false;
            return false;
        }

        // When a new parallel anchor is create in the graph, we finish the iteration and return
        // true to indicate a new iteration is needed. This happens because a parallel anchor
        // changes the number of adjacents one vertex has, possibly opening up oportunities for
        // building candidate lists (when adjacents == 2).
        if (newAnchor != sequence)
            return true;

        // If there was no parallel simplification, we'll keep walking the graph. So we clear the
        // candidates list to start again.
        candidates.clear();
    }

    return false;
}

void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
{
    const Qt::Orientation orientation = edge->isVertical ? Qt::Vertical : Qt::Horizontal;
#if 0
    static const char *anchortypes[] = {"Normal",
                                        "Sequential",
                                        "Parallel"};
    qDebug("Restoring %s edge.", anchortypes[int(edge->type)]);
#endif

    Graph<AnchorVertex, AnchorData> &g = graph[orientation];

    if (edge->type == AnchorData::Normal) {
        g.createEdge(edge->from, edge->to, edge);

    } else if (edge->type == AnchorData::Sequential) {
        const auto *sequence = static_cast<SequentialAnchorData *>(edge);

        for (AnchorData *data : sequence->m_edges)
            restoreSimplifiedAnchor(data);

        delete sequence;

    } else if (edge->type == AnchorData::Parallel) {

        // Skip parallel anchors that were created by vertex simplification, they will be processed
        // later, when restoring vertex simplification.
        // ### we could improve this check bit having a bit inside 'edge'
        if (anchorsFromSimplifiedVertices[orientation].contains(edge))
            return;

        ParallelAnchorData* parallel = static_cast<ParallelAnchorData*>(edge);
        restoreSimplifiedConstraints(parallel);

        // ### Because of the way parallel anchors are created in the anchor simplification
        // algorithm, we know that one of these will be a sequence, so it'll be safe if the other
        // anchor create an edge between the same vertices as the parallel.
        Q_ASSERT(parallel->firstEdge->type == AnchorData::Sequential
                 || parallel->secondEdge->type == AnchorData::Sequential);
        restoreSimplifiedAnchor(parallel->firstEdge);
        restoreSimplifiedAnchor(parallel->secondEdge);

        delete parallel;
    }
}

void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorData *parallel)
{
    if (!parallel->isCenterAnchor)
        return;

    for (int i = 0; i < parallel->m_firstConstraints.size(); ++i) {
        QSimplexConstraint *c = parallel->m_firstConstraints.at(i);
        qreal v = c->variables[parallel];
        c->variables.remove(parallel);
        c->variables.insert(parallel->firstEdge, v);
    }

    // When restoring, we might have to revert constraints back. See comments on
    // addAnchorMaybeParallel().
    const bool needsReverse = !parallel->secondForward();

    for (int i = 0; i < parallel->m_secondConstraints.size(); ++i) {
        QSimplexConstraint *c = parallel->m_secondConstraints.at(i);
        qreal v = c->variables[parallel];
        if (needsReverse)
            v *= -1;
        c->variables.remove(parallel);
        c->variables.insert(parallel->secondEdge, v);
    }
}

void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Qt::Orientation orientation)
{
#if 0
    qDebug("Restoring Simplified Graph for %s",
           orientation == Horizontal ? "Horizontal" : "Vertical");
#endif

    // Restore anchor simplification
    Graph<AnchorVertex, AnchorData> &g = graph[orientation];
    QList<std::pair<AnchorVertex *, AnchorVertex *>> connections = g.connections();
    for (int i = 0; i < connections.size(); ++i) {
        AnchorVertex *v1 = connections.at(i).first;
        AnchorVertex *v2 = connections.at(i).second;
        AnchorData *edge = g.edgeData(v1, v2);

        // We restore only sequential anchors and parallels that were not created by
        // vertex simplification.
        if (edge->type == AnchorData::Sequential
            || (edge->type == AnchorData::Parallel &&
                !anchorsFromSimplifiedVertices[orientation].contains(edge))) {

            g.takeEdge(v1, v2);
            restoreSimplifiedAnchor(edge);
        }
    }

    restoreVertices(orientation);
}

void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation)
{
    Q_Q(QGraphicsAnchorLayout);

    Graph<AnchorVertex, AnchorData> &g = graph[orientation];
    QList<AnchorVertexPair *> &toRestore = simplifiedVertices[orientation];

    // Since we keep a list of parallel anchors and vertices that were created during vertex
    // simplification, we can now iterate on those lists instead of traversing the graph
    // recursively.

    // First, restore the constraints changed when we created parallel anchors. Note that this
    // works at this point because the constraints doesn't depend on vertex information and at
    // this point it's always safe to identify whether the second child is forward or backwards.
    // In the next step, we'll change the anchors vertices so that would not be possible anymore.
    QList<AnchorData *> &parallelAnchors = anchorsFromSimplifiedVertices[orientation];

    for (int i = parallelAnchors.size() - 1; i >= 0; --i) {
        ParallelAnchorData *parallel = static_cast<ParallelAnchorData *>(parallelAnchors.at(i));
        restoreSimplifiedConstraints(parallel);
    }

    // Then, we will restore the vertices in the inverse order of creation, this way we ensure that
    // the vertex being restored was not wrapped by another simplification.
    for (int i = toRestore.size() - 1; i >= 0; --i) {
        AnchorVertexPair *pair = toRestore.at(i);
        QList<AnchorVertex *> adjacents = g.adjacentVertices(pair);

        // Restore the removed edge, this will also restore both vertices 'first' and 'second' to
        // the graph structure.
        AnchorVertex *first = pair->m_first;
        AnchorVertex *second = pair->m_second;
        g.createEdge(first, second, pair->m_removedAnchor);

        // Restore the anchors for the first child vertex
        for (int j = 0; j < pair->m_firstAnchors.size(); ++j) {
            AnchorData *ad = pair->m_firstAnchors.at(j);
            Q_ASSERT(ad->from == pair || ad->to == pair);

            replaceVertex_helper(ad, pair, first);
            g.createEdge(ad->from, ad->to, ad);
        }

        // Restore the anchors for the second child vertex
        for (int j = 0; j < pair->m_secondAnchors.size(); ++j) {
            AnchorData *ad = pair->m_secondAnchors.at(j);
            Q_ASSERT(ad->from == pair || ad->to == pair);

            replaceVertex_helper(ad, pair, second);
            g.createEdge(ad->from, ad->to, ad);
        }

        for (int j = 0; j < adjacents.size(); ++j) {
            g.takeEdge(pair, adjacents.at(j));
        }

        // The pair simplified a layout vertex, so place back the correct vertex in the variable
        // that track layout vertices
        if (pair->m_item == q) {
            AnchorVertex *layoutVertex = first->m_item == q ? first : second;
            Q_ASSERT(layoutVertex->m_item == q);
            changeLayoutVertex(orientation, pair, layoutVertex);
        }

        delete pair;
    }
    qDeleteAll(parallelAnchors);
    parallelAnchors.clear();
    toRestore.clear();
}

Qt::Orientation
QGraphicsAnchorLayoutPrivate::edgeOrientation(Qt::AnchorPoint edge) noexcept
{
    return edge > Qt::AnchorRight ? Qt::Vertical : Qt::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;
    addAnchor_helper(layout, Qt::AnchorLeft, layout,
                     Qt::AnchorRight, data);
    data->maxSize = QWIDGETSIZE_MAX;

    // Save a reference to layout vertices
    layoutFirstVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorLeft);
    layoutCentralVertex[Qt::Horizontal] = nullptr;
    layoutLastVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorRight);

    // Vertical
    data = new AnchorData;
    addAnchor_helper(layout, Qt::AnchorTop, layout,
                     Qt::AnchorBottom, data);
    data->maxSize = QWIDGETSIZE_MAX;

    // Save a reference to layout vertices
    layoutFirstVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorTop);
    layoutCentralVertex[Qt::Vertical] = nullptr;
    layoutLastVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorBottom);
}

void QGraphicsAnchorLayoutPrivate::deleteLayoutEdges()
{
    Q_Q(QGraphicsAnchorLayout);

    Q_ASSERT(!internalVertex(q, Qt::AnchorHorizontalCenter));
    Q_ASSERT(!internalVertex(q, Qt::AnchorVerticalCenter));

    removeAnchor_helper(internalVertex(q, Qt::AnchorLeft),
                        internalVertex(q, Qt::AnchorRight));
    removeAnchor_helper(internalVertex(q, Qt::AnchorTop),
                        internalVertex(q, Qt::AnchorBottom));
}

void QGraphicsAnchorLayoutPrivate::createItemEdges(QGraphicsLayoutItem *item)
{
    items.append(item);

    // Create horizontal and vertical internal anchors for the item and
    // refresh its size hint / policy values.
    AnchorData *data = new AnchorData;
    addAnchor_helper(item, Qt::AnchorLeft, item, Qt::AnchorRight, data);
    data->refreshSizeHints();

    data = new AnchorData;
    addAnchor_helper(item, Qt::AnchorTop, item, Qt::AnchorBottom, data);
    data->refreshSizeHints();
}

/*!
  \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, Qt::AnchorPoint centerEdge)
{
    Q_Q(QGraphicsAnchorLayout);

    Qt::Orientation orientation;
    switch (centerEdge) {
    case Qt::AnchorHorizontalCenter:
        orientation = Qt::Horizontal;
        break;
    case Qt::AnchorVerticalCenter:
        orientation = Qt::Vertical;
        break;
    default:
        // Don't create center edges unless needed
        return;
    }

    // Check if vertex already exists
    if (internalVertex(item, centerEdge))
        return;

    // Orientation code
    Qt::AnchorPoint firstEdge;
    Qt::AnchorPoint lastEdge;

    if (orientation == Qt::Horizontal) {
        firstEdge = Qt::AnchorLeft;
        lastEdge = Qt::AnchorRight;
    } else {
        firstEdge = Qt::AnchorTop;
        lastEdge = Qt::AnchorBottom;
    }

    AnchorVertex *first = internalVertex(item, firstEdge);
    AnchorVertex *last = internalVertex(item, lastEdge);
    Q_ASSERT(first && last);

    // Create new anchors
    QSimplexConstraint *c = new QSimplexConstraint;

    AnchorData *data = new AnchorData;
    c->variables.insert(data, 1.0);
    addAnchor_helper(item, firstEdge, item, centerEdge, data);
    data->isCenterAnchor = true;
    data->dependency = AnchorData::Master;
    data->refreshSizeHints();

    data = new AnchorData;
    c->variables.insert(data, -1.0);
    addAnchor_helper(item, centerEdge, item, lastEdge, data);
    data->isCenterAnchor = true;
    data->dependency = AnchorData::Slave;
    data->refreshSizeHints();

    itemCenterConstraints[orientation].append(c);

    // Remove old one
    removeAnchor_helper(first, last);

    if (item == q) {
        layoutCentralVertex[orientation] = internalVertex(q, centerEdge);
    }
}

void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
    QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge,
    bool substitute)
{
    Q_Q(QGraphicsAnchorLayout);

    Qt::Orientation orientation;
    switch (centerEdge) {
    case Qt::AnchorHorizontalCenter:
        orientation = Qt::Horizontal;
        break;
    case Qt::AnchorVerticalCenter:
        orientation = Qt::Vertical;
        break;
    default:
        // Don't remove edges that not the center ones
        return;
    }

    // Orientation code
    Qt::AnchorPoint firstEdge;
    Qt::AnchorPoint lastEdge;

    if (orientation == Qt::Horizontal) {
        firstEdge = Qt::AnchorLeft;
        lastEdge = Qt::AnchorRight;
    } else {
        firstEdge = Qt::AnchorTop;
        lastEdge = Qt::AnchorBottom;
    }

    AnchorVertex *center = internalVertex(item, centerEdge);
    if (!center)
        return;
    AnchorVertex *first = internalVertex(item, firstEdge);

    Q_ASSERT(first);
    Q_ASSERT(center);

    Graph<AnchorVertex, AnchorData> &g = graph[orientation];


    AnchorData *oldData = g.edgeData(first, center);
    // Remove center constraint
    for (int i = itemCenterConstraints[orientation].size() - 1; i >= 0; --i) {
        if (itemCenterConstraints[orientation].at(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 *data = new AnchorData;
        addAnchor_helper(item, firstEdge, item, lastEdge, data);
        data->refreshSizeHints();

        // Remove old anchors
        removeAnchor_helper(first, center);
        removeAnchor_helper(center, internalVertex(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.size(); ++i) {
            AnchorVertex *v = adjacents.at(i);
            if (v->m_item != item) {
                removeAnchor_helper(center, internalVertex(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_helper(first, internalVertex(item, lastEdge));
    }

    if (item == q) {
        layoutCentralVertex[orientation] = nullptr;
    }
}


void QGraphicsAnchorLayoutPrivate::removeCenterConstraints(QGraphicsLayoutItem *item,
                                                           Qt::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 == Qt::Horizontal ?
                                       Qt::AnchorLeft :
                                       Qt::AnchorTop);
    AnchorVertex *center = internalVertex(item, orientation == Qt::Horizontal ?
                                        Qt::AnchorHorizontalCenter :
                                        Qt::AnchorVerticalCenter);

    // 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].at(i)->variables.contains(internalAnchor)) {
            delete itemCenterConstraints[orientation].takeAt(i);
            break;
        }
    }
}

/*!
 * \internal
 * Implements the high level "addAnchor" feature. Called by the public API
 * addAnchor method.
 *
 * The optional \a spacing argument defines the size of the anchor. If not provided,
 * the anchor size is either 0 or not-set, depending on type of anchor created (see
 * matrix below).
 *
 * All anchors that remain with size not-set will assume the standard spacing,
 * set either by the layout style or through the "setSpacing" layout API.
 */
QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::addAnchor(QGraphicsLayoutItem *firstItem,
                                                         Qt::AnchorPoint firstEdge,
                                                         QGraphicsLayoutItem *secondItem,
                                                         Qt::AnchorPoint secondEdge,
                                                         qreal *spacing)
{
    Q_Q(QGraphicsAnchorLayout);
    if ((firstItem == nullptr) || (secondItem == nullptr)) {
        qWarning("QGraphicsAnchorLayout::addAnchor(): "
                 "Cannot anchor NULL items");
        return nullptr;
    }

    if (firstItem == secondItem) {
        qWarning("QGraphicsAnchorLayout::addAnchor(): "
                 "Cannot anchor the item to itself");
        return nullptr;
    }

    if (edgeOrientation(secondEdge) != edgeOrientation(firstEdge)) {
        qWarning("QGraphicsAnchorLayout::addAnchor(): "
                 "Cannot anchor edges of different orientations");
        return nullptr;
    }

    const QGraphicsLayoutItem *parentWidget = q->parentLayoutItem();
    if (firstItem == parentWidget || secondItem == parentWidget) {
        qWarning("QGraphicsAnchorLayout::addAnchor(): "
                 "You cannot add the parent of the layout to the layout.");
        return nullptr;
    }

    // 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 = new AnchorData;
    QGraphicsAnchor *graphicsAnchor = acquireGraphicsAnchor(data);

    addAnchor_helper(firstItem, firstEdge, secondItem, secondEdge, data);

    if (spacing) {
        graphicsAnchor->setSpacing(*spacing);
    } else {
        // 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, Qt::Horizontal) == Qt::AnchorHorizontalCenter
            || oppositeEdge(firstEdge) != secondEdge) {
            graphicsAnchor->setSpacing(0);
        } else {
            graphicsAnchor->unsetSpacing();
        }
    }

    return graphicsAnchor;
}

/*
  \internal

  This method adds an AnchorData to the internal graph. It is responsible for doing
  the boilerplate part of such task.

  If another AnchorData exists between the mentioned vertices, it is deleted and
  the new one is inserted.
*/
void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstItem,
                                                    Qt::AnchorPoint firstEdge,
                                                    QGraphicsLayoutItem *secondItem,
                                                    Qt::AnchorPoint secondEdge,
                                                    AnchorData *data)
{
    Q_Q(QGraphicsAnchorLayout);

    const Qt::Orientation orientation = edgeOrientation(firstEdge);

    // Create or increase the reference count for the related vertices.
    AnchorVertex *v1 = addInternalVertex(firstItem, firstEdge);
    AnchorVertex *v2 = addInternalVertex(secondItem, secondEdge);

    // Remove previous anchor
    if (graph[orientation].edgeData(v1, v2)) {
        removeAnchor_helper(v1, v2);
    }

    // If its an internal anchor, set the associated item
    if (firstItem == secondItem)
        data->item = firstItem;

    data->isVertical = orientation == Qt::Vertical;

    // 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->from = v1;
    data->to = v2;
#ifdef QT_DEBUG
    data->name = QString::fromLatin1("%1 --to--> %2").arg(v1->toString(), v2->toString());
#endif
    // ### bit to track internal anchors, since inside AnchorData methods
    // we don't have access to the 'q' pointer.
    data->isLayoutAnchor = (data->item == q);

    graph[orientation].createEdge(v1, v2, data);
}

QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::getAnchor(QGraphicsLayoutItem *firstItem,
                                                         Qt::AnchorPoint firstEdge,
                                                         QGraphicsLayoutItem *secondItem,
                                                         Qt::AnchorPoint secondEdge)
{
    // Do not expose internal anchors
    if (firstItem == secondItem)
        return nullptr;

    const Qt::Orientation orientation = edgeOrientation(firstEdge);
    AnchorVertex *v1 = internalVertex(firstItem, firstEdge);
    AnchorVertex *v2 = internalVertex(secondItem, secondEdge);

    QGraphicsAnchor *graphicsAnchor = nullptr;

    AnchorData *data = graph[orientation].edgeData(v1, v2);
    if (data) {
        // We could use "acquireGraphicsAnchor" here, but to avoid a regression where
        // an internal anchor was wrongly exposed, I want to ensure no new
        // QGraphicsAnchor instances are created by this call.
        // This assumption must hold because anchors are either user-created (and already
        // have their public object created), or they are internal (and must not reach
        // this point).
        Q_ASSERT(data->graphicsAnchor);
        graphicsAnchor = data->graphicsAnchor;
    }
    return graphicsAnchor;
}

/*!
 * \internal
 *
 * Implements the high level "removeAnchor" feature. Called by
 * the QAnchorData destructor.
 */
void QGraphicsAnchorLayoutPrivate::removeAnchor(AnchorVertex *firstVertex,
                                                AnchorVertex *secondVertex)
{
    Q_Q(QGraphicsAnchorLayout);

    // Save references to items while it's safe to assume the vertices exist
    QGraphicsLayoutItem *firstItem = firstVertex->m_item;
    QGraphicsLayoutItem *secondItem = secondVertex->m_item;

    // Delete the anchor (may trigger deletion of center vertices)
    removeAnchor_helper(firstVertex, secondVertex);

    // Ensure no dangling pointer is left behind
    firstVertex = secondVertex = nullptr;

    // Checking if the item stays in the layout or not
    bool keepFirstItem = false;
    bool keepSecondItem = false;

    std::pair<AnchorVertex *, int> v;
    int refcount = -1;

    if (firstItem != q) {
        for (int i = Qt::AnchorLeft; i <= Qt::AnchorBottom; ++i) {
            v = m_vertexList.value(std::pair(firstItem, static_cast<Qt::AnchorPoint>(i)));
            if (v.first) {
                if (i == Qt::AnchorHorizontalCenter || i == Qt::AnchorVerticalCenter)
                    refcount = 2;
                else
                    refcount = 1;

                if (v.second > refcount) {
                    keepFirstItem = true;
                    break;
                }
            }
        }
    } else
        keepFirstItem = true;

    if (secondItem != q) {