azul-layout 0.0.5

Layout solver + font and image loader the Azul GUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
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
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
use alloc::{
    collections::{btree_map::BTreeMap, btree_set::BTreeSet},
    string::ToString,
    vec::Vec,
};
use core::f32;

#[cfg(feature = "text_layout")]
use azul_core::callbacks::{CallbackInfo, DomNodeId, InlineText};
use azul_core::{
    app_resources::{
        DpiScaleFactor, Epoch, FontInstanceKey, IdNamespace, ImageCache, RendererResources,
        ResourceUpdate, ShapedWords, WordPositions, Words,
    },
    callbacks::DocumentId,
    display_list::RenderCallbacks,
    dom::{NodeData, NodeType},
    id_tree::{NodeDataContainer, NodeDataContainerRef, NodeDataContainerRefMut, NodeId},
    styled_dom::{
        ChangedCssProperty, CssPropertyCache, DomId, NodeHierarchyItem, ParentWithNodeDepth,
        StyledDom, StyledNode, StyledNodeState,
    },
    traits::GetTextLayout,
    ui_solver::{
        GpuValueCache, HeightCalculatedRect, HorizontalSolvedPosition, LayoutResult,
        PositionInfoInner, PositionedRectangle, RelayoutChanges, ResolvedOffsets, ScrolledNodes,
        StyleBoxShadowOffsets, VerticalSolvedPosition, WhConstraint, WidthCalculatedRect,
        DEFAULT_FONT_SIZE_PX,
    },
    window::{FullWindowState, LogicalPosition, LogicalRect, LogicalSize},
};
use azul_css::*;
use rust_fontconfig::FcFontCache;

const DEFAULT_FLEX_GROW_FACTOR: f32 = 0.0;

#[derive(Debug)]
pub struct WhConfig {
    pub width: WidthConfig,
    pub height: HeightConfig,
}

#[derive(Debug, Default)]
pub struct WidthConfig {
    pub exact: Option<LayoutWidth>,
    pub max: Option<LayoutMaxWidth>,
    pub min: Option<LayoutMinWidth>,
    pub overflow: Option<LayoutOverflow>,
}

#[derive(Debug, Default)]
pub struct HeightConfig {
    pub exact: Option<LayoutHeight>,
    pub max: Option<LayoutMaxHeight>,
    pub min: Option<LayoutMinHeight>,
    pub overflow: Option<LayoutOverflow>,
}

fn precalculate_wh_config(styled_dom: &StyledDom) -> NodeDataContainer<WhConfig> {
    let css_property_cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();

    NodeDataContainer {
        internal: styled_dom
            .styled_nodes
            .as_container()
            .internal
            .iter()
            .enumerate()
            .map(|(node_id, styled_node)| {
                let node_id = NodeId::new(node_id);
                WhConfig {
                    width: WidthConfig {
                        exact: css_property_cache
                            .get_width(&node_data_container[node_id], &node_id, &styled_node.state)
                            .and_then(|p| p.get_property().copied()),
                        max: css_property_cache
                            .get_max_width(
                                &node_data_container[node_id],
                                &node_id,
                                &styled_node.state,
                            )
                            .and_then(|p| p.get_property().copied()),
                        min: css_property_cache
                            .get_min_width(
                                &node_data_container[node_id],
                                &node_id,
                                &styled_node.state,
                            )
                            .and_then(|p| p.get_property().copied()),
                        overflow: css_property_cache
                            .get_overflow_x(
                                &node_data_container[node_id],
                                &node_id,
                                &styled_node.state,
                            )
                            .and_then(|p| p.get_property().copied()),
                    },
                    height: HeightConfig {
                        exact: css_property_cache
                            .get_height(&node_data_container[node_id], &node_id, &styled_node.state)
                            .and_then(|p| p.get_property().copied()),
                        max: css_property_cache
                            .get_max_height(
                                &node_data_container[node_id],
                                &node_id,
                                &styled_node.state,
                            )
                            .and_then(|p| p.get_property().copied()),
                        min: css_property_cache
                            .get_min_height(
                                &node_data_container[node_id],
                                &node_id,
                                &styled_node.state,
                            )
                            .and_then(|p| p.get_property().copied()),
                        overflow: css_property_cache
                            .get_overflow_y(
                                &node_data_container[node_id],
                                &node_id,
                                &styled_node.state,
                            )
                            .and_then(|p| p.get_property().copied()),
                    },
                }
            })
            .collect(),
    }
}

macro_rules! determine_preferred {
    ($fn_name:ident, $width:ident) => {
        /// - `preferred_inner_width` denotes the preferred width of the
        /// width or height got from the from the rectangles content.
        ///
        /// For example, if you have an image, the `preferred_inner_width` is the images width,
        /// if the node type is an text, the `preferred_inner_width` is the text height.
        fn $fn_name(
            config: &WhConfig,
            preferred_width: Option<f32>,
            parent_width: f32,
            parent_overflow: LayoutOverflow,
        ) -> WhConstraint {
            let width = config
                .$width
                .exact
                .as_ref()
                .map(|x| x.inner.to_pixels(parent_width).max(0.0));
            let min_width = config
                .$width
                .min
                .as_ref()
                .map(|x| x.inner.to_pixels(parent_width).max(0.0));
            let max_width = config
                .$width
                .max
                .as_ref()
                .map(|x| x.inner.to_pixels(parent_width).max(0.0));

            if let Some(width) = width {
                // ignore preferred_width if the width is set manually
                WhConstraint::EqualTo(
                    width
                        .min(max_width.unwrap_or(f32::MAX))
                        .max(min_width.unwrap_or(0.0)),
                )
            } else {
                // no width, only min_width and max_width
                if let Some(max_width) = max_width {
                    WhConstraint::Between(
                        min_width
                            .unwrap_or(0.0)
                            .max(preferred_width.unwrap_or(0.0))
                            .min(max_width.min(f32::MAX)),
                        max_width.max(0.0),
                    )
                } else {
                    // no width or max_width, only min_width
                    if let Some(min_width) = min_width {
                        if min_width.max(preferred_width.unwrap_or(0.0)) < parent_width.max(0.0) {
                            WhConstraint::Between(
                                min_width.max(preferred_width.unwrap_or(0.0)),
                                parent_width.max(0.0),
                            )
                        } else {
                            WhConstraint::EqualTo(min_width.max(preferred_width.unwrap_or(0.0)))
                        }
                    } else {
                        // no width, min_width or max_width: try preferred width
                        if let Some(preferred_width) = preferred_width {
                            let preferred_max = preferred_width.max(0.0);
                            if preferred_max > parent_width {
                                match parent_overflow {
                                    LayoutOverflow::Hidden | LayoutOverflow::Visible => {
                                        WhConstraint::Between(preferred_max, core::f32::MAX)
                                    }
                                    LayoutOverflow::Auto | LayoutOverflow::Scroll => {
                                        WhConstraint::EqualTo(parent_width)
                                    }
                                }
                            } else {
                                WhConstraint::Between(preferred_max, parent_width)
                            }
                        } else {
                            match parent_overflow {
                                LayoutOverflow::Hidden | LayoutOverflow::Visible => {
                                    WhConstraint::Between(0.0, core::f32::MAX)
                                }
                                LayoutOverflow::Auto | LayoutOverflow::Scroll => {
                                    WhConstraint::Between(0.0, parent_width)
                                }
                            }
                        }
                    }
                }
            }
        }
    };
}

// Returns the preferred width, given [width, min_width, max_width] inside a RectLayout
// or `None` if the height can't be determined from the node alone.
//
// fn determine_preferred_width(layout: &RectLayout) -> Option<f32>
determine_preferred!(determine_preferred_width, width);

// Returns the preferred height, given [height, min_height, max_height] inside a RectLayout
// or `None` if the height can't be determined from the node alone.
//
// fn determine_preferred_height(layout: &RectLayout) -> Option<f32>
determine_preferred!(determine_preferred_height, height);

/// ```rust
/// typed_arena!(
///     WidthCalculatedRect,
///     preferred_width,
///     determine_preferred_width,
///     get_horizontal_padding,
///     get_flex_basis_horizontal,
///     width_calculated_rect_arena_from_rect_layout_arena,
///     bubble_preferred_widths_to_parents,
///     width_calculated_rect_arena_apply_flex_grow,
///     width_calculated_rect_arena_sum_children_flex_basis,
///     Horizontal,
/// )
/// ```
macro_rules! typed_arena {
    (
        $struct_name:ident,
        $preferred_field:ident,
        $determine_preferred_fn:ident,
        $width_or_height:ident,
        $get_padding_fn:ident,
        $get_border_fn:ident,
        $get_margin_fn:ident,
        $get_flex_basis:ident,
        $from_rect_layout_arena_fn_name:ident,
        $bubble_fn_name:ident,
        $apply_flex_grow_fn_name:ident,
        $main_axis:ident,
        $margin_left:ident,
        $margin_right:ident,
        $padding_left:ident,
        $padding_right:ident,
        $border_left:ident,
        $border_right:ident,
        $left:ident,
        $right:ident,
    ) => {
        /// Fill out the preferred width of all nodes.
        ///
        /// We could operate on the NodeDataContainer<StyledNode> directly,
        /// but that makes testing very hard since we are only interested
        /// in testing or touching the layout. So this makes the
        /// calculation maybe a few microseconds slower, but gives better
        /// testing capabilities
        ///
        /// NOTE: Later on, this could maybe be a NodeDataContainer<&'a RectLayout>.
        #[must_use]
        fn $from_rect_layout_arena_fn_name<'a>(
            wh_configs: &NodeDataContainerRef<'a, WhConfig>,
            offsets: &NodeDataContainerRef<'a, AllOffsets>,
            widths: &NodeDataContainerRef<'a, Option<f32>>,
            node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
            node_depths: &[ParentWithNodeDepth],
            root_size_width: f32,
        ) -> NodeDataContainer<$struct_name> {
            // then calculate the widths again, but this time using the parent nodes
            let mut new_nodes = NodeDataContainer {
                internal: vec![$struct_name::default(); node_hierarchy.len()],
            };

            for ParentWithNodeDepth { depth: _, node_id } in node_depths.iter() {
                let parent_id = match node_id.into_crate_internal() {
                    Some(s) => s,
                    None => continue,
                };

                let nd = &wh_configs[parent_id];
                let parent_offsets = &offsets[parent_id];
                let width = match widths.get(parent_id) {
                    Some(s) => *s,
                    None => continue,
                };

                let parent_parent_id = node_hierarchy
                    .get(parent_id)
                    .and_then(|t| t.parent_id())
                    .unwrap_or(NodeId::ZERO);

                let parent_parent_width = new_nodes
                    .as_ref()
                    .get(parent_parent_id)
                    .map(|parent| parent.$preferred_field)
                    .unwrap_or_default()
                    .max_available_space()
                    .unwrap_or(root_size_width);

                let parent_parent_overflow = wh_configs[parent_parent_id]
                    .$width_or_height
                    .overflow
                    .unwrap_or_default();

                let parent_width = $determine_preferred_fn(
                    &nd,
                    width,
                    parent_parent_width,
                    parent_parent_overflow,
                );

                new_nodes.as_ref_mut()[parent_id] = $struct_name {
                    // TODO: get the initial width of the rect content
                    $preferred_field: parent_width,

                    $margin_left: parent_offsets.margin.$left.as_ref().copied(),
                    $margin_right: parent_offsets.margin.$right.as_ref().copied(),

                    $padding_left: parent_offsets.padding.$left.as_ref().copied(),
                    $padding_right: parent_offsets.padding.$right.as_ref().copied(),

                    $border_left: parent_offsets.border_widths.$left.as_ref().copied(),
                    $border_right: parent_offsets.border_widths.$right.as_ref().copied(),

                    $left: parent_offsets.position.$left.as_ref().copied(),
                    $right: parent_offsets.position.$right.as_ref().copied(),

                    box_sizing: parent_offsets.box_sizing,
                    flex_grow_px: 0.0,
                    min_inner_size_px: parent_width.min_needed_space().unwrap_or(0.0),
                };

                let parent_overflow = wh_configs[parent_id]
                    .$width_or_height
                    .overflow
                    .unwrap_or_default();

                for child_id in parent_id.az_children(node_hierarchy) {
                    let nd = &wh_configs[child_id];
                    let child_offsets = &offsets[child_id];
                    let width = match widths.get(child_id) {
                        Some(s) => *s,
                        None => continue,
                    };
                    let parent_available_space = parent_width.max_available_space().unwrap_or(0.0);
                    let child_width = $determine_preferred_fn(
                        &nd,
                        width,
                        parent_available_space,
                        parent_overflow,
                    );
                    let mut child = $struct_name {
                        // TODO: get the initial width of the rect content
                        $preferred_field: child_width,

                        $margin_left: child_offsets.margin.$left.as_ref().copied(),
                        $margin_right: child_offsets.margin.$right.as_ref().copied(),

                        $padding_left: child_offsets.padding.$left.as_ref().copied(),
                        $padding_right: child_offsets.padding.$right.as_ref().copied(),

                        $border_left: child_offsets.border_widths.$left.as_ref().copied(),
                        $border_right: child_offsets.border_widths.$right.as_ref().copied(),

                        $left: child_offsets.position.$left.as_ref().copied(),
                        $right: child_offsets.position.$right.as_ref().copied(),

                        box_sizing: child_offsets.box_sizing,
                        flex_grow_px: 0.0,
                        min_inner_size_px: child_width.min_needed_space().unwrap_or(0.0),
                    };
                    let child_flex_basis = child
                        .$get_flex_basis(parent_available_space)
                        .min(child_width.max_available_space().unwrap_or(core::f32::MAX));
                    child.min_inner_size_px = child.min_inner_size_px.max(child_flex_basis);
                    new_nodes.as_ref_mut()[child_id] = child;
                }
            }

            new_nodes
        }

        /// Bubble the inner sizes to their parents -  on any parent nodes, fill out
        /// the width so that the `preferred_width` can contain the child nodes (if
        /// that doesn't violate the constraints of the parent)
        fn $bubble_fn_name<'a, 'b>(
            node_data: &mut NodeDataContainerRefMut<'b, $struct_name>,
            node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
            layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
            layout_directions: &NodeDataContainerRef<'a, LayoutFlexDirection>,
            wh_configs: &NodeDataContainerRef<'a, WhConfig>,
            node_depths: &[ParentWithNodeDepth],
            root_size_width: f32,
        ) {
            // Reverse, since we want to go from the inside out
            // (depth 5 needs to be filled out first)
            //
            // Set the preferred_width of the parent nodes
            for ParentWithNodeDepth { depth: _, node_id } in node_depths.iter().rev() {
                let parent_id = match node_id.into_crate_internal() {
                    Some(s) => s,
                    None => continue,
                };

                let parent_parent_width = match node_hierarchy[parent_id].parent_id() {
                    None => root_size_width,
                    Some(s) => node_data[s]
                        .$preferred_field
                        .max_available_space()
                        .unwrap_or(root_size_width), // TODO: wrong
                };

                let parent_width = node_data[parent_id]
                    .$preferred_field
                    .max_available_space()
                    .unwrap_or(parent_parent_width);
                let flex_axis = layout_directions[parent_id].get_axis();

                let mut children_flex_basis = 0.0_f32;

                parent_id
                    .az_children(node_hierarchy)
                    .filter(|child_id| layout_positions[*child_id] != LayoutPosition::Absolute)
                    .map(|child_id| {
                        (
                            child_id,
                            node_data[child_id].min_inner_size_px
                                + node_data[child_id].$get_margin_fn(parent_width),
                        )
                    })
                    .for_each(|(_, flex_basis)| {
                        if flex_axis == LayoutAxis::$main_axis {
                            children_flex_basis += flex_basis;
                        } else {
                            // cross direction: take max flex basis of children
                            children_flex_basis = children_flex_basis.max(flex_basis);
                        }
                    });

                // if the children overflow, then the maximum width / height that can be
                // bubbled is the max_height / max_width of the parent
                let parent_max_available_space = node_data[parent_id]
                    .$preferred_field
                    .max_available_space()
                    .unwrap_or(children_flex_basis);
                let children_inner_width = parent_max_available_space.min(children_flex_basis);

                // parent minimum width = children (including borders, padding + margin of children)
                // PLUS padding (including borders) of parent
                let parent_min_inner_size_px = children_inner_width
                    + node_data[parent_id].$get_padding_fn(parent_parent_width);

                // bubble the min_inner_size_px to the parent
                node_data[parent_id].min_inner_size_px = node_data[parent_id]
                    .min_inner_size_px
                    .max(parent_min_inner_size_px);
            }

            // Now, the width of all elements should be filled,
            // but they aren't flex-grown yet
        }

        /// Go from the root down and flex_grow the children if
        /// needed - respects the `width`, `min_width` and `max_width`
        /// properties
        ///
        /// The layout step doesn't account for the min_width
        /// and max_width constraints, so we have to adjust them manually
        fn $apply_flex_grow_fn_name<'a, 'b>(
            node_data: &mut NodeDataContainer<$struct_name>,
            node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
            layout_displays: &NodeDataContainerRef<'a, CssPropertyValue<LayoutDisplay>>,
            layout_flex_grows: &NodeDataContainerRef<'a, f32>,
            layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
            layout_directions: &NodeDataContainerRef<'a, LayoutFlexDirection>,
            node_depths: &[ParentWithNodeDepth],
            root_width: f32,
            parents_to_recalc: &BTreeSet<NodeId>,
        ) {
            /// Does the actual width layout, respects the `width`,
            /// `min_width` and `max_width` properties as well as the
            /// `flex_grow` factor. `flex_shrink` currently does nothing.
            fn distribute_space_along_main_axis<'a>(
                node_id: &NodeId,
                children: &[NodeId],
                node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
                layout_displays: &NodeDataContainerRef<'a, CssPropertyValue<LayoutDisplay>>,
                layout_flex_grows: &NodeDataContainerRef<'a, f32>,
                layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
                width_calculated_arena: &'a NodeDataContainerRef<$struct_name>,
                root_width: f32,
            ) -> Vec<f32> {
                // The inner space of the parent node, without the padding
                let parent_node_inner_width = {
                    let parent_node = &width_calculated_arena[*node_id];
                    let parent_parent_width = node_hierarchy[*node_id]
                        .parent_id()
                        .and_then(|p| {
                            width_calculated_arena[p]
                                .$preferred_field
                                .max_available_space()
                        })
                        .unwrap_or(root_width);
                    parent_node.total() - parent_node.$get_padding_fn(parent_parent_width)
                };

                // 1. Set all child elements to their minimum required width or 0.0
                // if there is no min width
                let mut children_flex_grow = children
                    .iter()
                    .map(|child_id| {
                        if layout_positions[*child_id] != LayoutPosition::Absolute {
                            // so that node.min_width + node.flex_grow_px = exact_width
                            match width_calculated_arena[*child_id].$preferred_field {
                                WhConstraint::Between(min, _) => {
                                    if min > width_calculated_arena[*child_id].min_inner_size_px {
                                        min - width_calculated_arena[*child_id].min_inner_size_px
                                    } else {
                                        0.0
                                    }
                                }
                                WhConstraint::EqualTo(exact) => {
                                    exact - width_calculated_arena[*child_id].min_inner_size_px
                                }
                                WhConstraint::Unconstrained => 0.0,
                            }
                        } else {
                            // `position: absolute` items don't take space away from their siblings,
                            // rather they take the minimum needed space by
                            // their content
                            let nearest_relative_parent_node = child_id
                                .get_nearest_matching_parent(node_hierarchy, |n| {
                                    layout_positions[n].is_positioned()
                                })
                                .unwrap_or(NodeId::new(0));

                            let relative_parent_width = {
                                let relative_parent_node =
                                    &width_calculated_arena[nearest_relative_parent_node];
                                relative_parent_node.flex_grow_px
                                    + relative_parent_node.min_inner_size_px
                            };

                            // The absolute positioned node might have a max-width constraint, which
                            // has a higher precedence than `top, bottom, left,
                            // right`.
                            let max_space_current_node = width_calculated_arena[*child_id]
                                .$preferred_field
                                .calculate_from_relative_parent(relative_parent_width);

                            // expand so that node.min_inner_size_px + node.flex_grow_px =
                            // max_space_current_node
                            if max_space_current_node
                                > width_calculated_arena[*child_id].min_inner_size_px
                            {
                                max_space_current_node
                                    - width_calculated_arena[*child_id].min_inner_size_px
                            } else {
                                0.0
                            }
                        }
                    })
                    .collect::<Vec<f32>>();

                // 2. Calculate how much space has been taken up so far by the minimum width /
                //    height Exclude position: absolute items from being added into the sum since
                //    they are taken out of the regular layout flow
                let space_taken_up: f32 = children
                    .iter()
                    .enumerate()
                    .filter(|(_, child_id)| {
                        layout_positions[**child_id] != LayoutPosition::Absolute
                    })
                    .map(|(child_index_in_parent, child_id)| {
                        width_calculated_arena[*child_id].min_inner_size_px
                            + width_calculated_arena[*child_id]
                                .$get_margin_fn(parent_node_inner_width)
                            + children_flex_grow[child_index_in_parent]
                    })
                    .sum();

                // all items are now expanded to their minimum width,
                // calculate how much space is remaining
                let mut space_available = parent_node_inner_width - space_taken_up;

                if space_available <= 0.0 {
                    // no space to distribute
                    return children_flex_grow;
                }

                // The fixed-width items are now considered solved,
                // so subtract them out of the width of the parent.

                // Get the node ids that have to be expanded, exclude
                // fixed-width and absolute childrens
                let mut variable_width_childs = children
                    .iter()
                    .enumerate()
                    .filter(|(_, id)| {
                        !width_calculated_arena[**id]
                            .$preferred_field
                            .is_fixed_constraint()
                    })
                    .filter(|(_, id)| layout_positions[**id] != LayoutPosition::Absolute)
                    .filter(|(_, id)| {
                        !(layout_displays[**id] == CssPropertyValue::Exact(LayoutDisplay::None)
                            || layout_displays[**id] == CssPropertyValue::None)
                    })
                    .filter(|(_, id)| layout_flex_grows[**id] > 0.0)
                    .map(|(index_in_parent, id)| (*id, index_in_parent))
                    .collect::<BTreeMap<NodeId, usize>>();

                loop {
                    if !(space_available > 0.0) || variable_width_childs.is_empty() {
                        break;
                    }

                    // In order to apply flex-grow correctly, we need the sum of
                    // the flex-grow factors of all the variable-width children
                    //
                    // NOTE: variable_width_childs can change its length,
                    // have to recalculate every loop!
                    let children_combined_flex_grow: f32 = variable_width_childs
                        .iter()
                        .map(|(child_id, _)| layout_flex_grows[*child_id])
                        .sum();

                    if children_combined_flex_grow <= 0.0 {
                        break;
                    }

                    let size_per_child = space_available / children_combined_flex_grow;

                    // Grow all variable children by the same amount.
                    let new_iteration = variable_width_childs
                        .iter()
                        .map(|(variable_child_id, index_in_parent)| {
                            let flex_grow_of_child = layout_flex_grows[*variable_child_id];
                            let added_space_for_one_child = size_per_child * flex_grow_of_child;
                            let max_width = width_calculated_arena[*variable_child_id]
                                .$preferred_field
                                .max_available_space();
                            let current_flex_grow = children_flex_grow[*index_in_parent];
                            let current_width_of_child = {
                                width_calculated_arena[*variable_child_id].min_inner_size_px
                                    + current_flex_grow
                            };

                            let (flex_grow_this_iteration, node_is_solved) = match max_width {
                                Some(max) => {
                                    let overflow: f32 =
                                        current_width_of_child + added_space_for_one_child - max;
                                    if !overflow.is_sign_negative() {
                                        // flex-growing will overflow max-width, record overflow and
                                        // set
                                        ((max - current_width_of_child).max(0.0), true)
                                    } else {
                                        (added_space_for_one_child, false)
                                    }
                                }
                                None => (added_space_for_one_child, false),
                            };

                            (
                                *variable_child_id,
                                *index_in_parent,
                                flex_grow_this_iteration,
                                node_is_solved,
                            )
                        })
                        .collect::<Vec<_>>();

                    for (child_id, index_in_parent, flex_grow_to_add, node_is_solved) in
                        new_iteration
                    {
                        children_flex_grow[index_in_parent] += flex_grow_to_add;
                        space_available -= flex_grow_to_add;
                        if node_is_solved {
                            variable_width_childs.remove(&child_id);
                        }
                    }
                }

                children_flex_grow
            }

            fn distribute_space_along_cross_axis<'a>(
                parent_id: &NodeId,
                children: &[NodeId],
                node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
                layout_displays: &NodeDataContainerRef<'a, CssPropertyValue<LayoutDisplay>>,
                layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
                width_calculated_arena: &'a NodeDataContainerRef<$struct_name>,
                root_width: f32,
            ) -> Vec<f32> {
                let parent_node_inner_width = {
                    // The inner space of the parent node, without the padding
                    let parent_node = &width_calculated_arena[*parent_id];
                    let parent_parent_width = node_hierarchy[*parent_id]
                        .parent_id()
                        .and_then(|p| {
                            width_calculated_arena[p]
                                .$preferred_field
                                .max_available_space()
                        })
                        .unwrap_or(root_width);

                    parent_node.total() - parent_node.$get_padding_fn(parent_parent_width)
                };

                let nearest_relative_node = if layout_positions[*parent_id].is_positioned() {
                    *parent_id
                } else {
                    parent_id
                        .get_nearest_matching_parent(node_hierarchy, |n| {
                            layout_positions[n].is_positioned()
                        })
                        .unwrap_or(NodeId::new(0))
                };

                let last_relative_node_inner_width = {
                    let last_relative_node = &width_calculated_arena[nearest_relative_node];
                    let last_relative_node_parent_width = node_hierarchy[nearest_relative_node]
                        .parent_id()
                        .and_then(|p| {
                            width_calculated_arena[p]
                                .$preferred_field
                                .max_available_space()
                        })
                        .unwrap_or(root_width);

                    last_relative_node.total()
                        - last_relative_node.$get_padding_fn(last_relative_node_parent_width)
                };

                children
                    .iter()
                    .map(|child_id| {
                        let parent_node_inner_width =
                            if layout_positions[*child_id] == LayoutPosition::Absolute {
                                last_relative_node_inner_width
                            } else {
                                parent_node_inner_width
                            };

                        let min_child_width = width_calculated_arena[*child_id].total(); // +
                                                                                         // width_calculated_arena[*child_id].
                                                                                         // $get_padding_fn(parent_node_inner_width);
                                                                                         // + margin(child)

                        let space_available = parent_node_inner_width - min_child_width;

                        // If the min width of the cross axis is larger than the parent width,
                        // overflow
                        if space_available <= 0.0
                            || layout_displays[*child_id]
                                .get_property()
                                .copied()
                                .unwrap_or_default()
                                != LayoutDisplay::Flex
                        {
                            // do not grow the item - no space to distribute
                            0.0
                        } else {
                            let preferred_width = match width_calculated_arena[*child_id]
                                .$preferred_field
                                .max_available_space()
                            {
                                Some(max_width) => parent_node_inner_width.min(max_width),
                                None => parent_node_inner_width,
                            };
                            // flex_grow the item so that (space_available + node.flex_grow_px) =
                            // preferred_width (= either max_width or parent_width)
                            preferred_width - min_child_width
                        }
                    })
                    .collect()
            }

            use azul_css::{LayoutAxis, LayoutPosition};

            // Set the window width on the root node (since there is only one root node, we can
            // calculate the `flex_grow_px` directly)
            //
            // Usually `top_level_flex_basis` is NOT 0.0, rather it's the sum of all widths in the
            // DOM, i.e. the sum of the whole DOM tree
            let top_level_flex_basis = node_data.as_ref()[NodeId::ZERO].min_inner_size_px;

            // The root node can still have some sort of max-width attached, so we need to check for
            // that
            let root_preferred_width = match node_data.as_ref()[NodeId::ZERO]
                .$preferred_field
                .max_available_space()
            {
                Some(max_width) => root_width.min(max_width),
                None => root_width,
            };

            node_data.as_ref_mut()[NodeId::ZERO].flex_grow_px =
                root_preferred_width - top_level_flex_basis;

            let mut parents_grouped_by_depth = BTreeMap::new();
            for ParentWithNodeDepth { depth, node_id } in node_depths.iter() {
                let parent_id = match node_id.into_crate_internal() {
                    Some(s) => s,
                    None => continue,
                };
                if !parents_to_recalc.contains(&parent_id) {
                    continue;
                }
                parents_grouped_by_depth
                    .entry(depth)
                    .or_insert_with(|| Vec::new())
                    .push(parent_id);
            }

            for (depth, parent_ids) in parents_grouped_by_depth {
                // reset the flex_grow to 0
                {
                    let mut node_data_mut = node_data.as_ref_mut();
                    for parent_id in parent_ids.iter() {
                        for child_id in parent_id.az_children(node_hierarchy) {
                            node_data_mut[child_id].flex_grow_px = 0.0;
                        }
                    }
                }

                // calculate the new flex_grow
                let flex_grows_in_this_depth = parent_ids
                    .iter()
                    .map(|parent_id| {
                        let children = parent_id.az_children_collect(&node_hierarchy);
                        let flex_axis = layout_directions[*parent_id].get_axis();

                        let result = if flex_axis == LayoutAxis::$main_axis {
                            distribute_space_along_main_axis(
                                &parent_id,
                                &children,
                                node_hierarchy,
                                layout_displays,
                                layout_flex_grows,
                                layout_positions,
                                &node_data.as_ref(),
                                root_width,
                            )
                        } else {
                            distribute_space_along_cross_axis(
                                &parent_id,
                                &children,
                                node_hierarchy,
                                layout_displays,
                                layout_positions,
                                &node_data.as_ref(),
                                root_width,
                            )
                        };

                        (parent_id, result)
                    })
                    .collect::<Vec<_>>();

                // write the new flex-grow values into the flex_grow_px
                {
                    let mut node_data_mut = node_data.as_ref_mut();
                    for (parent_id, flex_grows) in flex_grows_in_this_depth {
                        for (child_id, flex_grow_px) in parent_id
                            .az_children(node_hierarchy)
                            .zip(flex_grows.into_iter())
                        {
                            node_data_mut[child_id].flex_grow_px = flex_grow_px;
                        }
                    }
                }
            }
        }
    };
}

typed_arena!(
    WidthCalculatedRect,
    preferred_width,
    determine_preferred_width,
    width,
    get_horizontal_padding,
    get_horizontal_border,
    get_horizontal_margin,
    get_flex_basis_horizontal,
    width_calculated_rect_arena_from_rect_layout_arena,
    bubble_preferred_widths_to_parents,
    width_calculated_rect_arena_apply_flex_grow,
    Horizontal,
    margin_left,
    margin_right,
    padding_left,
    padding_right,
    border_left,
    border_right,
    left,
    right,
);

typed_arena!(
    HeightCalculatedRect,
    preferred_height,
    determine_preferred_height,
    height,
    get_vertical_padding,
    get_vertical_border,
    get_vertical_margin,
    get_flex_basis_vertical,
    height_calculated_rect_arena_from_rect_layout_arena,
    bubble_preferred_heights_to_parents,
    height_calculated_rect_arena_apply_flex_grow,
    Vertical,
    margin_top,
    margin_bottom,
    padding_top,
    padding_bottom,
    border_top,
    border_bottom,
    top,
    bottom,
);

/// Returns the solved widths of the items in a BTree form
pub(crate) fn solve_flex_layout_width<'a, 'b>(
    width_calculated_arena: &'a mut NodeDataContainer<WidthCalculatedRect>,
    layout_flex_grow: &NodeDataContainerRef<'a, f32>,
    layout_displays: &NodeDataContainerRef<'a, CssPropertyValue<LayoutDisplay>>,
    layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
    layout_directions: &NodeDataContainerRef<'a, LayoutFlexDirection>,
    node_hierarchy: &'b NodeDataContainerRef<'a, NodeHierarchyItem>,
    wh_configs: &NodeDataContainerRef<'a, WhConfig>,
    node_depths: &[ParentWithNodeDepth],
    window_width: f32,
    parents_to_recalc: &BTreeSet<NodeId>,
) {
    bubble_preferred_widths_to_parents(
        &mut width_calculated_arena.as_ref_mut(),
        node_hierarchy,
        layout_positions,
        layout_directions,
        wh_configs,
        node_depths,
        window_width,
    );
    width_calculated_rect_arena_apply_flex_grow(
        width_calculated_arena,
        node_hierarchy,
        layout_displays,
        layout_flex_grow,
        layout_positions,
        layout_directions,
        node_depths,
        window_width,
        parents_to_recalc,
    );
}

/// Returns the solved height of the items in a BTree form
pub(crate) fn solve_flex_layout_height<'a, 'b>(
    height_calculated_arena: &'a mut NodeDataContainer<HeightCalculatedRect>,
    layout_flex_grow: &NodeDataContainerRef<'a, f32>,
    layout_displays: &NodeDataContainerRef<'a, CssPropertyValue<LayoutDisplay>>,
    layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
    layout_directions: &NodeDataContainerRef<'a, LayoutFlexDirection>,
    node_hierarchy: &'b NodeDataContainerRef<'a, NodeHierarchyItem>,
    wh_configs: &NodeDataContainerRef<'a, WhConfig>,
    node_depths: &[ParentWithNodeDepth],
    window_height: f32,
    parents_to_recalc: &BTreeSet<NodeId>,
) {
    bubble_preferred_heights_to_parents(
        &mut height_calculated_arena.as_ref_mut(),
        node_hierarchy,
        layout_positions,
        layout_directions,
        wh_configs,
        node_depths,
        window_height,
    );
    height_calculated_rect_arena_apply_flex_grow(
        height_calculated_arena,
        node_hierarchy,
        layout_displays,
        layout_flex_grow,
        layout_positions,
        layout_directions,
        node_depths,
        window_height,
        parents_to_recalc,
    );
}

macro_rules! get_position {
    (
        $fn_name:ident,
        $width_layout:ident,
        $height_solved_position:ident,
        $solved_widths_field:ident,
        $left:ident,
        $right:ident,
        $margin_left:ident,
        $margin_right:ident,
        $get_padding_left:ident,
        $get_padding_right:ident,
        $axis:ident
    ) => {
        /// Traverses along the DOM and solve for the X or Y position
        fn $fn_name<'a>(
            arena: &mut NodeDataContainer<$height_solved_position>,
            node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
            layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
            layout_directions: &NodeDataContainerRef<'a, LayoutFlexDirection>,
            layout_justify_contents: &NodeDataContainerRef<'a, LayoutJustifyContent>,
            node_depths: &[ParentWithNodeDepth],
            solved_widths: &NodeDataContainerRef<'a, $width_layout>,
            parents_to_solve: &BTreeSet<NodeId>,
        ) {
            /// Returns the absolute X for the child
            fn determine_child_x_absolute<'a>(
                child_id: NodeId,
                solved_widths: &NodeDataContainerRef<'a, $width_layout>,
                layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
                node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
            ) -> f32 {
                let child_width_with_padding = {
                    let child_node = &solved_widths[child_id];
                    child_node.min_inner_size_px + child_node.flex_grow_px
                };

                let child_node = &solved_widths[child_id];
                let child_node_parent_width = node_hierarchy[child_id]
                    .parent_id()
                    .map(|p| solved_widths[p].total())
                    .unwrap_or(0.0) as f32;

                let child_right = child_node
                    .$right
                    .and_then(|s| Some(s.get_property()?.inner.to_pixels(child_node_parent_width)));

                if let Some(child_right) = child_right {
                    // align right / bottom of last relative parent
                    let child_margin_right = child_node
                        .$margin_right
                        .and_then(|x| {
                            Some(x.get_property()?.inner.to_pixels(child_node_parent_width))
                        })
                        .unwrap_or(0.0);

                    let last_relative_node_id = child_id
                        .get_nearest_matching_parent(node_hierarchy, |n| {
                            layout_positions[n].is_positioned()
                        })
                        .unwrap_or(NodeId::new(0));

                    let last_relative_node_outer_width =
                        &solved_widths[last_relative_node_id].total();

                    last_relative_node_outer_width
                        - child_width_with_padding
                        - child_margin_right
                        - child_right
                } else {
                    // align left / top of last relative parent
                    let child_left = child_node.$left.and_then(|s| {
                        Some(s.get_property()?.inner.to_pixels(child_node_parent_width))
                    });

                    let child_margin_left = child_node
                        .$margin_left
                        .and_then(|x| {
                            Some(x.get_property()?.inner.to_pixels(child_node_parent_width))
                        })
                        .unwrap_or(0.0);

                    child_margin_left + child_left.unwrap_or(0.0)
                }
            }

            // Returns the X for the child + the distance to add for the next child
            fn determine_child_x_along_main_axis<'a>(
                main_axis_alignment: LayoutJustifyContent,
                layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
                solved_widths: &NodeDataContainerRef<'a, $width_layout>,
                child_id: NodeId,
                parent_x_position: f32,
                parent_inner_width: f32,
                sum_x_of_children_so_far: &f32,
                node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
            ) -> (f32, f32) {
                use azul_css::LayoutJustifyContent::*;

                // total width of the child, including padding + border
                let child_width_with_padding = solved_widths[child_id].total();

                // width: increase X according to the main axis, Y according to the cross_axis
                let child_node = &solved_widths[child_id];
                let child_margin_left = child_node
                    .$margin_left
                    .and_then(|x| Some(x.get_property()?.inner.to_pixels(parent_inner_width)))
                    .unwrap_or(0.0);
                let child_margin_right = child_node
                    .$margin_right
                    .and_then(|x| Some(x.get_property()?.inner.to_pixels(parent_inner_width)))
                    .unwrap_or(0.0);

                if layout_positions[child_id] == LayoutPosition::Absolute {
                    (
                        determine_child_x_absolute(
                            child_id,
                            solved_widths,
                            layout_positions,
                            node_hierarchy,
                        ),
                        0.0,
                    )
                } else {
                    // X position of the top left corner
                    // WARNING: End has to be added after all children!
                    let x_of_top_left_corner = match main_axis_alignment {
                        Start | End => {
                            parent_x_position + *sum_x_of_children_so_far + child_margin_left
                        }
                        Center => {
                            parent_x_position
                                + ((parent_inner_width as f32 / 2.0)
                                    - ((*sum_x_of_children_so_far
                                        + child_margin_right
                                        + child_width_with_padding)
                                        as f32
                                        / 2.0))
                        }
                        SpaceBetween => {
                            parent_x_position // TODO!
                        }
                        SpaceAround => {
                            parent_x_position // TODO!
                        }
                        SpaceEvenly => {
                            parent_x_position // TODO!
                        }
                    };

                    (
                        x_of_top_left_corner,
                        child_margin_right + child_width_with_padding + child_margin_left,
                    )
                }
            }

            fn determine_child_x_along_cross_axis<'a>(
                layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
                solved_widths: &NodeDataContainerRef<'a, $width_layout>,
                child_id: NodeId,
                parent_x_position: f32,
                parent_inner_width: f32,
                node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
            ) -> f32 {
                let child_node = &solved_widths[child_id];

                let child_margin_left = child_node
                    .$margin_left
                    .and_then(|x| Some(x.get_property()?.inner.to_pixels(parent_inner_width)))
                    .unwrap_or(0.0);

                if layout_positions[child_id] == LayoutPosition::Absolute {
                    determine_child_x_absolute(
                        child_id,
                        solved_widths,
                        layout_positions,
                        node_hierarchy,
                    )
                } else {
                    parent_x_position + child_margin_left
                }
            }

            use azul_css::{LayoutAxis, LayoutJustifyContent::*};

            for ParentWithNodeDepth { depth: _, node_id } in node_depths.iter() {
                let parent_id = match node_id.into_crate_internal() {
                    Some(s) => s,
                    None => continue,
                };

                if !parents_to_solve.contains(&parent_id) {
                    continue;
                }

                let parent_node = &solved_widths[parent_id];
                let parent_parent_width = node_hierarchy[parent_id]
                    .parent_id()
                    .map(|p| solved_widths[p].total())
                    .unwrap_or(0.0) as f32;

                let parent_padding_left = parent_node.$get_padding_left(parent_parent_width);
                let parent_padding_right = parent_node.$get_padding_right(parent_parent_width);

                let parent_x_position = arena.as_ref()[parent_id].0 + parent_padding_left;
                let parent_direction = layout_directions[parent_id];

                let parent_inner_width =
                    { parent_node.total() - (parent_padding_left + parent_padding_right) };

                if parent_direction.get_axis() == LayoutAxis::$axis {
                    // Along main axis: Increase X with width of current element
                    let main_axis_alignment = layout_justify_contents[parent_id];
                    let mut sum_x_of_children_so_far = 0.0;

                    if parent_direction.is_reverse() {
                        for child_id in parent_id.az_reverse_children(node_hierarchy) {
                            let (x, x_to_add) = determine_child_x_along_main_axis(
                                main_axis_alignment,
                                layout_positions,
                                solved_widths,
                                child_id,
                                parent_x_position,
                                parent_inner_width,
                                &sum_x_of_children_so_far,
                                node_hierarchy,
                            );
                            arena.as_ref_mut()[child_id].0 = x;
                            sum_x_of_children_so_far += x_to_add;
                        }
                    } else {
                        for child_id in parent_id.az_children(node_hierarchy) {
                            let (x, x_to_add) = determine_child_x_along_main_axis(
                                main_axis_alignment,
                                layout_positions,
                                solved_widths,
                                child_id,
                                parent_x_position,
                                parent_inner_width,
                                &sum_x_of_children_so_far,
                                node_hierarchy,
                            );
                            arena.as_ref_mut()[child_id].0 = x;
                            sum_x_of_children_so_far += x_to_add;
                        }
                    }

                    // If the direction is `flex-end`, we can't add the X position during the
                    // iteration, so we have to "add" the diff to the parent_inner_width
                    // at the end
                    let should_align_towards_end = (parent_direction.is_reverse()
                        && main_axis_alignment == Start)
                        || (!parent_direction.is_reverse() && main_axis_alignment == End);

                    if should_align_towards_end {
                        let diff = parent_inner_width - sum_x_of_children_so_far;
                        for child_id in parent_id
                            .az_children(node_hierarchy)
                            .filter(|ch| layout_positions[*ch] != LayoutPosition::Absolute)
                        {
                            arena.as_ref_mut()[child_id].0 += diff;
                        }
                    }
                } else {
                    // Along cross axis: Take X of parent

                    if parent_direction.is_reverse() {
                        for child_id in parent_id.az_reverse_children(node_hierarchy) {
                            arena.as_ref_mut()[child_id].0 = determine_child_x_along_cross_axis(
                                layout_positions,
                                solved_widths,
                                child_id,
                                parent_x_position,
                                parent_inner_width,
                                node_hierarchy,
                            );
                        }
                    } else {
                        for child_id in parent_id.az_children(node_hierarchy) {
                            arena.as_ref_mut()[child_id].0 = determine_child_x_along_cross_axis(
                                layout_positions,
                                solved_widths,
                                child_id,
                                parent_x_position,
                                parent_inner_width,
                                node_hierarchy,
                            );
                        }
                    }
                }
            }
        }
    };
}

fn get_x_positions<'a>(
    arena: &mut NodeDataContainer<HorizontalSolvedPosition>,
    solved_widths: &NodeDataContainerRef<'a, WidthCalculatedRect>,
    node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
    layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
    layout_directions: &NodeDataContainerRef<'a, LayoutFlexDirection>,
    layout_justify_contents: &NodeDataContainerRef<'a, LayoutJustifyContent>,
    node_depths: &[ParentWithNodeDepth],
    origin: LogicalPosition,
    parents_to_solve: &BTreeSet<NodeId>,
) {
    get_position!(
        get_pos_x,
        WidthCalculatedRect,
        HorizontalSolvedPosition,
        solved_widths,
        left,
        right,
        margin_left,
        margin_right,
        get_padding_left,
        get_padding_right,
        Horizontal
    );

    get_pos_x(
        arena,
        node_hierarchy,
        layout_positions,
        layout_directions,
        layout_justify_contents,
        node_depths,
        solved_widths,
        &parents_to_solve,
    );

    // Add the origin on top of the position
    for item in arena.internal.iter_mut() {
        item.0 += origin.x;
    }
}

fn get_y_positions<'a>(
    arena: &mut NodeDataContainer<VerticalSolvedPosition>,
    solved_heights: &NodeDataContainerRef<'a, HeightCalculatedRect>,
    node_hierarchy: &NodeDataContainerRef<'a, NodeHierarchyItem>,
    layout_positions: &NodeDataContainerRef<'a, LayoutPosition>,
    layout_directions: &NodeDataContainerRef<'a, LayoutFlexDirection>,
    layout_justify_contents: &NodeDataContainerRef<'a, LayoutJustifyContent>,
    node_depths: &[ParentWithNodeDepth],
    origin: LogicalPosition,
    parents_to_solve: &BTreeSet<NodeId>,
) {
    get_position!(
        get_pos_y,
        HeightCalculatedRect,
        VerticalSolvedPosition,
        solved_heights,
        top,
        bottom,
        margin_top,
        margin_bottom,
        get_padding_top,
        get_padding_bottom,
        Vertical
    );

    get_pos_y(
        arena,
        node_hierarchy,
        layout_positions,
        layout_directions,
        layout_justify_contents,
        node_depths,
        solved_heights,
        &parents_to_solve,
    );

    // Add the origin on top of the position
    for item in arena.internal.iter_mut() {
        item.0 += origin.y;
    }
}

#[inline]
pub fn get_layout_positions<'a>(styled_dom: &StyledDom) -> NodeDataContainer<LayoutPosition> {
    let cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    assert!(node_data_container.internal.len() == styled_nodes.internal.len()); // elide bounds checking
    NodeDataContainer {
        internal: styled_nodes
            .internal
            .iter()
            .enumerate()
            .map(|(node_id, styled_node)| {
                cache
                    .get_position(
                        &node_data_container.internal[node_id],
                        &NodeId::new(node_id),
                        &styled_node.state,
                    )
                    .cloned()
                    .unwrap_or_default()
                    .get_property_or_default()
                    .unwrap_or_default()
            })
            .collect(),
    }
}

#[inline]
pub fn get_layout_justify_contents<'a>(
    styled_dom: &StyledDom,
) -> NodeDataContainer<LayoutJustifyContent> {
    let cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    assert!(node_data_container.internal.len() == styled_nodes.internal.len()); // elide bounds checking

    NodeDataContainer {
        internal: styled_nodes
            .internal
            .iter()
            .enumerate()
            .map(|(node_id, styled_node)| {
                cache
                    .get_justify_content(
                        &node_data_container.internal[node_id],
                        &NodeId::new(node_id),
                        &styled_node.state,
                    )
                    .cloned()
                    .unwrap_or_default()
                    .get_property_or_default()
                    .unwrap_or_default()
            })
            .collect(),
    }
}

#[inline]
pub fn get_layout_flex_directions<'a>(
    styled_dom: &StyledDom,
) -> NodeDataContainer<LayoutFlexDirection> {
    let cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    assert!(node_data_container.internal.len() == styled_nodes.internal.len()); // elide bounds checking

    NodeDataContainer {
        internal: styled_nodes
            .internal
            .iter()
            .enumerate()
            .map(|(node_id, styled_node)| {
                cache
                    .get_flex_direction(
                        &node_data_container.internal[node_id],
                        &NodeId::new(node_id),
                        &styled_node.state,
                    )
                    .cloned()
                    .unwrap_or_default()
                    .get_property_or_default()
                    .unwrap_or_default()
            })
            .collect(),
    }
}

#[inline]
pub fn get_layout_flex_grows<'a>(styled_dom: &StyledDom) -> NodeDataContainer<f32> {
    // Prevent flex-grow and flex-shrink to be less than 0
    let cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    assert!(node_data_container.internal.len() == styled_nodes.internal.len()); // elide bounds checking

    NodeDataContainer {
        internal: styled_nodes
            .internal
            .iter()
            .enumerate()
            .map(|(node_id, styled_node)| {
                cache
                    .get_flex_grow(
                        &node_data_container.internal[node_id],
                        &NodeId::new(node_id),
                        &styled_node.state,
                    )
                    .and_then(|g| g.get_property().copied())
                    .and_then(|grow| Some(grow.inner.get().max(0.0)))
                    .unwrap_or(DEFAULT_FLEX_GROW_FACTOR)
            })
            .collect(),
    }
}

#[inline]
pub fn get_layout_displays<'a>(
    styled_dom: &StyledDom,
) -> NodeDataContainer<CssPropertyValue<LayoutDisplay>> {
    // Prevent flex-grow and flex-shrink to be less than 0
    let cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    assert!(node_data_container.internal.len() == styled_nodes.internal.len()); // elide bounds checking

    NodeDataContainer {
        internal: styled_nodes
            .internal
            .iter()
            .enumerate()
            .map(|(node_id, styled_node)| {
                cache
                    .get_display(
                        &node_data_container.internal[node_id],
                        &NodeId::new(node_id),
                        &styled_node.state,
                    )
                    .copied()
                    .unwrap_or(CssPropertyValue::Auto)
            })
            .collect(),
    }
}

fn precalculate_all_offsets(styled_dom: &StyledDom) -> NodeDataContainer<AllOffsets> {
    let css_property_cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    assert!(styled_nodes.internal.len() == node_data_container.internal.len()); // elide bounds check

    NodeDataContainer {
        internal: styled_nodes
            .internal
            .iter()
            .enumerate()
            .map(|(node_id_usize, styled_node)| {
                let node_id = NodeId::new(node_id_usize);
                let state = &styled_node.state;
                precalculate_offset(
                    &node_data_container.internal[node_id_usize],
                    &css_property_cache,
                    &node_id,
                    state,
                )
            })
            .collect(),
    }
}

struct AllOffsets {
    position: LayoutAbsolutePositions,
    border_widths: LayoutBorderOffsets,
    padding: LayoutPaddingOffsets,
    margin: LayoutMarginOffsets,
    box_shadow: StyleBoxShadowOffsets,
    box_sizing: LayoutBoxSizing,
    overflow_x: LayoutOverflow,
    overflow_y: LayoutOverflow,
}

fn precalculate_offset(
    node_data: &NodeData,
    css_property_cache: &CssPropertyCache,
    node_id: &NodeId,
    state: &StyledNodeState,
) -> AllOffsets {
    AllOffsets {
        border_widths: LayoutBorderOffsets {
            left: css_property_cache
                .get_border_left_width(node_data, node_id, state)
                .cloned(),
            right: css_property_cache
                .get_border_right_width(node_data, node_id, state)
                .cloned(),
            top: css_property_cache
                .get_border_top_width(node_data, node_id, state)
                .cloned(),
            bottom: css_property_cache
                .get_border_bottom_width(node_data, node_id, state)
                .cloned(),
        },
        padding: LayoutPaddingOffsets {
            left: css_property_cache
                .get_padding_left(node_data, node_id, state)
                .cloned(),
            right: css_property_cache
                .get_padding_right(node_data, node_id, state)
                .cloned(),
            top: css_property_cache
                .get_padding_top(node_data, node_id, state)
                .cloned(),
            bottom: css_property_cache
                .get_padding_bottom(node_data, node_id, state)
                .cloned(),
        },
        margin: LayoutMarginOffsets {
            left: css_property_cache
                .get_margin_left(node_data, node_id, state)
                .cloned(),
            right: css_property_cache
                .get_margin_right(node_data, node_id, state)
                .cloned(),
            top: css_property_cache
                .get_margin_top(node_data, node_id, state)
                .cloned(),
            bottom: css_property_cache
                .get_margin_bottom(node_data, node_id, state)
                .cloned(),
        },
        box_shadow: StyleBoxShadowOffsets {
            left: css_property_cache
                .get_box_shadow_left(node_data, node_id, state)
                .cloned(),
            right: css_property_cache
                .get_box_shadow_right(node_data, node_id, state)
                .cloned(),
            top: css_property_cache
                .get_box_shadow_top(node_data, node_id, state)
                .cloned(),
            bottom: css_property_cache
                .get_box_shadow_bottom(node_data, node_id, state)
                .cloned(),
        },
        position: LayoutAbsolutePositions {
            left: css_property_cache
                .get_left(node_data, node_id, state)
                .cloned(),
            right: css_property_cache
                .get_right(node_data, node_id, state)
                .cloned(),
            top: css_property_cache
                .get_top(node_data, node_id, state)
                .cloned(),
            bottom: css_property_cache
                .get_bottom(node_data, node_id, state)
                .cloned(),
        },
        box_sizing: css_property_cache
            .get_box_sizing(node_data, node_id, state)
            .cloned()
            .unwrap_or_default()
            .get_property()
            .copied()
            .unwrap_or_default(),
        overflow_x: css_property_cache
            .get_overflow_x(node_data, node_id, state)
            .cloned()
            .unwrap_or_default()
            .get_property()
            .copied()
            .unwrap_or_default(),
        overflow_y: css_property_cache
            .get_overflow_y(node_data, node_id, state)
            .cloned()
            .unwrap_or_default()
            .get_property()
            .copied()
            .unwrap_or_default(),
    }
}

struct LayoutAbsolutePositions {
    left: Option<CssPropertyValue<LayoutLeft>>,
    right: Option<CssPropertyValue<LayoutRight>>,
    top: Option<CssPropertyValue<LayoutTop>>,
    bottom: Option<CssPropertyValue<LayoutBottom>>,
}

struct LayoutBorderOffsets {
    left: Option<CssPropertyValue<LayoutBorderLeftWidth>>,
    right: Option<CssPropertyValue<LayoutBorderRightWidth>>,
    top: Option<CssPropertyValue<LayoutBorderTopWidth>>,
    bottom: Option<CssPropertyValue<LayoutBorderBottomWidth>>,
}

impl LayoutBorderOffsets {
    fn resolve(&self, parent_scale_x: f32, parent_scale_y: f32) -> ResolvedOffsets {
        ResolvedOffsets {
            left: self
                .left
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_x)))
                .unwrap_or_default(),
            top: self
                .top
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_y)))
                .unwrap_or_default(),
            bottom: self
                .bottom
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_y)))
                .unwrap_or_default(),
            right: self
                .right
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_x)))
                .unwrap_or_default(),
        }
    }
}

struct LayoutPaddingOffsets {
    left: Option<CssPropertyValue<LayoutPaddingLeft>>,
    right: Option<CssPropertyValue<LayoutPaddingRight>>,
    top: Option<CssPropertyValue<LayoutPaddingTop>>,
    bottom: Option<CssPropertyValue<LayoutPaddingBottom>>,
}

impl LayoutPaddingOffsets {
    fn resolve(&self, parent_scale_x: f32, parent_scale_y: f32) -> ResolvedOffsets {
        ResolvedOffsets {
            left: self
                .left
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_x)))
                .unwrap_or_default(),
            top: self
                .top
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_y)))
                .unwrap_or_default(),
            bottom: self
                .bottom
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_y)))
                .unwrap_or_default(),
            right: self
                .right
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_x)))
                .unwrap_or_default(),
        }
    }
}

struct LayoutMarginOffsets {
    left: Option<CssPropertyValue<LayoutMarginLeft>>,
    right: Option<CssPropertyValue<LayoutMarginRight>>,
    top: Option<CssPropertyValue<LayoutMarginTop>>,
    bottom: Option<CssPropertyValue<LayoutMarginBottom>>,
}

impl LayoutMarginOffsets {
    fn resolve(&self, parent_scale_x: f32, parent_scale_y: f32) -> ResolvedOffsets {
        ResolvedOffsets {
            left: self
                .left
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_x)))
                .unwrap_or_default(),
            top: self
                .top
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_y)))
                .unwrap_or_default(),
            bottom: self
                .bottom
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_y)))
                .unwrap_or_default(),
            right: self
                .right
                .and_then(|p| Some(p.get_property()?.inner.to_pixels(parent_scale_x)))
                .unwrap_or_default(),
        }
    }
}

struct NewIframeScrollState {
    dom_id: DomId,
    node_id: NodeId,
    child_rect: LogicalRect,
    virtual_child_rect: LogicalRect,
}

// Adds the image and font resources to the app_resources but does NOT add them to the RenderAPI
#[cfg(feature = "text_layout")]
pub fn do_the_layout(
    styled_dom: StyledDom,
    image_cache: &ImageCache,
    fc_cache: &FcFontCache,
    renderer_resources: &mut RendererResources,
    current_window_dpi: DpiScaleFactor,
    all_resource_updates: &mut Vec<ResourceUpdate>,
    id_namespace: IdNamespace,
    document_id: &DocumentId,
    epoch: Epoch,
    callbacks: &RenderCallbacks,
    full_window_state: &FullWindowState,
) -> Vec<LayoutResult> {
    use azul_core::{
        callbacks::{HidpiAdjustedBounds, IFrameCallbackInfo, IFrameCallbackReturn},
        styled_dom::NodeHierarchyItemId,
        ui_solver::OverflowingScrollNode,
    };

    let window_theme = full_window_state.theme;
    let mut current_dom_id = 0;
    let mut doms = vec![(
        None,
        DomId {
            inner: current_dom_id,
        },
        styled_dom,
        LogicalRect::new(LogicalPosition::zero(), full_window_state.size.dimensions),
    )];
    let mut resolved_doms = Vec::new();
    let mut new_scroll_states = Vec::new();

    loop {
        let mut new_doms = Vec::new();

        for (parent_dom_id, dom_id, styled_dom, rect) in doms.drain(..) {
            use azul_core::app_resources::add_fonts_and_images;

            add_fonts_and_images(
                image_cache,
                renderer_resources,
                current_window_dpi,
                fc_cache,
                id_namespace,
                epoch,
                document_id,
                all_resource_updates,
                &styled_dom,
                callbacks.load_font_fn,
                callbacks.parse_font_fn,
                callbacks.insert_into_active_gl_textures_fn,
            );

            let mut layout_result = do_the_layout_internal(
                dom_id,
                parent_dom_id,
                styled_dom,
                renderer_resources,
                document_id,
                rect,
            );

            let mut iframe_mapping = BTreeMap::new();

            for iframe_node_id in layout_result.styled_dom.scan_for_iframe_callbacks() {
                // Generate a new DomID
                current_dom_id += 1;
                let iframe_dom_id = DomId {
                    inner: current_dom_id,
                };
                iframe_mapping.insert(iframe_node_id, iframe_dom_id);

                let bounds = &layout_result.rects.as_ref()[iframe_node_id];
                let bounds_size = LayoutSize::new(
                    bounds.size.width.round() as isize,
                    bounds.size.height.round() as isize,
                );
                let hidpi_bounds = HidpiAdjustedBounds::from_bounds(
                    bounds_size,
                    full_window_state.size.get_hidpi_factor(),
                );

                // Invoke the IFrame callback
                let iframe_return: IFrameCallbackReturn = {
                    let mut iframe_callback_info = IFrameCallbackInfo::new(
                        fc_cache,
                        image_cache,
                        window_theme,
                        hidpi_bounds,
                        // TODO - see /examples/assets/images/scrollbounds.png for documentation!
                        /* scroll_size */
                        bounds.size,
                        /* scroll_offset */ LogicalPosition::zero(),
                        /* virtual_scroll_size */ bounds.size,
                        /* virtual_scroll_offset */ LogicalPosition::zero(),
                    );

                    let mut node_data_mut = layout_result.styled_dom.node_data.as_container_mut();
                    match &mut node_data_mut[iframe_node_id].get_iframe_node() {
                        Some(iframe_node) => (iframe_node.callback.cb)(
                            &mut iframe_node.data,
                            &mut iframe_callback_info,
                        ),
                        None => IFrameCallbackReturn::default(),
                    }
                };

                let IFrameCallbackReturn {
                    dom,
                    scroll_size,
                    scroll_offset,
                    virtual_scroll_size,
                    virtual_scroll_offset,
                } = iframe_return;

                let mut iframe_dom = dom;
                let (scroll_node_id, scroll_dom_id) = match parent_dom_id {
                    Some(s) => (iframe_node_id, s),
                    None => (NodeId::ZERO, DomId { inner: 0 }),
                };

                // layout_result.scrollable_nodes.get();
                // parent_dom_id

                // TODO: use other fields of iframe_return here!

                let hovered_nodes = full_window_state
                    .last_hit_test
                    .hovered_nodes
                    .get(&iframe_dom_id)
                    .map(|i| i.regular_hit_test_nodes.clone())
                    .unwrap_or_default()
                    .keys()
                    .cloned()
                    .collect::<Vec<_>>();

                let active_nodes = if !full_window_state.mouse_state.mouse_down() {
                    Vec::new()
                } else {
                    hovered_nodes.clone()
                };

                let _ = iframe_dom.restyle_nodes_hover(hovered_nodes.as_slice(), true);
                let _ = iframe_dom.restyle_nodes_active(active_nodes.as_slice(), true);
                if let Some(focused_node) = full_window_state.focused_node {
                    if focused_node.dom == iframe_dom_id {
                        let _ = iframe_dom.restyle_nodes_focus(
                            &[focused_node.node.into_crate_internal().unwrap()],
                            true,
                        );
                    }
                }

                // TODO: use the iframe static position here?
                let bounds =
                    LogicalRect::new(LogicalPosition::zero(), hidpi_bounds.get_logical_size());

                // push the styled iframe dom into the next iframes and repeat (recurse)
                new_doms.push((Some(dom_id), iframe_dom_id, iframe_dom, bounds));
                new_scroll_states.push(NewIframeScrollState {
                    dom_id: scroll_dom_id,
                    node_id: scroll_node_id,
                    child_rect: LogicalRect {
                        origin: scroll_offset,
                        size: scroll_size,
                    },
                    virtual_child_rect: LogicalRect {
                        origin: virtual_scroll_offset,
                        size: virtual_scroll_size,
                    },
                });
            }

            layout_result.iframe_mapping = iframe_mapping;
            resolved_doms.push(layout_result);
        }

        if new_doms.is_empty() {
            break;
        } else {
            doms = new_doms;
        }
    }

    for nss in new_scroll_states {
        if let Some(lr) = resolved_doms.get_mut(nss.dom_id.inner) {
            let mut osn = lr
                .scrollable_nodes
                .overflowing_nodes
                .entry(NodeHierarchyItemId::from_crate_internal(Some(nss.node_id)))
                .or_insert_with(|| OverflowingScrollNode::default());

            osn.child_rect = nss.child_rect;
            osn.virtual_child_rect = nss.virtual_child_rect;
        }
    }

    resolved_doms
}

/// At this point in time, all font keys, image keys, etc. have to be already
/// been submitted to the RenderApi and the AppResources!
#[cfg(feature = "text_layout")]
pub fn do_the_layout_internal(
    dom_id: DomId,
    parent_dom_id: Option<DomId>,
    mut styled_dom: StyledDom,
    renderer_resources: &mut RendererResources,
    document_id: &DocumentId,
    bounds: LogicalRect,
) -> LayoutResult {
    use azul_core::app_resources::DecodedImage;

    let rect_size = bounds.size;
    let rect_offset = bounds.origin;

    // TODO: Filter all inline text blocks: inline blocks + their padding + margin
    // The NodeId has to be the **next** NodeId (the next sibling after the inline element)
    // let mut inline_text_blocks = BTreeMap::<NodeId, InlineText>::new();

    let all_parents_btreeset = styled_dom
        .non_leaf_nodes
        .iter()
        .filter_map(|p| Some(p.node_id.into_crate_internal()?))
        .collect::<BTreeSet<_>>();

    let layout_position_info = get_layout_positions(&styled_dom);
    let layout_flex_grow_info = get_layout_flex_grows(&styled_dom);
    let layout_display_info = get_layout_displays(&styled_dom);
    let layout_directions_info = get_layout_flex_directions(&styled_dom);
    let layout_justify_contents = get_layout_justify_contents(&styled_dom);
    let layout_offsets = precalculate_all_offsets(&styled_dom);
    let layout_width_heights = precalculate_wh_config(&styled_dom);

    // Break all strings into words and / or resolve the TextIds
    let word_cache = create_word_cache(&styled_dom.node_data.as_container());
    // Scale the words to the correct size - TODO: Cache this in the app_resources!
    let shaped_words = create_shaped_words(renderer_resources, &word_cache, &styled_dom);

    let all_nodes_btreeset = (0..styled_dom.node_data.as_container().len())
        .map(|n| NodeId::new(n))
        .collect::<BTreeSet<_>>();

    // same as all_nodes_btreeset, but only for the words
    let display_none_nodes = get_display_none_nodes(
        &styled_dom.node_hierarchy.as_container(),
        &layout_display_info.as_ref(),
    );
    let all_word_nodes_btreeset = (0..styled_dom.node_data.as_container().len())
        .filter(|n| !display_none_nodes[*n]) // if the word block is marked as display:none, ignore
        .map(|n| NodeId::new(n)).collect::<BTreeSet<_>>();

    // Layout all words as if there was no max-width constraint
    // (to get the texts "content width").
    let mut word_positions_no_max_width = BTreeMap::new();
    create_word_positions(
        &mut word_positions_no_max_width,
        &all_word_nodes_btreeset,
        renderer_resources,
        &word_cache,
        &shaped_words,
        &styled_dom,
        None,
    );

    // Calculate the optional "intrinsic content widths" - i.e.
    // the width of a text or image, if no constraint would apply
    let mut content_widths_pre = styled_dom
        .node_data
        .as_container_mut()
        .transform_multithread(|node_data, node_id| {
            if display_none_nodes[node_id.index()] {
                None
            } else {
                match node_data.get_node_type() {
                    NodeType::Image(i) => match i.get_data() {
                        DecodedImage::NullImage { width, .. } => Some(*width as f32),
                        DecodedImage::Gl(tex) => Some(tex.size.width as f32),
                        DecodedImage::Raw((desc, _)) => Some(desc.width as f32),
                        _ => None,
                    },
                    _ => None,
                }
            }
        });

    for (node_id, word_positions) in word_positions_no_max_width.iter() {
        content_widths_pre.as_ref_mut()[*node_id] = Some(word_positions.0.content_size.width);
    }

    let mut width_calculated_arena = width_calculated_rect_arena_from_rect_layout_arena(
        &layout_width_heights.as_ref(),
        &layout_offsets.as_ref(),
        &content_widths_pre.as_ref(),
        &styled_dom.node_hierarchy.as_container(),
        &styled_dom.non_leaf_nodes.as_ref(),
        rect_size.width,
    );

    display_none_nodes
        .iter()
        .zip(width_calculated_arena.as_ref_mut().internal.iter_mut())
        .for_each(|(display_none, width)| {
            if *display_none {
                *width = WidthCalculatedRect::default();
            }
        });

    solve_flex_layout_width(
        &mut width_calculated_arena,
        &layout_flex_grow_info.as_ref(),
        &layout_display_info.as_ref(),
        &layout_position_info.as_ref(),
        &layout_directions_info.as_ref(),
        &styled_dom.node_hierarchy.as_container(),
        &layout_width_heights.as_ref(),
        styled_dom.non_leaf_nodes.as_ref(),
        rect_size.width,
        &all_parents_btreeset,
    );

    // If the flex grow / max-width step has caused the text block
    // to shrink in width, it needs to recalculate its height
    let word_blocks_to_recalculate = word_positions_no_max_width
        .iter()
        .filter_map(|(node_id, word_positions)| {
            let parent_id = styled_dom.node_hierarchy.as_container()[*node_id]
                .parent_id()
                .unwrap_or(NodeId::ZERO);
            if width_calculated_arena.as_ref()[*node_id].total()
                < word_positions.0.content_size.width
            {
                Some(*node_id)
            // if the text content overflows the parent width, we also need to recalculate
            } else if width_calculated_arena.as_ref()[*node_id].total()
                > width_calculated_arena.as_ref()[parent_id].total()
            {
                Some(*node_id)
            } else {
                None
            }
        })
        .collect::<BTreeSet<_>>();

    // Recalculate the height of the content blocks for the word blocks that need it
    create_word_positions(
        &mut word_positions_no_max_width,
        &word_blocks_to_recalculate,
        renderer_resources,
        &word_cache,
        &shaped_words,
        &styled_dom,
        Some(&width_calculated_arena.as_ref()),
    );
    let word_positions_with_max_width = word_positions_no_max_width;

    // Calculate the content height of the (text / image) content based on its width
    let mut content_heights_pre = styled_dom
        .node_data
        .as_container_mut()
        .transform_multithread(|node_data, node_id| {
            let (raw_width, raw_height) = if display_none_nodes[node_id.index()] {
                None
            } else {
                match node_data.get_node_type() {
                    NodeType::Image(i) => match i.get_data() {
                        DecodedImage::NullImage { width, height, .. } => {
                            Some((*width as f32, *height as f32))
                        }
                        DecodedImage::Gl(tex) => {
                            Some((tex.size.width as f32, tex.size.height as f32))
                        }
                        DecodedImage::Raw((desc, _)) => {
                            Some((desc.width as f32, desc.height as f32))
                        }
                        _ => None,
                    },
                    _ => None,
                }
            }?;

            let current_width = width_calculated_arena.as_ref()[node_id].total();

            // preserve aspect ratio
            Some(raw_height / raw_width * current_width)
        });
    for (node_id, word_positions) in word_positions_with_max_width.iter() {
        content_heights_pre.as_ref_mut()[*node_id] = Some(word_positions.0.content_size.height);
    }

    // TODO: The content height is not the final height!
    let mut height_calculated_arena = height_calculated_rect_arena_from_rect_layout_arena(
        &layout_width_heights.as_ref(),
        &layout_offsets.as_ref(),
        &content_heights_pre.as_ref(),
        &styled_dom.node_hierarchy.as_container(),
        &styled_dom.non_leaf_nodes.as_ref(),
        rect_size.height,
    );

    display_none_nodes
        .iter()
        .zip(height_calculated_arena.as_ref_mut().internal.iter_mut())
        .for_each(|(display_none, height)| {
            if *display_none {
                *height = HeightCalculatedRect::default();
            }
        });

    solve_flex_layout_height(
        &mut height_calculated_arena,
        &layout_flex_grow_info.as_ref(),
        &layout_display_info.as_ref(),
        &layout_position_info.as_ref(),
        &layout_directions_info.as_ref(),
        &styled_dom.node_hierarchy.as_container(),
        &layout_width_heights.as_ref(),
        styled_dom.non_leaf_nodes.as_ref(),
        rect_size.height,
        &all_parents_btreeset,
    );

    let mut x_positions = NodeDataContainer {
        internal: vec![HorizontalSolvedPosition(0.0); styled_dom.node_data.len()].into(),
    };

    get_x_positions(
        &mut x_positions,
        &width_calculated_arena.as_ref(),
        &styled_dom.node_hierarchy.as_container(),
        &layout_position_info.as_ref(),
        &layout_directions_info.as_ref(),
        &layout_justify_contents.as_ref(),
        &styled_dom.non_leaf_nodes.as_ref(),
        rect_offset.clone(),
        &all_parents_btreeset,
    );

    let mut y_positions = NodeDataContainer {
        internal: vec![VerticalSolvedPosition(0.0); styled_dom.node_data.as_ref().len()].into(),
    };

    get_y_positions(
        &mut y_positions,
        &height_calculated_arena.as_ref(),
        &styled_dom.node_hierarchy.as_container(),
        &layout_position_info.as_ref(),
        &layout_directions_info.as_ref(),
        &layout_justify_contents.as_ref(),
        &styled_dom.non_leaf_nodes.as_ref(),
        rect_offset,
        &all_parents_btreeset,
    );

    let mut positioned_rects = NodeDataContainer {
        internal: vec![PositionedRectangle::default(); styled_dom.node_data.len()].into(),
    };
    let nodes_that_updated_positions = all_nodes_btreeset.clone();
    let nodes_that_need_to_redraw_text = all_nodes_btreeset.clone();

    position_nodes(
        &mut positioned_rects.as_ref_mut(),
        &styled_dom,
        AllOffsetsProvider::All(&layout_offsets.as_ref()),
        &width_calculated_arena.as_ref(),
        &height_calculated_arena.as_ref(),
        &x_positions.as_ref(),
        &y_positions.as_ref(),
        &nodes_that_updated_positions,
        &nodes_that_need_to_redraw_text,
        &layout_position_info.as_ref(),
        &word_cache,
        &shaped_words,
        &word_positions_with_max_width,
        document_id,
    );

    let mut overflowing_rects = ScrolledNodes::default();
    get_nodes_that_need_scroll_clip(
        &mut overflowing_rects,
        &styled_dom.styled_nodes.as_container(),
        &styled_dom.node_data.as_container(),
        &styled_dom.node_hierarchy.as_container(),
        &positioned_rects.as_ref(),
        styled_dom.non_leaf_nodes.as_ref(),
        dom_id,
        document_id,
    );

    let mut gpu_value_cache = GpuValueCache::empty();
    let _ = gpu_value_cache.synchronize(&positioned_rects.as_ref(), &styled_dom);

    LayoutResult {
        dom_id,
        parent_dom_id,
        styled_dom,
        root_size: LayoutSize::new(
            rect_size.width.round() as isize,
            rect_size.height.round() as isize,
        ),
        root_position: LayoutPoint::new(
            rect_offset.x.round() as isize,
            rect_offset.y.round() as isize,
        ),
        preferred_widths: content_widths_pre,
        preferred_heights: content_heights_pre,
        width_calculated_rects: width_calculated_arena,
        height_calculated_rects: height_calculated_arena,
        solved_pos_x: x_positions,
        solved_pos_y: y_positions,
        layout_displays: layout_display_info,
        layout_flex_grows: layout_flex_grow_info,
        layout_positions: layout_position_info,
        layout_flex_directions: layout_directions_info,
        layout_justify_contents,
        rects: positioned_rects,
        words_cache: word_cache,
        shaped_words_cache: shaped_words,
        positioned_words_cache: word_positions_with_max_width,
        scrollable_nodes: overflowing_rects,
        iframe_mapping: BTreeMap::new(),
        gpu_value_cache,
    }
}

/// resets the preferred width / height to 0px before the layout is calculate
fn get_display_none_nodes<'a, 'b>(
    node_hierarchy: &'b NodeDataContainerRef<'a, NodeHierarchyItem>,
    layout_displays: &NodeDataContainerRef<'a, CssPropertyValue<LayoutDisplay>>,
) -> Vec<bool> {
    let mut items_that_should_be_set_to_zero = vec![false; layout_displays.internal.len()];
    if layout_displays.internal.is_empty() || layout_displays.internal.len() != node_hierarchy.len()
    {
        return items_that_should_be_set_to_zero;
    }

    let mut current = 0;
    while current < items_that_should_be_set_to_zero.len() {
        let display = layout_displays.internal[current].clone();

        if display == CssPropertyValue::None
            || display == CssPropertyValue::Exact(LayoutDisplay::None)
        {
            items_that_should_be_set_to_zero[current] = true;

            // set all children as display:none
            let subtree_len = node_hierarchy.subtree_len(NodeId::new(current));
            for child_id in current..=(current + subtree_len) {
                items_that_should_be_set_to_zero[child_id] = true;
            }

            current += subtree_len + 1;
        } else {
            current += 1;
        }
    }

    items_that_should_be_set_to_zero
}

/// Note: because this function is called both on layout() and relayout(),
/// the offsets are calculated during the layout() run. However,
/// we don't want to store all offsets because that would waste memory
///
/// So you can EITHER specify all offsets (useful during layout()) or specify
/// only the offsets of nodes that need to be recalculated (useful during relayout())
///
/// If an offset isn't found (usually shouldn't happen), the final positioned
/// rectangle is not positioned.
enum AllOffsetsProvider<'a> {
    All(&'a NodeDataContainerRef<'a, AllOffsets>),
    OnlyRecalculatedNodes(&'a BTreeMap<NodeId, AllOffsets>),
}

impl<'a> AllOffsetsProvider<'a> {
    fn get_offsets_for_node(&self, node_id: &NodeId) -> Option<&AllOffsets> {
        match self {
            AllOffsetsProvider::All(a) => Some(&a[*node_id]),
            AllOffsetsProvider::OnlyRecalculatedNodes(b) => b.get(node_id),
        }
    }
}

fn position_nodes<'a>(
    positioned_rects: &mut NodeDataContainerRefMut<'a, PositionedRectangle>,
    styled_dom: &StyledDom,
    offsets: AllOffsetsProvider<'a>,
    solved_widths: &NodeDataContainerRef<'a, WidthCalculatedRect>,
    solved_heights: &NodeDataContainerRef<'a, HeightCalculatedRect>,
    x_positions: &NodeDataContainerRef<'a, HorizontalSolvedPosition>,
    y_positions: &NodeDataContainerRef<'a, VerticalSolvedPosition>,
    nodes_that_updated_positions: &BTreeSet<NodeId>,
    nodes_that_need_to_redraw_text: &BTreeSet<NodeId>,
    position_info: &NodeDataContainerRef<'a, LayoutPosition>,
    word_cache: &BTreeMap<NodeId, Words>,
    shaped_words: &BTreeMap<NodeId, ShapedWords>,
    word_positions: &BTreeMap<NodeId, (WordPositions, FontInstanceKey)>,
    document_id: &DocumentId,
) {
    use azul_core::ui_solver::PositionInfo;

    let mut positioned_node_stack = vec![NodeId::new(0)];
    let css_property_cache = styled_dom.get_css_property_cache();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    let node_hierarchy = &styled_dom.node_hierarchy.as_container();

    // create the final positioned rectangles
    for ParentWithNodeDepth { depth: _, node_id } in styled_dom.non_leaf_nodes.as_ref().iter() {
        let parent_node_id = match node_id.into_crate_internal() {
            Some(s) => s,
            None => continue,
        };
        if !nodes_that_updated_positions.contains(&parent_node_id) {
            continue;
        };

        let parent_position = position_info[parent_node_id];
        let width = solved_widths[parent_node_id];
        let height = solved_heights[parent_node_id];
        let x_pos = x_positions[parent_node_id].0;
        let y_pos = y_positions[parent_node_id].0;

        let parent_parent_node_id = node_hierarchy[parent_node_id]
            .parent_id()
            .unwrap_or(NodeId::new(0));
        let parent_x_pos = x_positions[parent_parent_node_id].0;
        let parent_y_pos = y_positions[parent_parent_node_id].0;
        let parent_parent_width = solved_widths[parent_parent_node_id];
        let parent_parent_height = solved_heights[parent_parent_node_id];

        let last_positioned_item_node_id = positioned_node_stack
            .last()
            .map(|l| *l)
            .unwrap_or(NodeId::new(0));
        let last_positioned_item_x_pos = x_positions[last_positioned_item_node_id].0;
        let last_positioned_item_y_pos = y_positions[last_positioned_item_node_id].0;
        let parent_position_info = match parent_position {
            LayoutPosition::Static => PositionInfo::Static(PositionInfoInner {
                // calculate relative to parent
                x_offset: x_pos - parent_x_pos,
                y_offset: y_pos - parent_y_pos,
                static_x_offset: x_pos,
                static_y_offset: y_pos,
            }),
            LayoutPosition::Relative => PositionInfo::Relative(PositionInfoInner {
                // calculate relative to parent
                x_offset: x_pos - parent_x_pos,
                y_offset: y_pos - parent_y_pos,
                static_x_offset: x_pos,
                static_y_offset: y_pos,
            }),
            LayoutPosition::Absolute => PositionInfo::Absolute(PositionInfoInner {
                // calculate relative to last positioned item
                x_offset: x_pos - last_positioned_item_x_pos,
                y_offset: y_pos - last_positioned_item_y_pos,
                static_x_offset: x_pos,
                static_y_offset: y_pos,
            }),
            LayoutPosition::Fixed => PositionInfo::Fixed(PositionInfoInner {
                // relative to screen, already done
                x_offset: x_pos,
                y_offset: y_pos,
                static_x_offset: x_pos,
                static_y_offset: y_pos,
            }),
        };
        let parent_size = LogicalSize::new(width.total(), height.total());

        let parent_offsets = match offsets.get_offsets_for_node(&parent_node_id) {
            Some(s) => s,
            None => continue,
        };

        let parent_padding = parent_offsets
            .padding
            .resolve(parent_parent_width.total(), parent_parent_height.total());
        let parent_margin = parent_offsets
            .margin
            .resolve(parent_parent_width.total(), parent_parent_height.total());
        let parent_border_widths = parent_offsets
            .border_widths
            .resolve(parent_parent_width.total(), parent_parent_height.total());

        // push positioned item and layout children
        if parent_position != LayoutPosition::Static {
            positioned_node_stack.push(parent_node_id);
        }

        for child_node_id in parent_node_id.az_children(node_hierarchy) {
            // copy the width and height from the parent node
            let parent_width = width;
            let parent_height = height;
            let parent_x_pos = x_pos;
            let parent_y_pos = y_pos;

            let width = solved_widths[child_node_id];
            let height = solved_heights[child_node_id];
            let x_pos = x_positions[child_node_id].0;
            let y_pos = y_positions[child_node_id].0;
            let child_position = position_info[child_node_id];
            let child_styled_node_state = &styled_nodes[child_node_id].state;
            let child_node_data = &styled_dom.node_data.as_container()[child_node_id];

            let child_position = match child_position {
                LayoutPosition::Static => PositionInfo::Static(PositionInfoInner {
                    // calculate relative to parent
                    x_offset: x_pos - parent_x_pos,
                    y_offset: y_pos - parent_y_pos,
                    static_x_offset: x_pos,
                    static_y_offset: y_pos,
                }),
                LayoutPosition::Relative => PositionInfo::Relative(PositionInfoInner {
                    // calculate relative to parent
                    x_offset: x_pos - parent_x_pos,
                    y_offset: y_pos - parent_y_pos,
                    static_x_offset: x_pos,
                    static_y_offset: y_pos,
                }),
                LayoutPosition::Absolute => PositionInfo::Absolute(PositionInfoInner {
                    // calculate relative to last positioned item
                    x_offset: x_pos - last_positioned_item_x_pos,
                    y_offset: y_pos - last_positioned_item_y_pos,
                    static_x_offset: x_pos,
                    static_y_offset: y_pos,
                }),
                LayoutPosition::Fixed => PositionInfo::Fixed(PositionInfoInner {
                    // relative to screen, already done
                    x_offset: x_pos,
                    y_offset: y_pos,
                    static_x_offset: x_pos,
                    static_y_offset: y_pos,
                }),
            };

            let child_size_logical = LogicalSize::new(width.total(), height.total());
            let child_offsets = match offsets.get_offsets_for_node(&child_node_id) {
                Some(s) => s,
                None => continue,
            };

            let child_padding = child_offsets
                .padding
                .resolve(parent_width.total(), parent_height.total());
            let child_margin = child_offsets
                .margin
                .resolve(parent_width.total(), parent_height.total());
            let child_border_widths = child_offsets
                .border_widths
                .resolve(parent_width.total(), parent_height.total());

            // set text, if any
            let child_text = if let (Some(words), Some(shaped_words), Some((word_positions, _))) = (
                word_cache.get(&child_node_id),
                shaped_words.get(&child_node_id),
                word_positions.get(&child_node_id),
            ) {
                if nodes_that_need_to_redraw_text.contains(&child_node_id) {
                    #[cfg(feature = "text_layout")]
                    {
                        use crate::text::InlineText;

                        let mut inline_text_layout = InlineText {
                            words,
                            shaped_words,
                        }
                        .get_text_layout(
                            document_id,
                            child_node_id,
                            &word_positions.text_layout_options,
                        );

                        let (horz_alignment, vert_alignment) = determine_text_alignment(
                            css_property_cache
                                .get_align_items(
                                    child_node_data,
                                    &child_node_id,
                                    child_styled_node_state,
                                )
                                .cloned()
                                .and_then(|p| p.get_property_or_default())
                                .unwrap_or_default(),
                            css_property_cache
                                .get_justify_content(
                                    child_node_data,
                                    &child_node_id,
                                    child_styled_node_state,
                                )
                                .cloned()
                                .and_then(|p| p.get_property_or_default())
                                .unwrap_or_default(),
                            css_property_cache
                                .get_text_align(
                                    child_node_data,
                                    &child_node_id,
                                    child_styled_node_state,
                                )
                                .cloned(),
                        );

                        inline_text_layout
                            .align_children_horizontal(&child_size_logical, horz_alignment);
                        inline_text_layout.align_children_vertical_in_parent_bounds(
                            &child_size_logical,
                            vert_alignment,
                        );

                        Some((
                            word_positions.text_layout_options.clone(),
                            inline_text_layout,
                        ))
                    }
                    #[cfg(not(feature = "text_layout"))]
                    {
                        None
                    }
                } else {
                    positioned_rects[child_node_id]
                        .resolved_text_layout_options
                        .clone()
                }
            } else {
                None
            };

            let positioned_rect = PositionedRectangle {
                size: LogicalSize::new(width.total(), height.total()),
                position: child_position,
                padding: child_padding,
                margin: child_margin,
                box_shadow: child_offsets.box_shadow,
                box_sizing: child_offsets.box_sizing,
                border_widths: child_border_widths,
                resolved_text_layout_options: child_text,
                overflow_x: child_offsets.overflow_x,
                overflow_y: child_offsets.overflow_y,
            };

            positioned_rects[child_node_id] = positioned_rect;
        }

        // NOTE: Intentionally do not set text_layout_options,
        // otherwise this would overwrite the existing text layout options
        // Label / Text nodes are ALWAYS children of some parent node,
        // they can not be root nodes. Therefore the children_iter() will take
        // care of layouting the text
        let parent_rect = &mut positioned_rects[parent_node_id];
        parent_rect.size = parent_size;
        parent_rect.position = parent_position_info;
        parent_rect.padding = parent_padding;
        parent_rect.margin = parent_margin;
        parent_rect.border_widths = parent_border_widths;
        parent_rect.box_shadow = parent_offsets.box_shadow;
        parent_rect.box_sizing = parent_offsets.box_sizing;
        parent_rect.overflow_x = parent_offsets.overflow_x;
        parent_rect.overflow_y = parent_offsets.overflow_y;

        if parent_position != LayoutPosition::Static {
            positioned_node_stack.pop();
        }
    }
}

#[cfg(feature = "text_layout")]
fn create_word_cache<'a>(
    node_data: &NodeDataContainerRef<'a, NodeData>,
) -> BTreeMap<NodeId, Words> {
    use crate::text::layout::split_text_into_words;

    let word_map = node_data
        .internal
        .iter()
        .enumerate()
        .map(|(node_id, node)| {
            let node_id = NodeId::new(node_id);
            let string = match node.get_node_type() {
                NodeType::Text(string) => Some(string.as_str()),
                _ => None,
            }?;
            Some((node_id, split_text_into_words(string)))
        })
        .collect::<Vec<_>>();

    word_map.into_iter().filter_map(|a| a).collect()
}

// same as get_inline_text(), but shapes a new word instead of using the internal one
// - necessary to implement text cursor, so that we can calculate the x-offset of
// the text cursor for the next frame (after the character has been pressed)
#[cfg(feature = "text_layout")]
pub fn callback_info_shape_text(
    callbackinfo: &CallbackInfo,
    node_id: DomNodeId,
    text: AzString,
) -> Option<InlineText> {
    let font_ref = callbackinfo.get_font_ref(node_id)?;
    let text_layout_options = callbackinfo.get_text_layout_options(node_id)?;
    Some(crate::text::layout::shape_text(
        &font_ref,
        text.as_str(),
        &text_layout_options,
    ))
}

#[cfg(feature = "text_layout")]
pub fn create_shaped_words<'a>(
    renderer_resources: &RendererResources,
    words: &BTreeMap<NodeId, Words>,
    styled_dom: &'a StyledDom,
) -> BTreeMap<NodeId, ShapedWords> {
    use crate::text::{layout::shape_words, shaping::ParsedFont};

    let css_property_cache = styled_dom.get_css_property_cache();
    let styled_nodes = styled_dom.styled_nodes.as_container();
    let node_data = styled_dom.node_data.as_container();

    words
        .iter()
        .filter_map(|(node_id, words)| {
            use azul_core::styled_dom::StyleFontFamiliesHash;

            let styled_node_state = &styled_nodes[*node_id].state;
            let node_data = &node_data[*node_id];
            let css_font_families =
                css_property_cache.get_font_id_or_default(node_data, node_id, styled_node_state);
            let css_font_families_hash = StyleFontFamiliesHash::new(css_font_families.as_ref());
            let css_font_family = renderer_resources.get_font_family(&css_font_families_hash)?;
            let font_key = renderer_resources.get_font_key(&css_font_family)?;
            let (font_ref, _) = renderer_resources.get_registered_font(&font_key)?;
            let font_data = font_ref.get_data();

            // downcast the loaded_font.font from *const c_void to *const ParsedFont
            let parsed_font_downcasted = unsafe { &*(font_data.parsed as *const ParsedFont) };

            let shaped_words = shape_words(words, parsed_font_downcasted);

            Some((*node_id, shaped_words))
        })
        .collect()
}

#[cfg(feature = "text_layout")]
fn create_word_positions<'a>(
    word_positions: &mut BTreeMap<NodeId, (WordPositions, FontInstanceKey)>,
    word_positions_to_generate: &BTreeSet<NodeId>,
    renderer_resources: &RendererResources,
    words: &BTreeMap<NodeId, Words>,
    shaped_words: &BTreeMap<NodeId, ShapedWords>,
    styled_dom: &'a StyledDom,
    solved_widths: Option<&'a NodeDataContainerRef<'a, WidthCalculatedRect>>,
) {
    use azul_core::{
        app_resources::font_size_to_au,
        ui_solver::{ResolvedTextLayoutOptions, DEFAULT_LETTER_SPACING, DEFAULT_WORD_SPACING},
    };

    use crate::text::layout::position_words;

    let css_property_cache = styled_dom.get_css_property_cache();
    let node_data_container = styled_dom.node_data.as_container();

    let collected = words
        .iter()
        .filter_map(|(node_id, words)| {
            use azul_core::styled_dom::StyleFontFamiliesHash;

            if !word_positions_to_generate.contains(node_id) {
                return None;
            }
            let node_data = &node_data_container[*node_id];

            let styled_node_state = &styled_dom.styled_nodes.as_container()[*node_id].state;
            let font_size =
                css_property_cache.get_font_size_or_default(node_data, node_id, &styled_node_state);
            let font_size_au = font_size_to_au(font_size);
            let font_size_px = font_size.inner.to_pixels(DEFAULT_FONT_SIZE_PX as f32);

            let css_font_families =
                css_property_cache.get_font_id_or_default(node_data, node_id, styled_node_state);
            let css_font_families_hash = StyleFontFamiliesHash::new(css_font_families.as_ref());
            let css_font_family = renderer_resources.get_font_family(&css_font_families_hash)?;
            let font_key = renderer_resources.get_font_key(&css_font_family)?;
            let (_, font_instances) = renderer_resources.get_registered_font(&font_key)?;

            let font_instance_key = font_instances
                .iter()
                .find(|(k, v)| k.0 == font_size_au)
                .map(|(_, v)| v)?;

            let shaped_words = shaped_words.get(&node_id)?;

            let mut max_text_width = None;
            let mut cur_node = *node_id;
            while let Some(parent) = styled_dom.node_hierarchy.as_container()[*node_id].parent_id()
            {
                let overflow_x = css_property_cache
                    .get_overflow_x(
                        &node_data_container[parent],
                        &parent,
                        &styled_dom.styled_nodes.as_container()[parent].state,
                    )
                    .cloned();

                match overflow_x {
                    Some(CssPropertyValue::Exact(LayoutOverflow::Hidden))
                    | Some(CssPropertyValue::Exact(LayoutOverflow::Visible)) => {
                        max_text_width = None;
                        break;
                    }
                    None
                    | Some(CssPropertyValue::None)
                    | Some(CssPropertyValue::Auto)
                    | Some(CssPropertyValue::Initial)
                    | Some(CssPropertyValue::Inherit)
                    | Some(CssPropertyValue::Exact(LayoutOverflow::Auto))
                    | Some(CssPropertyValue::Exact(LayoutOverflow::Scroll)) => {
                        max_text_width = solved_widths.map(|sw| sw[parent].total() as f32);
                        break;
                    }
                }

                cur_node = parent;
            }

            let letter_spacing = css_property_cache
                .get_letter_spacing(node_data, node_id, &styled_node_state)
                .and_then(|ls| Some(ls.get_property()?.inner.to_pixels(DEFAULT_LETTER_SPACING)));

            let word_spacing = css_property_cache
                .get_word_spacing(node_data, node_id, &styled_node_state)
                .and_then(|ws| Some(ws.get_property()?.inner.to_pixels(DEFAULT_WORD_SPACING)));

            let line_height = css_property_cache
                .get_line_height(node_data, node_id, &styled_node_state)
                .and_then(|lh| Some(lh.get_property()?.inner.get()));

            let tab_width = css_property_cache
                .get_tab_width(node_data, node_id, &styled_node_state)
                .and_then(|tw| Some(tw.get_property()?.inner.get()));

            let text_layout_options = ResolvedTextLayoutOptions {
                max_horizontal_width: max_text_width.into(),
                leading: None.into(),     // TODO
                holes: Vec::new().into(), // TODO
                font_size_px,
                word_spacing: word_spacing.into(),
                letter_spacing: letter_spacing.into(),
                line_height: line_height.into(),
                tab_width: tab_width.into(),
            };

            let w = position_words(words, shaped_words, &text_layout_options);

            Some((*node_id, (w, *font_instance_key)))
        })
        .collect::<Vec<_>>();

    collected.into_iter().for_each(|(node_id, word_position)| {
        word_positions.insert(node_id, word_position);
    });
}

/// For a given rectangle, determines what text alignment should be used
fn determine_text_alignment(
    align_items: LayoutAlignItems,
    justify_content: LayoutJustifyContent,
    text_align: Option<CssPropertyValue<StyleTextAlign>>,
) -> (StyleTextAlign, StyleVerticalAlign) {
    // Vertical text alignment
    let vert_alignment = match align_items {
        LayoutAlignItems::FlexStart => StyleVerticalAlign::Top,
        LayoutAlignItems::FlexEnd => StyleVerticalAlign::Bottom,
        // technically stretch = blocktext, but we don't have that yet
        _ => StyleVerticalAlign::Center,
    };

    // Horizontal text alignment
    let mut horz_alignment = match justify_content {
        LayoutJustifyContent::Start => StyleTextAlign::Left,
        LayoutJustifyContent::End => StyleTextAlign::Right,
        _ => StyleTextAlign::Center,
    };

    if let Some(text_align) = text_align
        .as_ref()
        .and_then(|ta| ta.get_property().copied())
    {
        // Horizontal text alignment with higher priority
        horz_alignment = text_align;
    }

    (horz_alignment, vert_alignment)
}

/// Returns all node IDs where the children overflow the parent, together with the
/// `(parent_rect, child_rect)` - the child rect is the sum of the children.
///
/// TODO: The performance of this function can be theoretically improved:
///
/// - Unioning the rectangles is heavier than just looping through the children and
/// summing up their width / height / padding + margin.
/// - Scroll nodes only need to be inserted if the parent doesn't have `overflow: hidden`
/// activated
/// - Overflow for X and Y needs to be tracked seperately (for overflow-x / overflow-y separation),
/// so there we'd need to track in which direction the inner_rect is overflowing.
fn get_nodes_that_need_scroll_clip(
    scrolled_nodes: &mut ScrolledNodes,
    display_list_rects: &NodeDataContainerRef<StyledNode>,
    dom_rects: &NodeDataContainerRef<NodeData>,
    node_hierarchy: &NodeDataContainerRef<NodeHierarchyItem>,
    layouted_rects: &NodeDataContainerRef<PositionedRectangle>,
    parents: &[ParentWithNodeDepth],
    dom_id: DomId,
    document_id: &DocumentId,
) {
    use azul_core::{
        dom::{ScrollTagId, TagId},
        styled_dom::NodeHierarchyItemId,
        ui_solver::{ExternalScrollId, OverflowingScrollNode},
    };

    let mut overflowing_nodes = BTreeMap::new();
    let mut tags_to_node_ids = BTreeMap::new();
    let mut clip_nodes = BTreeMap::new();

    // brute force: calculate all immediate children sum rects of all parents
    let mut all_direct_overflows = parents
        .iter()
        .filter_map(|ParentWithNodeDepth { depth: _, node_id }| {
            let parent_id = node_id.into_crate_internal()?;
            let parent_rect = layouted_rects[parent_id].get_approximate_static_bounds();

            // cannot create scroll clips if the parent is less than 1px wide
            if parent_rect.width() < 1 {
                return None;
            }

            let children_sum_rect = LayoutRect::union(
                parent_id
                    .az_children(node_hierarchy)
                    .filter(|child_id| {
                        use azul_core::ui_solver::PositionInfo;
                        match layouted_rects[*child_id].position {
                            PositionInfo::Absolute(_) => false,
                            _ => true,
                        }
                    })
                    .map(|child_id| layouted_rects[child_id].get_approximate_static_bounds()),
            )?;

            // only register the directly overflowing children
            if parent_rect.contains_rect(&children_sum_rect) {
                None
            } else {
                Some((parent_id, (parent_rect, children_sum_rect)))
            }
        })
        .collect::<BTreeMap<_, _>>();

    // Go from the inside out and bubble the overflowing rectangles
    // based on the overflow-x / overflow-y property
    let mut len = parents.len();
    while len != 0 {
        use azul_css::LayoutOverflow::*;

        len -= 1;

        let parent = &parents[len];
        let parent_id = match parent.node_id.into_crate_internal() {
            Some(s) => s,
            None => continue,
        };

        let (parent_rect, children_sum_rect) = match all_direct_overflows.get(&parent_id).cloned() {
            Some(s) => s,
            None => continue,
        };

        let positioned_rect = &layouted_rects[parent_id];
        let overflow_x = positioned_rect.overflow_x;
        let overflow_y = positioned_rect.overflow_y;

        match (overflow_x, overflow_y) {
            (Hidden, Hidden) => {
                clip_nodes.insert(parent_id, positioned_rect.size);
                all_direct_overflows.remove(&parent_id);
            }
            (Visible, Visible) => {
                all_direct_overflows.remove(&parent_id);
            }
            _ => {
                // modify the rect in the all_direct_overflows,
                // then recalculate the rectangles for all parents
                // this is expensive, but at least correct
            }
        }
    }

    // Insert all rectangles that need to scroll
    for (parent_id, (parent_rect, children_sum_rect)) in all_direct_overflows {
        use azul_core::callbacks::PipelineId;

        let parent_dom_hash = dom_rects[parent_id].calculate_node_data_hash();
        let parent_external_scroll_id = ExternalScrollId(
            parent_dom_hash.0,
            PipelineId(dom_id.inner as u32, document_id.id),
        );

        let scroll_tag_id = match display_list_rects[parent_id].tag_id.as_ref() {
            Some(s) => ScrollTagId(s.into_crate_internal()),
            None => ScrollTagId(TagId::unique()),
        };

        let child_rect = LogicalRect::new(
            LogicalPosition::new(
                children_sum_rect.origin.x as f32,
                children_sum_rect.origin.y as f32,
            ),
            LogicalSize::new(
                children_sum_rect.size.width as f32,
                children_sum_rect.size.height as f32,
            ),
        );

        let os = OverflowingScrollNode {
            parent_rect: LogicalRect::new(
                LogicalPosition::new(parent_rect.origin.x as f32, parent_rect.origin.y as f32),
                LogicalSize::new(
                    parent_rect.size.width as f32,
                    parent_rect.size.height as f32,
                ),
            ),
            child_rect,
            virtual_child_rect: child_rect,
            parent_external_scroll_id,
            parent_dom_hash,
            scroll_tag_id,
        };

        overflowing_nodes.insert(
            NodeHierarchyItemId::from_crate_internal(Some(parent_id)),
            os,
        );
        tags_to_node_ids.insert(
            scroll_tag_id,
            NodeHierarchyItemId::from_crate_internal(Some(parent_id)),
        );
    }

    *scrolled_nodes = ScrolledNodes {
        overflowing_nodes,
        clip_nodes,
        tags_to_node_ids,
    };
}

/// Relayout function, takes an existing LayoutResult and adjusts it
/// so that only the nodes that need relayout are touched.
/// See `CallbacksToCall`
///
/// Returns a vec of node IDs that whose layout was changed
pub fn do_the_relayout(
    dom_id: DomId,
    root_bounds: LayoutRect,
    layout_result: &mut LayoutResult,
    _image_cache: &ImageCache,
    renderer_resources: &mut RendererResources,
    document_id: &DocumentId,
    nodes_to_relayout: Option<&BTreeMap<NodeId, Vec<ChangedCssProperty>>>,
    words_to_relayout: Option<&BTreeMap<NodeId, AzString>>,
) -> RelayoutChanges {
    // shortcut: in most cases, the root size hasn't
    // changed and there are no nodes to relayout

    let root_size = root_bounds.size;
    let root_size_changed = root_bounds != layout_result.get_bounds();

    if !root_size_changed && nodes_to_relayout.is_none() && words_to_relayout.is_none() {
        return RelayoutChanges::empty();
    }

    // merge the nodes to relayout by type so that we don't relayout twice
    let mut nodes_to_relayout = nodes_to_relayout.map(|n| {
        n.iter()
            .filter_map(|(node_id, changed_properties)| {
                let mut properties = BTreeMap::new();

                for prop in changed_properties.iter() {
                    let prop_type = prop.previous_prop.get_type();
                    if prop_type.can_trigger_relayout() {
                        properties.insert(prop_type, prop.clone());
                    }
                }

                if properties.is_empty() {
                    None
                } else {
                    Some((*node_id, properties))
                }
            })
            .collect::<BTreeMap<NodeId, BTreeMap<CssPropertyType, ChangedCssProperty>>>()
    });

    if !root_size_changed && nodes_to_relayout.is_none() && words_to_relayout.is_none() {
        let resized_nodes = Vec::new();
        let gpu_key_changes = layout_result
            .gpu_value_cache
            .synchronize(&layout_result.rects.as_ref(), &layout_result.styled_dom);

        return RelayoutChanges {
            resized_nodes,
            gpu_key_changes,
        };
    }

    // ---- step 1: recalc size

    // TODO: for now, the preferred_widths and preferred_widths is always None,
    // so the content width + height isn't taken into account. If that changes,
    // the new content size has to be calculated first!

    // TODO: changes to display, float and box-sizing property are ignored
    // TODO: changes to top, bottom, right, left property are ignored for now
    // TODO: changes to position: property are updated, but ignored for now

    // recalc(&mut layout_result.preferred_widths);

    let mut display_changed = false;

    // update the precalculated properties (position, flex-grow,
    // flex-direction, justify-content)
    if let Some(nodes_to_relayout) = nodes_to_relayout.as_ref() {
        nodes_to_relayout
            .iter()
            .for_each(|(node_id, changed_props)| {
                if let Some(CssProperty::Display(new_display_state)) = changed_props
                    .get(&CssPropertyType::Display)
                    .map(|p| &p.current_prop)
                {
                    display_changed = true;
                    layout_result.layout_displays.as_ref_mut()[*node_id] =
                        new_display_state.clone();
                }

                if let Some(CssProperty::Position(new_position_state)) = changed_props
                    .get(&CssPropertyType::Position)
                    .map(|p| &p.current_prop)
                {
                    layout_result.layout_positions.as_ref_mut()[*node_id] = new_position_state
                        .get_property()
                        .cloned()
                        .unwrap_or_default();
                }

                if let Some(CssProperty::FlexGrow(new_flex_grow)) = changed_props
                    .get(&CssPropertyType::FlexGrow)
                    .map(|p| &p.current_prop)
                {
                    layout_result.layout_flex_grows.as_ref_mut()[*node_id] = new_flex_grow
                        .get_property()
                        .cloned()
                        .map(|grow| grow.inner.get().max(0.0))
                        .unwrap_or(DEFAULT_FLEX_GROW_FACTOR);
                }

                if let Some(CssProperty::FlexDirection(new_flex_direction)) = changed_props
                    .get(&CssPropertyType::FlexDirection)
                    .map(|p| &p.current_prop)
                {
                    layout_result.layout_flex_directions.as_ref_mut()[*node_id] =
                        new_flex_direction
                            .get_property()
                            .cloned()
                            .unwrap_or_default();
                }

                if let Some(CssProperty::JustifyContent(new_justify_content)) = changed_props
                    .get(&CssPropertyType::JustifyContent)
                    .map(|p| &p.current_prop)
                {
                    layout_result.layout_justify_contents.as_ref_mut()[*node_id] =
                        new_justify_content
                            .get_property()
                            .cloned()
                            .unwrap_or_default();
                }
            });
    }

    let mut nodes_that_need_to_bubble_width = BTreeMap::new();
    let mut nodes_that_need_to_bubble_height = BTreeMap::new();
    let mut parents_that_need_to_recalc_width_of_children = BTreeSet::new();
    let mut parents_that_need_to_recalc_height_of_children = BTreeSet::new();
    let mut parents_that_need_to_reposition_children_x = BTreeSet::new();
    let mut parents_that_need_to_reposition_children_y = BTreeSet::new();

    /*
    if display_changed {
        // recalculate changed display:none nodes
        let new_display_none_nodes = get_display_none_nodes(
            &styled_dom.node_hierarchy.as_container(),
            &layout_result.layout_displays.as_ref(),
        );
    }
    */

    if root_size_changed {
        let all_parents_btreeset = layout_result
            .styled_dom
            .non_leaf_nodes
            .iter()
            .filter_map(|p| Some(p.node_id.into_crate_internal()?))
            .collect::<BTreeSet<_>>();
        layout_result.root_size = root_size;
        parents_that_need_to_recalc_width_of_children
            .extend(all_parents_btreeset.clone().into_iter());
        parents_that_need_to_recalc_height_of_children.extend(all_parents_btreeset.into_iter());
    }

    if root_size.width != layout_result.root_size.width {
        let root_id = layout_result.styled_dom.root.into_crate_internal().unwrap();
        parents_that_need_to_recalc_width_of_children.insert(root_id);
    }

    if root_size.height != layout_result.root_size.height {
        let root_id = layout_result.styled_dom.root.into_crate_internal().unwrap();
        parents_that_need_to_recalc_height_of_children.insert(root_id);
    }

    let mut node_ids_that_changed_text_content = BTreeSet::new();

    // Update words cache and shaped words cache
    #[cfg(feature = "text_layout")]
    if let Some(words_to_relayout) = words_to_relayout {
        for (node_id, new_string) in words_to_relayout.iter() {
            use azul_core::{
                styled_dom::StyleFontFamiliesHash,
                ui_solver::{
                    ResolvedTextLayoutOptions, DEFAULT_LETTER_SPACING, DEFAULT_WORD_SPACING,
                },
            };

            use crate::text::{
                layout::{
                    position_words, shape_words, split_text_into_words,
                    word_positions_to_inline_text_layout,
                },
                shaping::ParsedFont,
            };

            if layout_result.words_cache.get(&node_id).is_none() {
                continue;
            }
            if layout_result.shaped_words_cache.get(&node_id).is_none() {
                continue;
            }
            if layout_result.positioned_words_cache.get(&node_id).is_none() {
                continue;
            }
            let text_layout_options = match layout_result
                .rects
                .as_ref()
                .get(*node_id)
                .and_then(|s| s.resolved_text_layout_options.as_ref())
            {
                None => continue,
                Some(s) => s.0.clone(),
            };

            let new_words = split_text_into_words(new_string.as_str());

            let css_property_cache = layout_result.styled_dom.get_css_property_cache();
            let styled_nodes = layout_result.styled_dom.styled_nodes.as_container();
            let node_data = layout_result.styled_dom.node_data.as_container();
            let styled_node_state = &styled_nodes[*node_id].state;
            let node_data = &node_data[*node_id];

            let css_font_families =
                css_property_cache.get_font_id_or_default(node_data, node_id, styled_node_state);
            let css_font_families_hash = StyleFontFamiliesHash::new(css_font_families.as_ref());
            let css_font_family = match renderer_resources.get_font_family(&css_font_families_hash)
            {
                Some(s) => s,
                None => continue,
            };
            let font_key = match renderer_resources.get_font_key(&css_font_family) {
                Some(s) => s,
                None => continue,
            };
            let (font_ref, _) = match renderer_resources.get_registered_font(&font_key) {
                Some(s) => s,
                None => continue,
            };
            let font_data = font_ref.get_data();
            let parsed_font_downcasted = unsafe { &*(font_data.parsed as *const ParsedFont) };
            let new_shaped_words = shape_words(&new_words, parsed_font_downcasted);

            let font_size =
                css_property_cache.get_font_size_or_default(node_data, node_id, &styled_node_state);
            let font_size_px = font_size.inner.to_pixels(DEFAULT_FONT_SIZE_PX as f32);

            let letter_spacing = css_property_cache
                .get_letter_spacing(node_data, node_id, &styled_node_state)
                .and_then(|ls| Some(ls.get_property()?.inner.to_pixels(DEFAULT_LETTER_SPACING)));

            let word_spacing = css_property_cache
                .get_word_spacing(node_data, node_id, &styled_node_state)
                .and_then(|ws| Some(ws.get_property()?.inner.to_pixels(DEFAULT_WORD_SPACING)));

            let line_height = css_property_cache
                .get_line_height(node_data, node_id, &styled_node_state)
                .and_then(|lh| Some(lh.get_property()?.inner.get()));

            let tab_width = css_property_cache
                .get_tab_width(node_data, node_id, &styled_node_state)
                .and_then(|tw| Some(tw.get_property()?.inner.get()));

            let new_word_positions =
                position_words(&new_words, &new_shaped_words, &text_layout_options);
            let new_inline_text_layout = word_positions_to_inline_text_layout(&new_word_positions);

            let old_word_dimensions = layout_result
                .rects
                .as_ref()
                .get(*node_id)
                .and_then(|s| s.resolved_text_layout_options.as_ref())
                .map(|s| s.1.content_size)
                .unwrap_or(LogicalSize::zero());

            let new_word_dimensions = new_word_positions.content_size;

            layout_result.preferred_widths.as_ref_mut()[*node_id] =
                Some(new_word_positions.content_size.width);
            *layout_result.words_cache.get_mut(node_id).unwrap() = new_words;
            *layout_result.shaped_words_cache.get_mut(node_id).unwrap() = new_shaped_words;
            layout_result
                .positioned_words_cache
                .get_mut(node_id)
                .unwrap()
                .0 = new_word_positions;
            layout_result
                .rects
                .as_ref_mut()
                .get_mut(*node_id)
                .unwrap()
                .resolved_text_layout_options = Some((text_layout_options, new_inline_text_layout));
            node_ids_that_changed_text_content.insert(*node_id);
        }
    }

    // parents need to be adjust before children
    for ParentWithNodeDepth { depth: _, node_id } in layout_result.styled_dom.non_leaf_nodes.iter()
    {
        macro_rules! detect_changes {
            ($node_id:expr, $parent_id:expr) => {
                let node_data = &layout_result.styled_dom.node_data.as_container()[$node_id];
                let text_content_has_changed =
                    node_ids_that_changed_text_content.contains(&$node_id);
                let default_changes = BTreeMap::new();
                let changes_for_this_node =
                    match nodes_to_relayout.as_ref().and_then(|n| n.get(&$node_id)) {
                        Some(s) => Some(s),
                        None => {
                            if text_content_has_changed {
                                Some(&default_changes)
                            } else {
                                None
                            }
                        }
                    };

                let has_word_positions = layout_result
                    .positioned_words_cache
                    .get(&$node_id)
                    .is_some();
                if let Some(changes_for_this_node) = changes_for_this_node.as_ref() {
                    if !changes_for_this_node.is_empty()
                        || has_word_positions
                        || text_content_has_changed
                    {
                        let mut preferred_width_changed = None;
                        let mut preferred_height_changed = None;
                        let mut padding_x_changed = false;
                        let mut padding_y_changed = false;
                        let mut margin_x_changed = false;
                        let mut margin_y_changed = false;

                        let solved_width_layout =
                            &mut layout_result.width_calculated_rects.as_ref_mut()[$node_id];
                        let solved_height_layout =
                            &mut layout_result.height_calculated_rects.as_ref_mut()[$node_id];
                        let css_property_cache = layout_result.styled_dom.get_css_property_cache();
                        let parent_parent = layout_result.styled_dom.node_hierarchy.as_container()
                            [$parent_id]
                            .parent_id()
                            .unwrap_or(NodeId::ZERO);

                        // recalculate min / max / preferred width constraint if needed
                        if changes_for_this_node.contains_key(&CssPropertyType::Width)
                            || changes_for_this_node.contains_key(&CssPropertyType::MinWidth)
                            || changes_for_this_node.contains_key(&CssPropertyType::MaxWidth)
                            || has_word_positions
                            || text_content_has_changed
                        {
                            let styled_node_state =
                                &layout_result.styled_dom.styled_nodes.as_container()[$node_id]
                                    .state;

                            let wh_config = WhConfig {
                                width: WidthConfig {
                                    exact: css_property_cache
                                        .get_width(node_data, &$node_id, styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                    max: css_property_cache
                                        .get_max_width(node_data, &$node_id, styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                    min: css_property_cache
                                        .get_min_width(node_data, &$node_id, styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                    overflow: css_property_cache
                                        .get_overflow_x(node_data, &$node_id, styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                },
                                height: HeightConfig::default(),
                            };
                            let parent_width = layout_result.preferred_widths.as_ref()[$parent_id]
                                .clone()
                                .unwrap_or(root_size.width as f32);
                            let parent_parent_overflow_x = css_property_cache
                                .get_overflow_x(
                                    &layout_result.styled_dom.node_data.as_container()
                                        [parent_parent],
                                    &parent_parent,
                                    &layout_result.styled_dom.styled_nodes.as_container()
                                        [parent_parent]
                                        .state,
                                )
                                .and_then(|p| p.get_property().copied())
                                .unwrap_or_default();

                            let new_preferred_width = determine_preferred_width(
                                &wh_config,
                                layout_result.preferred_widths.as_ref()[$node_id],
                                parent_width,
                                parent_parent_overflow_x,
                            );

                            if new_preferred_width != solved_width_layout.preferred_width {
                                preferred_width_changed = Some((
                                    solved_width_layout.preferred_width,
                                    new_preferred_width,
                                ));
                                solved_width_layout.preferred_width = new_preferred_width;
                            }
                        }

                        // recalculate min / max / preferred width constraint if needed
                        if changes_for_this_node.contains_key(&CssPropertyType::MinHeight)
                            || changes_for_this_node.contains_key(&CssPropertyType::MaxHeight)
                            || changes_for_this_node.contains_key(&CssPropertyType::Height)
                            || has_word_positions
                            || text_content_has_changed
                        {
                            let styled_node_state =
                                &layout_result.styled_dom.styled_nodes.as_container()[$node_id]
                                    .state;
                            let wh_config = WhConfig {
                                width: WidthConfig::default(),
                                height: HeightConfig {
                                    exact: css_property_cache
                                        .get_height(node_data, &$node_id, &styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                    max: css_property_cache
                                        .get_max_height(node_data, &$node_id, &styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                    min: css_property_cache
                                        .get_min_height(node_data, &$node_id, &styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                    overflow: css_property_cache
                                        .get_overflow_y(node_data, &$node_id, &styled_node_state)
                                        .and_then(|p| p.get_property().copied()),
                                },
                            };
                            let parent_height = layout_result.preferred_heights.as_ref()
                                [$parent_id]
                                .clone()
                                .unwrap_or(root_size.height as f32);
                            let parent_parent_overflow_y = css_property_cache
                                .get_overflow_x(
                                    &layout_result.styled_dom.node_data.as_container()
                                        [parent_parent],
                                    &parent_parent,
                                    &layout_result.styled_dom.styled_nodes.as_container()
                                        [parent_parent]
                                        .state,
                                )
                                .and_then(|p| p.get_property().copied())
                                .unwrap_or_default();

                            let new_preferred_height = determine_preferred_height(
                                &wh_config,
                                layout_result.preferred_heights.as_ref()[$node_id],
                                parent_height,
                                parent_parent_overflow_y,
                            );

                            if new_preferred_height != solved_height_layout.preferred_height {
                                preferred_height_changed = Some((
                                    solved_height_layout.preferred_height,
                                    new_preferred_height,
                                ));
                                solved_height_layout.preferred_height = new_preferred_height;
                            }
                        }

                        // padding / margin horizontal change
                        if let Some(CssProperty::PaddingLeft(prop)) = changes_for_this_node
                            .get(&CssPropertyType::PaddingLeft)
                            .map(|p| &p.current_prop)
                        {
                            solved_width_layout.padding_left = Some(*prop);
                            padding_x_changed = true;
                        }

                        if let Some(CssProperty::PaddingRight(prop)) = changes_for_this_node
                            .get(&CssPropertyType::PaddingRight)
                            .map(|p| &p.current_prop)
                        {
                            solved_width_layout.padding_right = Some(*prop);
                            padding_x_changed = true;
                        }

                        if let Some(CssProperty::MarginLeft(prop)) = changes_for_this_node
                            .get(&CssPropertyType::MarginLeft)
                            .map(|p| &p.current_prop)
                        {
                            solved_width_layout.margin_left = Some(*prop);
                            margin_x_changed = true;
                        }

                        if let Some(CssProperty::MarginRight(prop)) = changes_for_this_node
                            .get(&CssPropertyType::MarginRight)
                            .map(|p| &p.current_prop)
                        {
                            solved_width_layout.margin_right = Some(*prop);
                            margin_x_changed = true;
                        }

                        // padding / margin vertical change
                        if let Some(CssProperty::PaddingTop(prop)) = changes_for_this_node
                            .get(&CssPropertyType::PaddingTop)
                            .map(|p| &p.current_prop)
                        {
                            solved_height_layout.padding_top = Some(*prop);
                            padding_y_changed = true;
                        }

                        if let Some(CssProperty::PaddingBottom(prop)) = changes_for_this_node
                            .get(&CssPropertyType::PaddingBottom)
                            .map(|p| &p.current_prop)
                        {
                            solved_height_layout.padding_bottom = Some(*prop);
                            padding_y_changed = true;
                        }

                        if let Some(CssProperty::MarginTop(prop)) = changes_for_this_node
                            .get(&CssPropertyType::MarginTop)
                            .map(|p| &p.current_prop)
                        {
                            solved_height_layout.margin_top = Some(*prop);
                            margin_y_changed = true;
                        }

                        if let Some(CssProperty::MarginBottom(prop)) = changes_for_this_node
                            .get(&CssPropertyType::MarginBottom)
                            .map(|p| &p.current_prop)
                        {
                            solved_height_layout.margin_bottom = Some(*prop);
                            margin_y_changed = true;
                        }

                        if let Some((previous_preferred_width, current_preferred_width)) =
                            preferred_width_changed
                        {
                            // need to recalc the width of the node
                            // need to bubble the width to the parent width
                            // need to recalc the width of all children
                            // need to recalc the x position of all siblings
                            parents_that_need_to_recalc_width_of_children.insert($parent_id);
                            nodes_that_need_to_bubble_width.insert(
                                $node_id,
                                (previous_preferred_width, current_preferred_width),
                            );
                            parents_that_need_to_recalc_width_of_children.insert($node_id);
                            parents_that_need_to_reposition_children_x.insert($parent_id);
                        }

                        if let Some((previous_preferred_height, current_preferred_height)) =
                            preferred_height_changed
                        {
                            // need to recalc the height of the node
                            // need to bubble the height of all current node siblings to the parent
                            // height need to recalc the height of all children
                            // need to recalc the y position of all siblings
                            parents_that_need_to_recalc_height_of_children.insert($parent_id);
                            nodes_that_need_to_bubble_height.insert(
                                $node_id,
                                (previous_preferred_height, current_preferred_height),
                            );
                            parents_that_need_to_recalc_height_of_children.insert($node_id);
                            parents_that_need_to_reposition_children_y.insert($parent_id);
                        }

                        if padding_x_changed {
                            // need to recalc the widths of all children
                            // need to recalc the x position of all children
                            parents_that_need_to_recalc_width_of_children.insert($node_id);
                            parents_that_need_to_reposition_children_x.insert($node_id);
                        }

                        if padding_y_changed {
                            // need to recalc the heights of all children
                            // need to bubble the height of all current node children to the
                            // current node min_inner_size_px
                            parents_that_need_to_recalc_height_of_children.insert($node_id);
                            parents_that_need_to_reposition_children_y.insert($node_id);
                        }

                        if margin_x_changed {
                            // need to recalc the widths of all siblings
                            // need to recalc the x positions of all siblings
                            parents_that_need_to_recalc_width_of_children.insert($parent_id);
                            parents_that_need_to_reposition_children_x.insert($parent_id);
                        }

                        if margin_y_changed {
                            // need to recalc the heights of all siblings
                            // need to recalc the y positions of all siblings
                            parents_that_need_to_recalc_height_of_children.insert($parent_id);
                            parents_that_need_to_reposition_children_y.insert($parent_id);
                        }

                        // TODO: absolute positions / top-left-right-bottom changes!
                    }
                }
            };
        }

        let node_id = match node_id.into_crate_internal() {
            Some(s) => s,
            None => continue,
        };

        let parent_id = layout_result.styled_dom.node_hierarchy.as_container()[node_id]
            .parent_id()
            .unwrap_or(layout_result.styled_dom.root.into_crate_internal().unwrap());

        detect_changes!(node_id, parent_id);

        for child_id in node_id.az_children(&layout_result.styled_dom.node_hierarchy.as_container())
        {
            detect_changes!(child_id, node_id);
        }
    }

    // for all nodes that changed, recalculate the min_inner_size_px of the parents
    // by re-bubbling the sizes to the parents (but only for the nodes that need it)
    let mut rebubble_parent_widths = BTreeMap::new();
    let mut rebubble_parent_heights = BTreeMap::new();

    for (node_id, (old_preferred_width, new_preferred_width)) in
        nodes_that_need_to_bubble_width.iter().rev()
    {
        if let Some(parent_id) =
            layout_result.styled_dom.node_hierarchy.as_container()[*node_id].parent_id()
        {
            let change = new_preferred_width.min_needed_space().unwrap_or(0.0)
                - old_preferred_width.min_needed_space().unwrap_or(0.0);
            layout_result.width_calculated_rects.as_ref_mut()[*node_id].min_inner_size_px =
                new_preferred_width.min_needed_space().unwrap_or(0.0);
            layout_result.width_calculated_rects.as_ref_mut()[parent_id].min_inner_size_px +=
                change;
            layout_result.width_calculated_rects.as_ref_mut()[parent_id].flex_grow_px = 0.0;
            if change != 0.0 {
                *rebubble_parent_widths
                    .entry(parent_id)
                    .or_insert_with(|| 0.0) += change;
                parents_that_need_to_recalc_width_of_children.insert(parent_id);
            }
        }
    }

    for (node_id, (old_preferred_height, new_preferred_height)) in
        nodes_that_need_to_bubble_height.iter().rev()
    {
        if let Some(parent_id) =
            layout_result.styled_dom.node_hierarchy.as_container()[*node_id].parent_id()
        {
            let change = new_preferred_height.min_needed_space().unwrap_or(0.0)
                - old_preferred_height.min_needed_space().unwrap_or(0.0);
            layout_result.height_calculated_rects.as_ref_mut()[*node_id].min_inner_size_px =
                new_preferred_height.min_needed_space().unwrap_or(0.0);
            layout_result.height_calculated_rects.as_ref_mut()[parent_id].min_inner_size_px +=
                change;
            layout_result.height_calculated_rects.as_ref_mut()[parent_id].flex_grow_px = 0.0;
            if change != 0.0 {
                *rebubble_parent_heights
                    .entry(parent_id)
                    .or_insert_with(|| 0.0) += change;
                parents_that_need_to_recalc_height_of_children.insert(parent_id);
            }
        }
    }

    let mut subtree_needs_relayout_width = BTreeSet::new();
    let mut subtree_needs_relayout_height = BTreeSet::new();

    // propagate width / height change from the inside out
    while !parents_that_need_to_recalc_width_of_children.is_empty() {
        // width_calculated_rect_arena_apply_flex_grow also
        // needs the parents parent to work correctly
        let parents_to_extend = parents_that_need_to_recalc_width_of_children
            .iter()
            .map(|p| {
                layout_result.styled_dom.node_hierarchy.as_container()[*p]
                    .parent_id()
                    .unwrap_or(NodeId::ZERO)
            })
            .collect::<BTreeSet<_>>();

        parents_that_need_to_recalc_width_of_children.extend(parents_to_extend.into_iter());

        let previous_widths = parents_that_need_to_recalc_width_of_children
            .iter()
            .filter_map(|node_id| {
                layout_result
                    .width_calculated_rects
                    .as_ref()
                    .get(*node_id)
                    .map(|s| (node_id, *s))
            })
            .collect::<BTreeMap<_, _>>();

        subtree_needs_relayout_width.extend(
            parents_that_need_to_recalc_width_of_children
                .iter()
                .cloned(),
        );

        width_calculated_rect_arena_apply_flex_grow(
            &mut layout_result.width_calculated_rects,
            &layout_result.styled_dom.node_hierarchy.as_container(),
            &layout_result.layout_displays.as_ref(),
            &layout_result.layout_flex_grows.as_ref(),
            &layout_result.layout_positions.as_ref(),
            &layout_result.layout_flex_directions.as_ref(),
            &layout_result.styled_dom.non_leaf_nodes.as_ref(),
            root_size.width as f32,
            // important - only recalc the widths necessary!
            &parents_that_need_to_recalc_width_of_children,
        );

        // if the parent width is not the same, bubble
        let parents_that_changed_width = parents_that_need_to_recalc_width_of_children
            .iter()
            .filter_map(|p| {
                // get the current width after relayout
                let current_width = layout_result
                    .width_calculated_rects
                    .as_ref()
                    .get(*p)
                    .copied()?;
                let previous_width = previous_widths.get(p).copied()?;
                if current_width == previous_width {
                    return None;
                }
                let parent_id =
                    layout_result.styled_dom.node_hierarchy.as_container()[*p].parent_id()?;
                Some(parent_id)
            })
            .collect();

        // loop while there are still widths that changed size
        parents_that_need_to_recalc_width_of_children = parents_that_changed_width;
    }

    parents_that_need_to_recalc_width_of_children = subtree_needs_relayout_width;

    while !parents_that_need_to_recalc_height_of_children.is_empty() {
        let parents_to_extend = parents_that_need_to_recalc_height_of_children
            .iter()
            .map(|p| {
                layout_result.styled_dom.node_hierarchy.as_container()[*p]
                    .parent_id()
                    .unwrap_or(NodeId::ZERO)
            })
            .collect::<BTreeSet<_>>();

        parents_that_need_to_recalc_height_of_children.extend(parents_to_extend.into_iter());

        let previous_heights = parents_that_need_to_recalc_height_of_children
            .iter()
            .filter_map(|node_id| {
                layout_result
                    .height_calculated_rects
                    .as_ref()
                    .get(*node_id)
                    .map(|s| (node_id, *s))
            })
            .collect::<BTreeMap<_, _>>();

        subtree_needs_relayout_height.extend(
            parents_that_need_to_recalc_height_of_children
                .iter()
                .cloned(),
        );

        height_calculated_rect_arena_apply_flex_grow(
            &mut layout_result.height_calculated_rects,
            &layout_result.styled_dom.node_hierarchy.as_container(),
            &layout_result.layout_displays.as_ref(),
            &layout_result.layout_flex_grows.as_ref(),
            &layout_result.layout_positions.as_ref(),
            &layout_result.layout_flex_directions.as_ref(),
            &layout_result.styled_dom.non_leaf_nodes.as_ref(),
            root_size.height as f32,
            // important - only recalc the heights necessary!
            &parents_that_need_to_recalc_height_of_children,
        );

        // if the parent height is not the same, bubble
        let mut parents_that_changed_height = parents_that_need_to_recalc_height_of_children
            .iter()
            .filter_map(|p| {
                // get the current height after relayout
                let current_height = layout_result
                    .height_calculated_rects
                    .as_ref()
                    .get(*p)
                    .copied()?;
                let previous_height = previous_heights.get(p).copied()?;
                if current_height == previous_height {
                    return None;
                }
                let parent_id =
                    layout_result.styled_dom.node_hierarchy.as_container()[*p].parent_id()?;
                Some(parent_id)
            })
            .collect();

        // loop while there are still heights that changed size
        parents_that_need_to_recalc_height_of_children = parents_that_changed_height;
    }

    parents_that_need_to_recalc_height_of_children = subtree_needs_relayout_height;

    // if a node has been modified then the entire subtree needs to be re-laid out
    for n in parents_that_need_to_recalc_width_of_children.clone() {
        let subtree_parents = layout_result.styled_dom.get_subtree_parents(n);
        for s in subtree_parents {
            parents_that_need_to_recalc_width_of_children.insert(s);
        }
        parents_that_need_to_reposition_children_x.insert(n);
    }

    for n in parents_that_need_to_recalc_height_of_children.clone() {
        let subtree_parents = layout_result.styled_dom.get_subtree_parents(n);
        for s in subtree_parents {
            parents_that_need_to_recalc_height_of_children.insert(s);
        }
        parents_that_need_to_reposition_children_y.insert(n);
    }

    for n in parents_that_need_to_reposition_children_x.clone() {
        let subtree_parents = layout_result.styled_dom.get_subtree_parents(n);
        for s in subtree_parents {
            parents_that_need_to_reposition_children_x.insert(s);
        }
    }

    for n in parents_that_need_to_reposition_children_y.clone() {
        let subtree_parents = layout_result.styled_dom.get_subtree_parents(n);
        for s in subtree_parents {
            parents_that_need_to_reposition_children_y.insert(s);
        }
    }

    // -- step 2: recalc position for those parents that need it

    width_calculated_rect_arena_apply_flex_grow(
        &mut layout_result.width_calculated_rects,
        &layout_result.styled_dom.node_hierarchy.as_container(),
        &layout_result.layout_displays.as_ref(),
        &layout_result.layout_flex_grows.as_ref(),
        &layout_result.layout_positions.as_ref(),
        &layout_result.layout_flex_directions.as_ref(),
        &layout_result.styled_dom.non_leaf_nodes.as_ref(),
        root_size.width as f32,
        // important - only recalc the widths necessary!
        &parents_that_need_to_recalc_width_of_children,
    );

    height_calculated_rect_arena_apply_flex_grow(
        &mut layout_result.height_calculated_rects,
        &layout_result.styled_dom.node_hierarchy.as_container(),
        &layout_result.layout_displays.as_ref(),
        &layout_result.layout_flex_grows.as_ref(),
        &layout_result.layout_positions.as_ref(),
        &layout_result.layout_flex_directions.as_ref(),
        &layout_result.styled_dom.non_leaf_nodes.as_ref(),
        root_size.height as f32,
        // important - only recalc the heights necessary!
        &parents_that_need_to_recalc_height_of_children,
    );

    // -- step 2: recalc position for those parents that need it

    get_x_positions(
        &mut layout_result.solved_pos_x,
        &layout_result.width_calculated_rects.as_ref(),
        &layout_result.styled_dom.node_hierarchy.as_container(),
        &layout_result.layout_positions.as_ref(),
        &layout_result.layout_flex_directions.as_ref(),
        &layout_result.layout_justify_contents.as_ref(),
        &layout_result.styled_dom.non_leaf_nodes.as_ref(),
        LogicalPosition::new(root_bounds.origin.x as f32, root_bounds.origin.y as f32),
        &parents_that_need_to_reposition_children_x, // <- important
    );

    get_y_positions(
        &mut layout_result.solved_pos_y,
        &layout_result.height_calculated_rects.as_ref(),
        &layout_result.styled_dom.node_hierarchy.as_container(),
        &layout_result.layout_positions.as_ref(),
        &layout_result.layout_flex_directions.as_ref(),
        &layout_result.layout_justify_contents.as_ref(),
        &layout_result.styled_dom.non_leaf_nodes.as_ref(),
        LogicalPosition::new(root_bounds.origin.x as f32, root_bounds.origin.y as f32),
        &parents_that_need_to_reposition_children_y, // <- important
    );

    // update positioned_word_cache
    let mut updated_word_caches = parents_that_need_to_recalc_width_of_children.clone();
    for parent_id in parents_that_need_to_recalc_width_of_children.iter() {
        for child_id in
            parent_id.az_children(&layout_result.styled_dom.node_hierarchy.as_container())
        {
            // if max_width_changed { } // - optimization?
            updated_word_caches.insert(child_id);
        }
    }

    updated_word_caches.extend(node_ids_that_changed_text_content.clone().into_iter());

    #[cfg(feature = "text_layout")]
    create_word_positions(
        &mut layout_result.positioned_words_cache,
        &updated_word_caches,
        renderer_resources,
        &layout_result.words_cache,
        &layout_result.shaped_words_cache,
        &layout_result.styled_dom,
        Some(&layout_result.width_calculated_rects.as_ref()),
    );

    // determine which nodes changed their size and return
    let mut nodes_that_changed_size = BTreeSet::new();
    for parent_id in parents_that_need_to_recalc_width_of_children {
        nodes_that_changed_size.insert(parent_id);
        for child_id in
            parent_id.az_children(&layout_result.styled_dom.node_hierarchy.as_container())
        {
            nodes_that_changed_size.insert(child_id);
        }
    }
    for parent_id in parents_that_need_to_recalc_height_of_children {
        nodes_that_changed_size.insert(parent_id);
        for child_id in
            parent_id.az_children(&layout_result.styled_dom.node_hierarchy.as_container())
        {
            nodes_that_changed_size.insert(child_id);
        }
    }
    for node_text_content_changed in &node_ids_that_changed_text_content {
        let parent = layout_result.styled_dom.node_hierarchy.as_container()
            [*node_text_content_changed]
            .parent_id()
            .unwrap_or(NodeId::ZERO);
        nodes_that_changed_size.insert(parent);
    }
    nodes_that_changed_size.extend(node_ids_that_changed_text_content.into_iter());

    let css_property_cache = layout_result.styled_dom.get_css_property_cache();
    let node_data_container = layout_result.styled_dom.node_data.as_container();

    let mut all_offsets_to_recalc = BTreeMap::new();
    for node_id in nodes_that_changed_size.iter() {
        all_offsets_to_recalc.entry(*node_id).or_insert_with(|| {
            let styled_node_state =
                &layout_result.styled_dom.styled_nodes.as_container()[*node_id].state;
            precalculate_offset(
                &node_data_container[*node_id],
                &css_property_cache,
                node_id,
                styled_node_state,
            )
        });

        for child_id in node_id.az_children(&layout_result.styled_dom.node_hierarchy.as_container())
        {
            all_offsets_to_recalc.entry(child_id).or_insert_with(|| {
                let styled_node_state =
                    &layout_result.styled_dom.styled_nodes.as_container()[child_id].state;
                precalculate_offset(
                    &node_data_container[*node_id],
                    &css_property_cache,
                    &child_id,
                    styled_node_state,
                )
            });
        }
    }

    // update layout_result.rects and layout_result.glyph_cache
    // if positioned_word_cache changed, regenerate layouted_glyph_cache
    position_nodes(
        &mut layout_result.rects.as_ref_mut(),
        &layout_result.styled_dom,
        AllOffsetsProvider::OnlyRecalculatedNodes(&all_offsets_to_recalc),
        &layout_result.width_calculated_rects.as_ref(),
        &layout_result.height_calculated_rects.as_ref(),
        &layout_result.solved_pos_x.as_ref(),
        &layout_result.solved_pos_y.as_ref(),
        &nodes_that_changed_size,
        &nodes_that_changed_size,
        &layout_result.layout_positions.as_ref(),
        &layout_result.words_cache,
        &layout_result.shaped_words_cache,
        &layout_result.positioned_words_cache,
        document_id,
    );

    layout_result.root_size = root_bounds.size;
    layout_result.root_position = root_bounds.origin;

    if !nodes_that_changed_size.is_empty() {
        // TODO: optimize?
        get_nodes_that_need_scroll_clip(
            &mut layout_result.scrollable_nodes,
            &layout_result.styled_dom.styled_nodes.as_container(),
            &layout_result.styled_dom.node_data.as_container(),
            &layout_result.styled_dom.node_hierarchy.as_container(),
            &layout_result.rects.as_ref(),
            &layout_result.styled_dom.non_leaf_nodes.as_ref(),
            dom_id,
            document_id,
        );
    }

    let gpu_key_changes = layout_result
        .gpu_value_cache
        .synchronize(&layout_result.rects.as_ref(), &layout_result.styled_dom);

    let resized_nodes = nodes_that_changed_size.into_iter().collect();

    RelayoutChanges {
        resized_nodes,
        gpu_key_changes,
    }
}