Welcome to mirror list, hosted at ThFree Co, Russian Federation.

interface_layout.c « interface « editors « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 794cb53d5daf8375a2607e142808a83109eaf59a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
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
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

/** \file
 * \ingroup edinterface
 */

#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

#include "MEM_guardedalloc.h"

#include "DNA_armature_types.h"
#include "DNA_screen_types.h"
#include "DNA_userdef_types.h"

#include "BLI_alloca.h"
#include "BLI_dynstr.h"
#include "BLI_listbase.h"
#include "BLI_math.h"
#include "BLI_rect.h"
#include "BLI_string.h"
#include "BLI_utildefines.h"

#include "BLT_translation.h"

#include "BKE_anim_data.h"
#include "BKE_context.h"
#include "BKE_global.h"
#include "BKE_idprop.h"
#include "BKE_screen.h"

#include "RNA_access.h"

#include "UI_interface.h"

#include "ED_armature.h"

#include "WM_api.h"
#include "WM_types.h"

#include "interface_intern.h"

/* Show an icon button after each RNA button to use to quickly set keyframes,
 * this is a way to display animation/driven/override status, see T54951. */
#define UI_PROP_DECORATE
/* Alternate draw mode where some buttons can use single icon width,
 * giving more room for the text at the expense of nicely aligned text. */
#define UI_PROP_SEP_ICON_WIDTH_EXCEPTION

/* -------------------------------------------------------------------- */
/** \name Structs and Defines
 * \{ */

#define UI_OPERATOR_ERROR_RET(_ot, _opname, return_statement) \
  if (ot == NULL) { \
    ui_item_disabled(layout, _opname); \
    RNA_warning("'%s' unknown operator", _opname); \
    return_statement; \
  } \
  (void)0

#define UI_ITEM_PROP_SEP_DIVIDE 0.4f

/* uiLayoutRoot */

/**
 * A group of button references, used by property search to keep track of sets of buttons that
 * should be searched together. For example, in property split layouts number buttons and their
 * labels (and even their decorators) are separate buttons, but they must be searched and
 * highlighted together.
 */
typedef struct uiButtonGroup {
  void *next, *prev;
  ListBase buttons; /* #LinkData with #uiBut data field. */
} uiButtonGroup;

typedef struct uiLayoutRoot {
  struct uiLayoutRoot *next, *prev;

  int type;
  int opcontext;

  /**
   * If true, the root will be removed as part of the property search process.
   * Necessary for cases like searching the contents of closed panels, where the
   * block-level tag isn't enough because there might be buttons in the header.
   */
  bool search_only;

  ListBase button_groups; /* #uiButtonGroup. */

  int emw, emh;
  int padding;

  uiMenuHandleFunc handlefunc;
  void *argv;

  const uiStyle *style;
  uiBlock *block;
  uiLayout *layout;
} uiLayoutRoot;

/* Item */

typedef enum uiItemType {
  ITEM_BUTTON,

  ITEM_LAYOUT_ROW,
  ITEM_LAYOUT_COLUMN,
  ITEM_LAYOUT_COLUMN_FLOW,
  ITEM_LAYOUT_ROW_FLOW,
  ITEM_LAYOUT_GRID_FLOW,
  ITEM_LAYOUT_BOX,
  ITEM_LAYOUT_ABSOLUTE,
  ITEM_LAYOUT_SPLIT,
  ITEM_LAYOUT_OVERLAP,
  ITEM_LAYOUT_RADIAL,

  ITEM_LAYOUT_ROOT
#if 0
      TEMPLATE_COLUMN_FLOW,
  TEMPLATE_SPLIT,
  TEMPLATE_BOX,

  TEMPLATE_HEADER,
  TEMPLATE_HEADER_ID,
#endif
} uiItemType;

typedef struct uiItem {
  void *next, *prev;
  uiItemType type;
  int flag;
} uiItem;

enum {
  UI_ITEM_AUTO_FIXED_SIZE = 1 << 0,
  UI_ITEM_FIXED_SIZE = 1 << 1,

  UI_ITEM_BOX_ITEM = 1 << 2, /* The item is "inside" a box item */
  UI_ITEM_PROP_SEP = 1 << 3,
  UI_ITEM_INSIDE_PROP_SEP = 1 << 4,
  /* Show an icon button next to each property (to set keyframes, show status).
   * Enabled by default, depends on 'UI_ITEM_PROP_SEP'. */
  UI_ITEM_PROP_DECORATE = 1 << 5,
  UI_ITEM_PROP_DECORATE_NO_PAD = 1 << 6,
};

typedef struct uiButtonItem {
  uiItem item;
  uiBut *but;
} uiButtonItem;

struct uiLayout {
  uiItem item;

  uiLayoutRoot *root;
  bContextStore *context;
  uiLayout *parent;
  ListBase items;

  char heading[UI_MAX_NAME_STR];

  /** Sub layout to add child items, if not the layout itself. */
  uiLayout *child_items_layout;

  int x, y, w, h;
  float scale[2];
  short space;
  bool align;
  bool active;
  bool active_default;
  bool activate_init;
  bool enabled;
  bool redalert;
  bool keepaspect;
  /** For layouts inside gridflow, they and their items shall never have a fixed maximal size. */
  bool variable_size;
  char alignment;
  char emboss;
  /** for fixed width or height to avoid UI size changes */
  float units[2];
};

typedef struct uiLayoutItemFlow {
  uiLayout litem;
  int number;
  int totcol;
} uiLayoutItemFlow;

typedef struct uiLayoutItemGridFlow {
  uiLayout litem;

  /* Extra parameters */
  bool row_major;    /* Fill first row first, instead of filling first column first. */
  bool even_columns; /* Same width for all columns. */
  bool even_rows;    /* Same height for all rows. */
  /**
   * - If positive, absolute fixed number of columns.
   * - If 0, fully automatic (based on available width).
   * - If negative, automatic but only generates number of columns/rows
   *   multiple of given (absolute) value.
   */
  int columns_len;

  /* Pure internal runtime storage. */
  int tot_items, tot_columns, tot_rows;
} uiLayoutItemGridFlow;

typedef struct uiLayoutItemBx {
  uiLayout litem;
  uiBut *roundbox;
} uiLayoutItemBx;

typedef struct uiLayoutItemSplit {
  uiLayout litem;
  float percentage;
} uiLayoutItemSplit;

typedef struct uiLayoutItemRoot {
  uiLayout litem;
} uiLayoutItemRoot;

/** \} */

/* -------------------------------------------------------------------- */
/** \name Item
 * \{ */

static const char *ui_item_name_add_colon(const char *name, char namestr[UI_MAX_NAME_STR])
{
  const int len = strlen(name);

  if (len != 0 && len + 1 < UI_MAX_NAME_STR) {
    memcpy(namestr, name, len);
    namestr[len] = ':';
    namestr[len + 1] = '\0';
    return namestr;
  }

  return name;
}

static int ui_item_fit(
    int item, int pos, int all, int available, bool is_last, int alignment, float *extra_pixel)
{
  /* available == 0 is unlimited */
  if (ELEM(0, available, all)) {
    return item;
  }

  if (all > available) {
    /* contents is bigger than available space */
    if (is_last) {
      return available - pos;
    }

    const float width = *extra_pixel + (item * available) / (float)all;
    *extra_pixel = width - (int)width;
    return (int)width;
  }

  /* contents is smaller or equal to available space */
  if (alignment == UI_LAYOUT_ALIGN_EXPAND) {
    if (is_last) {
      return available - pos;
    }

    const float width = *extra_pixel + (item * available) / (float)all;
    *extra_pixel = width - (int)width;
    return (int)width;
  }
  return item;
}

/* variable button size in which direction? */
#define UI_ITEM_VARY_X 1
#define UI_ITEM_VARY_Y 2

static int ui_layout_vary_direction(uiLayout *layout)
{
  return ((ELEM(layout->root->type, UI_LAYOUT_HEADER, UI_LAYOUT_PIEMENU) ||
           (layout->alignment != UI_LAYOUT_ALIGN_EXPAND)) ?
              UI_ITEM_VARY_X :
              UI_ITEM_VARY_Y);
}

static bool ui_layout_variable_size(uiLayout *layout)
{
  /* Note that this code is probably a bit flakey, we'd probably want to know whether it's
   * variable in X and/or Y, etc. But for now it mimics previous one,
   * with addition of variable flag set for children of grid-flow layouts. */
  return ui_layout_vary_direction(layout) == UI_ITEM_VARY_X || layout->variable_size;
}

/* estimated size of text + icon */
static int ui_text_icon_width(uiLayout *layout, const char *name, int icon, bool compact)
{
  bool variable;
  const int unit_x = UI_UNIT_X * (layout->scale[0] ? layout->scale[0] : 1.0f);

  if (icon && !name[0]) {
    return unit_x; /* icon only */
  }

  variable = ui_layout_variable_size(layout);

  if (variable) {
    if (!icon && !name[0]) {
      return unit_x; /* No icon or name. */
    }
    if (layout->alignment != UI_LAYOUT_ALIGN_EXPAND) {
      layout->item.flag |= UI_ITEM_FIXED_SIZE;
    }
    const uiFontStyle *fstyle = UI_FSTYLE_WIDGET;
    float margin = compact ? 1.25 : 1.50;
    if (icon) {
      /* It may seem odd that the icon only adds (unit_x / 4)
       * but taking margins into account its fine, except
       * in compact mode a bit more margin is required. */
      margin += compact ? 0.35 : 0.25;
    }
    return UI_fontstyle_string_width(fstyle, name) + (unit_x * margin);
  }
  return unit_x * 10;
}

static void ui_item_size(uiItem *item, int *r_w, int *r_h)
{
  if (item->type == ITEM_BUTTON) {
    uiButtonItem *bitem = (uiButtonItem *)item;

    if (r_w) {
      *r_w = BLI_rctf_size_x(&bitem->but->rect);
    }
    if (r_h) {
      *r_h = BLI_rctf_size_y(&bitem->but->rect);
    }
  }
  else {
    uiLayout *litem = (uiLayout *)item;

    if (r_w) {
      *r_w = litem->w;
    }
    if (r_h) {
      *r_h = litem->h;
    }
  }
}

static void ui_item_offset(uiItem *item, int *r_x, int *r_y)
{
  if (item->type == ITEM_BUTTON) {
    uiButtonItem *bitem = (uiButtonItem *)item;

    if (r_x) {
      *r_x = bitem->but->rect.xmin;
    }
    if (r_y) {
      *r_y = bitem->but->rect.ymin;
    }
  }
  else {
    if (r_x) {
      *r_x = 0;
    }
    if (r_y) {
      *r_y = 0;
    }
  }
}

static void ui_item_position(uiItem *item, int x, int y, int w, int h)
{
  if (item->type == ITEM_BUTTON) {
    uiButtonItem *bitem = (uiButtonItem *)item;

    bitem->but->rect.xmin = x;
    bitem->but->rect.ymin = y;
    bitem->but->rect.xmax = x + w;
    bitem->but->rect.ymax = y + h;

    ui_but_update(bitem->but); /* for strlen */
  }
  else {
    uiLayout *litem = (uiLayout *)item;

    litem->x = x;
    litem->y = y + h;
    litem->w = w;
    litem->h = h;
  }
}

static void ui_item_move(uiItem *item, int delta_xmin, int delta_xmax)
{
  if (item->type == ITEM_BUTTON) {
    uiButtonItem *bitem = (uiButtonItem *)item;

    bitem->but->rect.xmin += delta_xmin;
    bitem->but->rect.xmax += delta_xmax;

    ui_but_update(bitem->but); /* for strlen */
  }
  else {
    uiLayout *litem = (uiLayout *)item;

    if (delta_xmin > 0) {
      litem->x += delta_xmin;
    }
    else {
      litem->w += delta_xmax;
    }
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Button Groups
 * \{ */

/**
 * Every function that adds a set of buttons must create another group,
 * then #ui_def_but adds buttons to the current group (the last).
 */
static void layout_root_new_button_group(uiLayoutRoot *root)
{
  uiButtonGroup *new_group = MEM_mallocN(sizeof(uiButtonGroup), __func__);
  BLI_listbase_clear(&new_group->buttons);
  BLI_addtail(&root->button_groups, new_group);
}

static void button_group_add_but(uiLayoutRoot *root, uiBut *but)
{
  BLI_assert(root != NULL);

  uiButtonGroup *current_button_group = root->button_groups.last;
  BLI_assert(current_button_group != NULL);

  /* We can't use the button directly because adding it to
   * this list would mess with its prev and next pointers. */
  LinkData *button_link = MEM_mallocN(sizeof(LinkData), __func__);
  button_link->data = but;
  BLI_addtail(&current_button_group->buttons, button_link);
}

static void button_group_free(uiButtonGroup *button_group)
{
  BLI_freelistN(&button_group->buttons);
  MEM_freeN(button_group);
}

/* This function should be removed whenever #ui_layout_replace_but_ptr is removed. */
void ui_button_group_replace_but_ptr(uiLayout *layout, const void *old_but_ptr, uiBut *new_but)
{
  LISTBASE_FOREACH (uiButtonGroup *, button_group, &layout->root->button_groups) {
    LISTBASE_FOREACH (LinkData *, link, &button_group->buttons) {
      if (link->data == old_but_ptr) {
        link->data = new_but;
        return;
      }
    }
  }

  /* The button should be in a group. */
  BLI_assert(false);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Special RNA Items
 * \{ */

int uiLayoutGetLocalDir(const uiLayout *layout)
{
  switch (layout->item.type) {
    case ITEM_LAYOUT_ROW:
    case ITEM_LAYOUT_ROOT:
    case ITEM_LAYOUT_OVERLAP:
      return UI_LAYOUT_HORIZONTAL;
    case ITEM_LAYOUT_COLUMN:
    case ITEM_LAYOUT_COLUMN_FLOW:
    case ITEM_LAYOUT_GRID_FLOW:
    case ITEM_LAYOUT_SPLIT:
    case ITEM_LAYOUT_ABSOLUTE:
    case ITEM_LAYOUT_BOX:
    default:
      return UI_LAYOUT_VERTICAL;
  }
}

static uiLayout *ui_item_local_sublayout(uiLayout *test, uiLayout *layout, bool align)
{
  uiLayout *sub;

  if (uiLayoutGetLocalDir(test) == UI_LAYOUT_HORIZONTAL) {
    sub = uiLayoutRow(layout, align);
  }
  else {
    sub = uiLayoutColumn(layout, align);
  }

  sub->space = 0;
  return sub;
}

static void ui_layer_but_cb(bContext *C, void *arg_but, void *arg_index)
{
  wmWindow *win = CTX_wm_window(C);
  uiBut *but = arg_but;
  PointerRNA *ptr = &but->rnapoin;
  PropertyRNA *prop = but->rnaprop;
  int index = POINTER_AS_INT(arg_index);
  const int shift = win->eventstate->shift;
  const int len = RNA_property_array_length(ptr, prop);

  if (!shift) {
    RNA_property_boolean_set_index(ptr, prop, index, true);

    for (int i = 0; i < len; i++) {
      if (i != index) {
        RNA_property_boolean_set_index(ptr, prop, i, 0);
      }
    }

    RNA_property_update(C, ptr, prop);

    LISTBASE_FOREACH (uiBut *, cbut, &but->block->buttons) {
      ui_but_update(cbut);
    }
  }
}

/* create buttons for an item with an RNA array */
static void ui_item_array(uiLayout *layout,
                          uiBlock *block,
                          const char *name,
                          int icon,
                          PointerRNA *ptr,
                          PropertyRNA *prop,
                          int len,
                          int x,
                          int y,
                          int w,
                          int UNUSED(h),
                          bool expand,
                          bool slider,
                          int toggle,
                          bool icon_only,
                          bool compact,
                          bool show_text)
{
  const uiStyle *style = layout->root->style;
  uiBut *but;
  PropertyType type;
  PropertySubType subtype;
  uiLayout *sub;
  uint a, b;

  /* retrieve type and subtype */
  type = RNA_property_type(prop);
  subtype = RNA_property_subtype(prop);

  sub = ui_item_local_sublayout(layout, layout, 1);
  UI_block_layout_set_current(block, sub);

  /* create label */
  if (name[0] && show_text) {
    uiDefBut(block, UI_BTYPE_LABEL, 0, name, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
  }

  /* create buttons */
  if (type == PROP_BOOLEAN && ELEM(subtype, PROP_LAYER, PROP_LAYER_MEMBER)) {
    /* special check for layer layout */
    int butw, buth, unit;
    const int cols = (len >= 20) ? 2 : 1;
    const uint colbuts = len / (2 * cols);
    uint layer_used = 0;
    uint layer_active = 0;

    UI_block_layout_set_current(block, uiLayoutAbsolute(layout, false));

    unit = UI_UNIT_X * 0.75;
    butw = unit;
    buth = unit;

    if (ptr->type == &RNA_Armature) {
      bArmature *arm = ptr->data;

      layer_used = arm->layer_used;

      if (arm->edbo) {
        if (arm->act_edbone) {
          layer_active |= arm->act_edbone->layer;
        }
      }
      else {
        if (arm->act_bone) {
          layer_active |= arm->act_bone->layer;
        }
      }
    }

    for (b = 0; b < cols; b++) {
      UI_block_align_begin(block);

      for (a = 0; a < colbuts; a++) {
        const int layer_num = a + b * colbuts;
        const uint layer_flag = (1u << layer_num);

        if (layer_used & layer_flag) {
          if (layer_active & layer_flag) {
            icon = ICON_LAYER_ACTIVE;
          }
          else {
            icon = ICON_LAYER_USED;
          }
        }
        else {
          icon = ICON_BLANK1;
        }

        but = uiDefAutoButR(
            block, ptr, prop, layer_num, "", icon, x + butw * a, y + buth, butw, buth);
        if (subtype == PROP_LAYER_MEMBER) {
          UI_but_func_set(but, ui_layer_but_cb, but, POINTER_FROM_INT(layer_num));
        }
      }
      for (a = 0; a < colbuts; a++) {
        const int layer_num = a + len / 2 + b * colbuts;
        const uint layer_flag = (1u << layer_num);

        if (layer_used & layer_flag) {
          if (layer_active & layer_flag) {
            icon = ICON_LAYER_ACTIVE;
          }
          else {
            icon = ICON_LAYER_USED;
          }
        }
        else {
          icon = ICON_BLANK1;
        }

        but = uiDefAutoButR(block, ptr, prop, layer_num, "", icon, x + butw * a, y, butw, buth);
        if (subtype == PROP_LAYER_MEMBER) {
          UI_but_func_set(but, ui_layer_but_cb, but, POINTER_FROM_INT(layer_num));
        }
      }
      UI_block_align_end(block);

      x += colbuts * butw + style->buttonspacex;
    }
  }
  else if (subtype == PROP_MATRIX) {
    int totdim, dim_size[3]; /* 3 == RNA_MAX_ARRAY_DIMENSION */
    int row, col;

    UI_block_layout_set_current(block, uiLayoutAbsolute(layout, true));

    totdim = RNA_property_array_dimension(ptr, prop, dim_size);
    if (totdim != 2) {
      /* Only 2D matrices supported in UI so far. */
      return;
    }

    w /= dim_size[0];
    /* h /= dim_size[1]; */ /* UNUSED */

    for (a = 0; a < len; a++) {
      col = a % dim_size[0];
      row = a / dim_size[0];

      but = uiDefAutoButR(block,
                          ptr,
                          prop,
                          a,
                          "",
                          ICON_NONE,
                          x + w * col,
                          y + (dim_size[1] * UI_UNIT_Y) - (row * UI_UNIT_Y),
                          w,
                          UI_UNIT_Y);
      if (slider && but->type == UI_BTYPE_NUM) {
        uiButNumber *number_but = (uiButNumber *)but;

        but->a1 = number_but->step_size;
        but = ui_but_change_type(but, UI_BTYPE_NUM_SLIDER);
      }
    }
  }
  else if (subtype == PROP_DIRECTION && !expand) {
    uiDefButR_prop(block,
                   UI_BTYPE_UNITVEC,
                   0,
                   name,
                   x,
                   y,
                   UI_UNIT_X * 3,
                   UI_UNIT_Y * 3,
                   ptr,
                   prop,
                   -1,
                   0,
                   0,
                   -1,
                   -1,
                   NULL);
  }
  else {
    /* note, this block of code is a bit arbitrary and has just been made
     * to work with common cases, but may need to be re-worked */

    /* special case, boolean array in a menu, this could be used in a more generic way too */
    if (ELEM(subtype, PROP_COLOR, PROP_COLOR_GAMMA) && !expand && ELEM(len, 3, 4)) {
      uiDefAutoButR(block, ptr, prop, -1, "", ICON_NONE, 0, 0, w, UI_UNIT_Y);
    }
    else {
      bool *boolarr = NULL;

      /* even if 'expand' is fale, expanding anyway */

      /* layout for known array subtypes */
      char str[3] = {'\0'};

      if (!icon_only && show_text) {
        if (type != PROP_BOOLEAN) {
          str[1] = ':';
        }
      }

      /* show checkboxes for rna on a non-emboss block (menu for eg) */
      if (type == PROP_BOOLEAN &&
          ELEM(layout->root->block->emboss, UI_EMBOSS_NONE, UI_EMBOSS_PULLDOWN)) {
        boolarr = MEM_callocN(sizeof(bool) * len, __func__);
        RNA_property_boolean_get_array(ptr, prop, boolarr);
      }

      const char *str_buf = show_text ? str : "";
      for (a = 0; a < len; a++) {
        int width_item;

        if (!icon_only && show_text) {
          str[0] = RNA_property_array_item_char(prop, a);
        }
        if (boolarr) {
          icon = boolarr[a] ? ICON_CHECKBOX_HLT : ICON_CHECKBOX_DEHLT;
        }

        width_item = ((compact && type == PROP_BOOLEAN) ?
                          min_ii(w, ui_text_icon_width(layout, str_buf, icon, false)) :
                          w);

        but = uiDefAutoButR(block, ptr, prop, a, str_buf, icon, 0, 0, width_item, UI_UNIT_Y);
        if (slider && but->type == UI_BTYPE_NUM) {
          uiButNumber *number_but = (uiButNumber *)but;

          but->a1 = number_but->step_size;
          but = ui_but_change_type(but, UI_BTYPE_NUM_SLIDER);
        }
        if ((toggle == 1) && but->type == UI_BTYPE_CHECKBOX) {
          but->type = UI_BTYPE_TOGGLE;
        }
        if ((a == 0) && (subtype == PROP_AXISANGLE)) {
          UI_but_unit_type_set(but, PROP_UNIT_ROTATION);
        }
      }

      if (boolarr) {
        MEM_freeN(boolarr);
      }
    }
  }

  UI_block_layout_set_current(block, layout);
}

static void ui_item_enum_expand_handle(bContext *C, void *arg1, void *arg2)
{
  wmWindow *win = CTX_wm_window(C);

  if (!win->eventstate->shift) {
    uiBut *but = (uiBut *)arg1;
    const int enum_value = POINTER_AS_INT(arg2);

    int current_value = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
    if (!(current_value & enum_value)) {
      current_value = enum_value;
    }
    else {
      current_value &= enum_value;
    }
    RNA_property_enum_set(&but->rnapoin, but->rnaprop, current_value);
  }
}

/**
 * Draw a single enum button, a utility for #ui_item_enum_expand_exec
 */
static void ui_item_enum_expand_elem_exec(uiLayout *layout,
                                          uiBlock *block,
                                          PointerRNA *ptr,
                                          PropertyRNA *prop,
                                          const char *uiname,
                                          const int h,
                                          const eButType but_type,
                                          const bool icon_only,
                                          const EnumPropertyItem *item,
                                          const bool is_first)
{
  const char *name = (!uiname || uiname[0]) ? item->name : "";
  const int icon = item->icon;
  const int value = item->value;
  const int itemw = ui_text_icon_width(block->curlayout, icon_only ? "" : name, icon, 0);

  uiBut *but;

  if (icon && name[0] && !icon_only) {
    but = uiDefIconTextButR_prop(
        block, but_type, 0, icon, name, 0, 0, itemw, h, ptr, prop, -1, 0, value, -1, -1, NULL);
  }
  else if (icon) {
    const int w = (is_first) ? itemw : ceilf(itemw - U.pixelsize);
    but = uiDefIconButR_prop(
        block, but_type, 0, icon, 0, 0, w, h, ptr, prop, -1, 0, value, -1, -1, NULL);
  }
  else {
    but = uiDefButR_prop(
        block, but_type, 0, name, 0, 0, itemw, h, ptr, prop, -1, 0, value, -1, -1, NULL);
  }

  if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
    /* If this is set, assert since we're clobbering someone elses callback. */
    /* Buttons get their block's func by default, so we cannot assert in that case either. */
    BLI_assert(ELEM(but->func, NULL, block->func));
    UI_but_func_set(but, ui_item_enum_expand_handle, but, POINTER_FROM_INT(value));
  }

  if (uiLayoutGetLocalDir(layout) != UI_LAYOUT_HORIZONTAL) {
    but->drawflag |= UI_BUT_TEXT_LEFT;
  }

  /* Allow quick, inaccurate swipe motions to switch tabs
   * (no need to keep cursor over them). */
  if (but_type == UI_BTYPE_TAB) {
    but->flag |= UI_BUT_DRAG_LOCK;
  }
}

static void ui_item_enum_expand_exec(uiLayout *layout,
                                     uiBlock *block,
                                     PointerRNA *ptr,
                                     PropertyRNA *prop,
                                     const char *uiname,
                                     const int h,
                                     const eButType but_type,
                                     const bool icon_only)
{
  /* XXX: The way this function currently handles uiname parameter
   * is insane and inconsistent with general UI API:
   *
   * - uiname is the *enum property* label.
   * - when it is NULL or empty, we do not draw *enum items* labels,
   *   this doubles the icon_only parameter.
   * - we *never* draw (i.e. really use) the enum label uiname, it is just used as a mere flag!
   *
   * Unfortunately, fixing this implies an API "soft break", so better to defer it for later... :/
   * - mont29
   */

  const EnumPropertyItem *item, *item_array;
  bool free;

  BLI_assert(RNA_property_type(prop) == PROP_ENUM);

  uiLayout *layout_radial = NULL;
  const bool radial = (layout->root->type == UI_LAYOUT_PIEMENU);
  if (radial) {
    RNA_property_enum_items_gettexted_all(block->evil_C, ptr, prop, &item_array, NULL, &free);
  }
  else {
    RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item_array, NULL, &free);
  }

  /* we dont want nested rows, cols in menus */
  if (radial) {
    if (layout->root->layout == layout) {
      layout_radial = uiLayoutRadial(layout);
      UI_block_layout_set_current(block, layout_radial);
    }
    else {
      if (layout->item.type == ITEM_LAYOUT_RADIAL) {
        layout_radial = layout;
      }
      UI_block_layout_set_current(block, layout);
    }
  }
  else if (ELEM(layout->item.type, ITEM_LAYOUT_GRID_FLOW, ITEM_LAYOUT_COLUMN_FLOW) ||
           layout->root->type == UI_LAYOUT_MENU) {
    UI_block_layout_set_current(block, layout);
  }
  else {
    UI_block_layout_set_current(block, ui_item_local_sublayout(layout, layout, 1));
  }

  for (item = item_array; item->identifier; item++) {
    const bool is_first = item == item_array;

    if (!item->identifier[0]) {
      const EnumPropertyItem *next_item = item + 1;

      /* Separate items, potentially with a label. */
      if (next_item->identifier) {
        /* Item without identifier but with name:
         * Add group label for the following items. */
        if (item->name) {
          if (!is_first) {
            uiItemS(block->curlayout);
          }
          uiItemL(block->curlayout, item->name, item->icon);
        }
        else if (radial && layout_radial) {
          uiItemS(layout_radial);
        }
        else {
          uiItemS(block->curlayout);
        }
      }
      continue;
    }

    ui_item_enum_expand_elem_exec(
        layout, block, ptr, prop, uiname, h, but_type, icon_only, item, is_first);
  }

  UI_block_layout_set_current(block, layout);

  if (free) {
    MEM_freeN((void *)item_array);
  }
}
static void ui_item_enum_expand(uiLayout *layout,
                                uiBlock *block,
                                PointerRNA *ptr,
                                PropertyRNA *prop,
                                const char *uiname,
                                const int h,
                                const bool icon_only)
{
  ui_item_enum_expand_exec(layout, block, ptr, prop, uiname, h, UI_BTYPE_ROW, icon_only);
}
static void ui_item_enum_expand_tabs(uiLayout *layout,
                                     bContext *C,
                                     uiBlock *block,
                                     PointerRNA *ptr,
                                     PropertyRNA *prop,
                                     PointerRNA *ptr_highlight,
                                     PropertyRNA *prop_highlight,
                                     const char *uiname,
                                     const int h,
                                     const bool icon_only)
{
  uiBut *last = block->buttons.last;

  ui_item_enum_expand_exec(layout, block, ptr, prop, uiname, h, UI_BTYPE_TAB, icon_only);
  BLI_assert(last != block->buttons.last);

  const bool use_custom_highlight = (prop_highlight != NULL);

  int custom_highlight_flag = 0; /* Max of 32 tabs. */
  if (use_custom_highlight) {
    BLI_assert(prop_highlight != NULL);
    BLI_assert(RNA_property_flag(prop_highlight) & PROP_ENUM_FLAG);
    custom_highlight_flag = RNA_property_enum_get(ptr_highlight, prop_highlight);
  }

  int i = 0;
  for (uiBut *tab = last ? last->next : block->buttons.first; tab; tab = tab->next) {
    UI_but_drawflag_enable(tab, ui_but_align_opposite_to_area_align_get(CTX_wm_region(C)));

    if (use_custom_highlight) {
      if (!(custom_highlight_flag & (1 << i))) {
        tab->flag |= UI_BUT_INACTIVE;
      }
    }
    i++;
  }
}

/* callback for keymap item change button */
static void ui_keymap_but_cb(bContext *UNUSED(C), void *but_v, void *UNUSED(key_v))
{
  uiBut *but = but_v;

  RNA_boolean_set(&but->rnapoin, "shift", (but->modifier_key & KM_SHIFT) != 0);
  RNA_boolean_set(&but->rnapoin, "ctrl", (but->modifier_key & KM_CTRL) != 0);
  RNA_boolean_set(&but->rnapoin, "alt", (but->modifier_key & KM_ALT) != 0);
  RNA_boolean_set(&but->rnapoin, "oskey", (but->modifier_key & KM_OSKEY) != 0);
}

/**
 * Create label + button for RNA property
 *
 * \param w_hint: For varying width layout, this becomes the label width.
 *                Otherwise it's used to fit both items into it.
 */
static uiBut *ui_item_with_label(uiLayout *layout,
                                 uiBlock *block,
                                 const char *name,
                                 int icon,
                                 PointerRNA *ptr,
                                 PropertyRNA *prop,
                                 int index,
                                 int x,
                                 int y,
                                 int w_hint,
                                 int h,
                                 int flag)
{
  uiLayout *sub = layout;
  uiBut *but = NULL;
  PropertyType type;
  PropertySubType subtype;
  int prop_but_width = w_hint;
#ifdef UI_PROP_DECORATE
  uiLayout *layout_prop_decorate = NULL;
  const bool use_prop_sep = ((layout->item.flag & UI_ITEM_PROP_SEP) != 0);
  const bool use_prop_decorate = use_prop_sep && (layout->item.flag & UI_ITEM_PROP_DECORATE) &&
                                 (layout->item.flag & UI_ITEM_PROP_DECORATE_NO_PAD) == 0;
#endif

  UI_block_layout_set_current(block, layout);

  /* Only add new row if more than 1 item will be added. */
  if (name[0] || use_prop_decorate) {
    /* Also avoid setting 'align' if possible. Set the space to zero instead as aligning a large
     * number of labels can end up aligning thousands of buttons when displaying key-map search (a
     * heavy operation), see: T78636. */
    sub = uiLayoutRow(layout, layout->align);
    sub->space = 0;
  }

#ifdef UI_PROP_DECORATE
  if (name[0]) {
    if (use_prop_sep) {
      layout_prop_decorate = uiItemL_respect_property_split(layout, name, 0);
    }
    else
#endif
    {
      int w_label;

      if (ui_layout_variable_size(layout)) {
        /* w_hint is width for label in this case.
         * Use a default width for property button(s) */
        prop_but_width = UI_UNIT_X * 5;
        w_label = w_hint;
      }
      else {
        w_label = w_hint / 3;
      }
      uiDefBut(block, UI_BTYPE_LABEL, 0, name, x, y, w_label, h, NULL, 0.0, 0.0, 0, 0, "");
    }
  }

  type = RNA_property_type(prop);
  subtype = RNA_property_subtype(prop);

  if (subtype == PROP_FILEPATH || subtype == PROP_DIRPATH) {
    UI_block_layout_set_current(block, uiLayoutRow(sub, true));
    but = uiDefAutoButR(block, ptr, prop, index, "", icon, x, y, prop_but_width - UI_UNIT_X, h);

    /* BUTTONS_OT_file_browse calls UI_context_active_but_prop_get_filebrowser */
    uiDefIconButO(block,
                  UI_BTYPE_BUT,
                  subtype == PROP_DIRPATH ? "BUTTONS_OT_directory_browse" :
                                            "BUTTONS_OT_file_browse",
                  WM_OP_INVOKE_DEFAULT,
                  ICON_FILEBROWSER,
                  x,
                  y,
                  UI_UNIT_X,
                  h,
                  NULL);
  }
  else if (flag & UI_ITEM_R_EVENT) {
    but = uiDefButR_prop(block,
                         UI_BTYPE_KEY_EVENT,
                         0,
                         name,
                         x,
                         y,
                         prop_but_width,
                         h,
                         ptr,
                         prop,
                         index,
                         0,
                         0,
                         -1,
                         -1,
                         NULL);
  }
  else if (flag & UI_ITEM_R_FULL_EVENT) {
    if (RNA_struct_is_a(ptr->type, &RNA_KeyMapItem)) {
      char buf[128];

      WM_keymap_item_to_string(ptr->data, false, buf, sizeof(buf));

      but = uiDefButR_prop(block,
                           UI_BTYPE_HOTKEY_EVENT,
                           0,
                           buf,
                           x,
                           y,
                           prop_but_width,
                           h,
                           ptr,
                           prop,
                           0,
                           0,
                           0,
                           -1,
                           -1,
                           NULL);
      UI_but_func_set(but, ui_keymap_but_cb, but, NULL);
      if (flag & UI_ITEM_R_IMMEDIATE) {
        UI_but_flag_enable(but, UI_BUT_IMMEDIATE);
      }
    }
  }
  else {
    const char *str = (type == PROP_ENUM && !(flag & UI_ITEM_R_ICON_ONLY)) ? NULL : "";
    but = uiDefAutoButR(block, ptr, prop, index, str, icon, x, y, prop_but_width, h);
  }

#ifdef UI_PROP_DECORATE
  /* Only for alignment. */
  if (use_prop_decorate) { /* Note that sep flag may have been unset meanwhile. */
    uiItemL(layout_prop_decorate ? layout_prop_decorate : sub, NULL, ICON_BLANK1);
  }
#endif /* UI_PROP_DECORATE */

  UI_block_layout_set_current(block, layout);
  return but;
}

void UI_context_active_but_prop_get_filebrowser(const bContext *C,
                                                PointerRNA *r_ptr,
                                                PropertyRNA **r_prop,
                                                bool *r_is_undo,
                                                bool *r_is_userdef)
{
  ARegion *region = CTX_wm_menu(C) ? CTX_wm_menu(C) : CTX_wm_region(C);
  uiBut *prevbut = NULL;

  memset(r_ptr, 0, sizeof(*r_ptr));
  *r_prop = NULL;
  *r_is_undo = false;
  *r_is_userdef = false;

  if (!region) {
    return;
  }

  LISTBASE_FOREACH (uiBlock *, block, &region->uiblocks) {
    LISTBASE_FOREACH (uiBut *, but, &block->buttons) {
      if (but && but->rnapoin.data) {
        if (RNA_property_type(but->rnaprop) == PROP_STRING) {
          prevbut = but;
        }
      }

      /* find the button before the active one */
      if ((but->flag & UI_BUT_LAST_ACTIVE) && prevbut) {
        *r_ptr = prevbut->rnapoin;
        *r_prop = prevbut->rnaprop;
        *r_is_undo = (prevbut->flag & UI_BUT_UNDO) != 0;
        *r_is_userdef = UI_but_is_userdef(prevbut);
        return;
      }
    }
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Button Items
 * \{ */

/**
 * Update a buttons tip with an enum's description if possible.
 */
static void ui_but_tip_from_enum_item(uiBut *but, const EnumPropertyItem *item)
{
  if (but->tip == NULL || but->tip[0] == '\0') {
    if (item->description && item->description[0] &&
        !(but->optype && but->optype->get_description)) {
      but->tip = item->description;
    }
  }
}

/* disabled item */
static void ui_item_disabled(uiLayout *layout, const char *name)
{
  uiBlock *block = layout->root->block;
  uiBut *but;
  int w;

  UI_block_layout_set_current(block, layout);

  if (!name) {
    name = "";
  }

  w = ui_text_icon_width(layout, name, 0, 0);

  but = uiDefBut(block, UI_BTYPE_LABEL, 0, name, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
  UI_but_disable(but, "");
}

/**
 * Operator Item
 * \param r_opptr: Optional, initialize with operator properties when not NULL.
 * Will always be written to even in the case of errors.
 */
static uiBut *uiItemFullO_ptr_ex(uiLayout *layout,
                                 wmOperatorType *ot,
                                 const char *name,
                                 int icon,
                                 IDProperty *properties,
                                 int context,
                                 int flag,
                                 PointerRNA *r_opptr)
{
  /* Take care to fill 'r_opptr' whatever happens. */
  uiBlock *block = layout->root->block;
  uiBut *but;
  int w;

  if (!name) {
    if (ot && ot->srna && (flag & UI_ITEM_R_ICON_ONLY) == 0) {
      name = WM_operatortype_name(ot, NULL);
    }
    else {
      name = "";
    }
  }

  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  /* create button */
  UI_block_layout_set_current(block, layout);

  w = ui_text_icon_width(layout, name, icon, 0);

  const int prev_emboss = layout->emboss;
  if (flag & UI_ITEM_R_NO_BG) {
    layout->emboss = UI_EMBOSS_NONE;
  }

  /* create the button */
  if (icon) {
    if (name[0]) {
      but = uiDefIconTextButO_ptr(
          block, UI_BTYPE_BUT, ot, context, icon, name, 0, 0, w, UI_UNIT_Y, NULL);
    }
    else {
      but = uiDefIconButO_ptr(block, UI_BTYPE_BUT, ot, context, icon, 0, 0, w, UI_UNIT_Y, NULL);
    }
  }
  else {
    but = uiDefButO_ptr(block, UI_BTYPE_BUT, ot, context, name, 0, 0, w, UI_UNIT_Y, NULL);
  }

  assert(but->optype != NULL);

  if (flag & UI_ITEM_R_NO_BG) {
    layout->emboss = prev_emboss;
  }

  if (flag & UI_ITEM_O_DEPRESS) {
    but->flag |= UI_SELECT_DRAW;
  }

  if (layout->redalert) {
    UI_but_flag_enable(but, UI_BUT_REDALERT);
  }

  if (layout->active_default) {
    UI_but_flag_enable(but, UI_BUT_ACTIVE_DEFAULT);
  }

  /* assign properties */
  if (properties || r_opptr) {
    PointerRNA *opptr = UI_but_operator_ptr_get(but);
    if (properties) {
      opptr->data = properties;
    }
    else {
      const IDPropertyTemplate val = {0};
      opptr->data = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
    }
    if (r_opptr) {
      *r_opptr = *opptr;
    }
  }

  return but;
}

static void ui_item_menu_hold(struct bContext *C, ARegion *butregion, uiBut *but)
{
  uiPopupMenu *pup = UI_popup_menu_begin(C, "", ICON_NONE);
  uiLayout *layout = UI_popup_menu_layout(pup);
  uiBlock *block = layout->root->block;
  UI_popup_menu_but_set(pup, butregion, but);

  block->flag |= UI_BLOCK_POPUP_HOLD;
  block->flag |= UI_BLOCK_IS_FLIP;

  char direction = UI_DIR_DOWN;
  if (!but->drawstr[0]) {
    switch (RGN_ALIGN_ENUM_FROM_MASK(butregion->alignment)) {
      case RGN_ALIGN_LEFT:
        direction = UI_DIR_RIGHT;
        break;
      case RGN_ALIGN_RIGHT:
        direction = UI_DIR_LEFT;
        break;
      case RGN_ALIGN_BOTTOM:
        direction = UI_DIR_UP;
        break;
      default:
        direction = UI_DIR_DOWN;
        break;
    }
  }
  UI_block_direction_set(block, direction);

  const char *menu_id = but->hold_argN;
  MenuType *mt = WM_menutype_find(menu_id, true);
  if (mt) {
    uiLayoutSetContextFromBut(layout, but);
    UI_menutype_draw(C, mt, layout);
  }
  else {
    uiItemL(layout, "Menu Missing:", ICON_NONE);
    uiItemL(layout, menu_id, ICON_NONE);
  }
  UI_popup_menu_end(C, pup);
}

void uiItemFullO_ptr(uiLayout *layout,
                     wmOperatorType *ot,
                     const char *name,
                     int icon,
                     IDProperty *properties,
                     int context,
                     int flag,
                     PointerRNA *r_opptr)
{
  uiItemFullO_ptr_ex(layout, ot, name, icon, properties, context, flag, r_opptr);
}

void uiItemFullOMenuHold_ptr(uiLayout *layout,
                             wmOperatorType *ot,
                             const char *name,
                             int icon,
                             IDProperty *properties,
                             int context,
                             int flag,
                             const char *menu_id,
                             PointerRNA *r_opptr)
{
  uiBut *but = uiItemFullO_ptr_ex(layout, ot, name, icon, properties, context, flag, r_opptr);
  UI_but_func_hold_set(but, ui_item_menu_hold, BLI_strdup(menu_id));
}

void uiItemFullO(uiLayout *layout,
                 const char *opname,
                 const char *name,
                 int icon,
                 IDProperty *properties,
                 int context,
                 int flag,
                 PointerRNA *r_opptr)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */

  UI_OPERATOR_ERROR_RET(ot, opname, {
    if (r_opptr) {
      *r_opptr = PointerRNA_NULL;
    }
    return;
  });

  uiItemFullO_ptr(layout, ot, name, icon, properties, context, flag, r_opptr);
}

static const char *ui_menu_enumpropname(uiLayout *layout,
                                        PointerRNA *ptr,
                                        PropertyRNA *prop,
                                        int retval)
{
  const EnumPropertyItem *item;
  bool free;
  const char *name;

  RNA_property_enum_items(layout->root->block->evil_C, ptr, prop, &item, NULL, &free);
  if (RNA_enum_name(item, retval, &name)) {
    name = CTX_IFACE_(RNA_property_translation_context(prop), name);
  }
  else {
    name = "";
  }

  if (free) {
    MEM_freeN((void *)item);
  }

  return name;
}

void uiItemEnumO_ptr(uiLayout *layout,
                     wmOperatorType *ot,
                     const char *name,
                     int icon,
                     const char *propname,
                     int value)
{
  PointerRNA ptr;
  PropertyRNA *prop;

  WM_operator_properties_create_ptr(&ptr, ot);

  if ((prop = RNA_struct_find_property(&ptr, propname))) {
    /* pass */
  }
  else {
    RNA_warning("%s.%s not found", RNA_struct_identifier(ptr.type), propname);
    return;
  }

  RNA_property_enum_set(&ptr, prop, value);

  if (!name) {
    name = ui_menu_enumpropname(layout, &ptr, prop, value);
  }

  uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemEnumO(uiLayout *layout,
                 const char *opname,
                 const char *name,
                 int icon,
                 const char *propname,
                 int value)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */

  if (ot) {
    uiItemEnumO_ptr(layout, ot, name, icon, propname, value);
  }
  else {
    ui_item_disabled(layout, opname);
    RNA_warning("unknown operator '%s'", opname);
  }
}

BLI_INLINE bool ui_layout_is_radial(const uiLayout *layout)
{
  return (layout->item.type == ITEM_LAYOUT_RADIAL) ||
         ((layout->item.type == ITEM_LAYOUT_ROOT) && (layout->root->type == UI_LAYOUT_PIEMENU));
}

/**
 * Create ui items for enum items in \a item_array.
 *
 * A version of #uiItemsFullEnumO that takes pre-calculated item array.
 */
void uiItemsFullEnumO_items(uiLayout *layout,
                            wmOperatorType *ot,
                            PointerRNA ptr,
                            PropertyRNA *prop,
                            IDProperty *properties,
                            int context,
                            int flag,
                            const EnumPropertyItem *item_array,
                            int totitem)
{
  const char *propname = RNA_property_identifier(prop);
  if (RNA_property_type(prop) != PROP_ENUM) {
    RNA_warning("%s.%s, not an enum type", RNA_struct_identifier(ptr.type), propname);
    return;
  }

  uiLayout *target, *split = NULL;
  const EnumPropertyItem *item;
  uiBlock *block = layout->root->block;
  const bool radial = ui_layout_is_radial(layout);

  if (radial) {
    target = uiLayoutRadial(layout);
  }
  else {
    split = uiLayoutSplit(layout, 0.0f, false);
    target = uiLayoutColumn(split, layout->align);
  }

  int i;
  bool last_iter = false;

  for (i = 1, item = item_array; item->identifier && !last_iter; i++, item++) {
    /* handle oversized pies */
    if (radial && (totitem > PIE_MAX_ITEMS) && (i >= PIE_MAX_ITEMS)) {
      if (item->name) { /* only visible items */
        const EnumPropertyItem *tmp;

        /* Check if there are more visible items for the next level. If not, we don't
         * add a new level and add the remaining item instead of the 'more' button. */
        for (tmp = item + 1; tmp->identifier; tmp++) {
          if (tmp->name) {
            break;
          }
        }

        if (tmp->identifier) { /* only true if loop above found item and did early-exit */
          ui_pie_menu_level_create(
              block, ot, propname, properties, item_array, totitem, context, flag);
          /* break since rest of items is handled in new pie level */
          break;
        }
        last_iter = true;
      }
      else {
        continue;
      }
    }

    if (item->identifier[0]) {
      PointerRNA tptr;

      WM_operator_properties_create_ptr(&tptr, ot);
      if (properties) {
        if (tptr.data) {
          IDP_FreeProperty(tptr.data);
        }
        tptr.data = IDP_CopyProperty(properties);
      }
      RNA_property_enum_set(&tptr, prop, item->value);

      uiItemFullO_ptr(target, ot, item->name, item->icon, tptr.data, context, flag, NULL);

      ui_but_tip_from_enum_item(block->buttons.last, item);
    }
    else {
      if (item->name) {
        uiBut *but;

        if (item != item_array && !radial) {
          target = uiLayoutColumn(split, layout->align);

          /* inconsistent, but menus with labels do not look good flipped */
          block->flag |= UI_BLOCK_NO_FLIP;
        }

        if (item->icon || radial) {
          uiItemL(target, item->name, item->icon);

          but = block->buttons.last;
        }
        else {
          /* Do not use uiItemL here, as our root layout is a menu one,
           * it will add a fake blank icon! */
          but = uiDefBut(block,
                         UI_BTYPE_LABEL,
                         0,
                         item->name,
                         0,
                         0,
                         UI_UNIT_X * 5,
                         UI_UNIT_Y,
                         NULL,
                         0.0,
                         0.0,
                         0,
                         0,
                         "");
        }
        ui_but_tip_from_enum_item(but, item);
      }
      else {
        if (radial) {
          /* invisible dummy button to ensure all items are
           * always at the same position */
          uiItemS(target);
        }
        else {
          /* XXX bug here, columns draw bottom item badly */
          uiItemS(target);
        }
      }
    }
  }
}

void uiItemsFullEnumO(uiLayout *layout,
                      const char *opname,
                      const char *propname,
                      IDProperty *properties,
                      int context,
                      int flag)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */

  PointerRNA ptr;
  PropertyRNA *prop;
  uiBlock *block = layout->root->block;

  if (!ot || !ot->srna) {
    ui_item_disabled(layout, opname);
    RNA_warning("%s '%s'", ot ? "unknown operator" : "operator missing srna", opname);
    return;
  }

  WM_operator_properties_create_ptr(&ptr, ot);
  /* so the context is passed to itemf functions (some need it) */
  WM_operator_properties_sanitize(&ptr, false);
  prop = RNA_struct_find_property(&ptr, propname);

  /* don't let bad properties slip through */
  BLI_assert((prop == NULL) || (RNA_property_type(prop) == PROP_ENUM));

  if (prop && RNA_property_type(prop) == PROP_ENUM) {
    const EnumPropertyItem *item_array = NULL;
    int totitem;
    bool free;

    if (ui_layout_is_radial(layout)) {
      /* XXX: While "_all()" guarantees spatial stability,
       * it's bad when an enum has > 8 items total,
       * but only a small subset will ever be shown at once
       * (e.g. Mode Switch menu, after the introduction of GP editing modes).
       */
#if 0
      RNA_property_enum_items_gettexted_all(
          block->evil_C, &ptr, prop, &item_array, &totitem, &free);
#else
      RNA_property_enum_items_gettexted(block->evil_C, &ptr, prop, &item_array, &totitem, &free);
#endif
    }
    else {
      RNA_property_enum_items_gettexted(block->evil_C, &ptr, prop, &item_array, &totitem, &free);
    }

    /* add items */
    uiItemsFullEnumO_items(layout, ot, ptr, prop, properties, context, flag, item_array, totitem);

    if (free) {
      MEM_freeN((void *)item_array);
    }

    /* intentionally don't touch UI_BLOCK_IS_FLIP here,
     * we don't know the context this is called in */
  }
  else if (prop && RNA_property_type(prop) != PROP_ENUM) {
    RNA_warning("%s.%s, not an enum type", RNA_struct_identifier(ptr.type), propname);
    return;
  }
  else {
    RNA_warning("%s.%s not found", RNA_struct_identifier(ptr.type), propname);
    return;
  }
}

void uiItemsEnumO(uiLayout *layout, const char *opname, const char *propname)
{
  uiItemsFullEnumO(layout, opname, propname, NULL, layout->root->opcontext, 0);
}

/* for use in cases where we have */
void uiItemEnumO_value(uiLayout *layout,
                       const char *name,
                       int icon,
                       const char *opname,
                       const char *propname,
                       int value)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
  PointerRNA ptr;
  PropertyRNA *prop;

  UI_OPERATOR_ERROR_RET(ot, opname, return );

  WM_operator_properties_create_ptr(&ptr, ot);

  /* enum lookup */
  if ((prop = RNA_struct_find_property(&ptr, propname))) {
    /* pass */
  }
  else {
    RNA_warning("%s.%s not found", RNA_struct_identifier(ptr.type), propname);
    return;
  }

  RNA_property_enum_set(&ptr, prop, value);

  /* same as uiItemEnumO */
  if (!name) {
    name = ui_menu_enumpropname(layout, &ptr, prop, value);
  }

  uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}

void uiItemEnumO_string(uiLayout *layout,
                        const char *name,
                        int icon,
                        const char *opname,
                        const char *propname,
                        const char *value_str)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
  PointerRNA ptr;
  PropertyRNA *prop;

  const EnumPropertyItem *item;
  int value;
  bool free;

  UI_OPERATOR_ERROR_RET(ot, opname, return );

  WM_operator_properties_create_ptr(&ptr, ot);

  /* enum lookup */
  if ((prop = RNA_struct_find_property(&ptr, propname))) {
    /* no need for translations here */
    RNA_property_enum_items(layout->root->block->evil_C, &ptr, prop, &item, NULL, &free);
    if (item == NULL || RNA_enum_value_from_id(item, value_str, &value) == 0) {
      if (free) {
        MEM_freeN((void *)item);
      }
      RNA_warning(
          "%s.%s, enum %s not found", RNA_struct_identifier(ptr.type), propname, value_str);
      return;
    }

    if (free) {
      MEM_freeN((void *)item);
    }
  }
  else {
    RNA_warning("%s.%s not found", RNA_struct_identifier(ptr.type), propname);
    return;
  }

  RNA_property_enum_set(&ptr, prop, value);

  /* same as uiItemEnumO */
  if (!name) {
    name = ui_menu_enumpropname(layout, &ptr, prop, value);
  }

  uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}

void uiItemBooleanO(uiLayout *layout,
                    const char *name,
                    int icon,
                    const char *opname,
                    const char *propname,
                    int value)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
  PointerRNA ptr;

  UI_OPERATOR_ERROR_RET(ot, opname, return );

  WM_operator_properties_create_ptr(&ptr, ot);
  RNA_boolean_set(&ptr, propname, value);

  uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}

void uiItemIntO(uiLayout *layout,
                const char *name,
                int icon,
                const char *opname,
                const char *propname,
                int value)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
  PointerRNA ptr;

  UI_OPERATOR_ERROR_RET(ot, opname, return );

  WM_operator_properties_create_ptr(&ptr, ot);
  RNA_int_set(&ptr, propname, value);

  uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}

void uiItemFloatO(uiLayout *layout,
                  const char *name,
                  int icon,
                  const char *opname,
                  const char *propname,
                  float value)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
  PointerRNA ptr;

  UI_OPERATOR_ERROR_RET(ot, opname, return );

  WM_operator_properties_create_ptr(&ptr, ot);
  RNA_float_set(&ptr, propname, value);

  uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}

void uiItemStringO(uiLayout *layout,
                   const char *name,
                   int icon,
                   const char *opname,
                   const char *propname,
                   const char *value)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
  PointerRNA ptr;

  UI_OPERATOR_ERROR_RET(ot, opname, return );

  WM_operator_properties_create_ptr(&ptr, ot);
  RNA_string_set(&ptr, propname, value);

  uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}

void uiItemO(uiLayout *layout, const char *name, int icon, const char *opname)
{
  uiItemFullO(layout, opname, name, icon, NULL, layout->root->opcontext, 0, NULL);
}

/* RNA property items */

static void ui_item_rna_size(uiLayout *layout,
                             const char *name,
                             int icon,
                             PointerRNA *ptr,
                             PropertyRNA *prop,
                             int index,
                             bool icon_only,
                             bool compact,
                             int *r_w,
                             int *r_h)
{
  PropertyType type;
  PropertySubType subtype;
  int len, w = 0, h;
  bool is_checkbox_only = false;

  /* arbitrary extended width by type */
  type = RNA_property_type(prop);
  subtype = RNA_property_subtype(prop);
  len = RNA_property_array_length(ptr, prop);

  if (!name[0] && !icon_only) {
    if (ELEM(type, PROP_STRING, PROP_POINTER)) {
      name = "non-empty text";
    }
    else if (type == PROP_BOOLEAN) {
      if (icon == ICON_NONE) {
        /* Exception for checkboxes, they need a little less space to align nicely. */
        is_checkbox_only = true;
      }
      icon = ICON_DOT;
    }
    else if (type == PROP_ENUM) {
      /* Find the longest enum item name, instead of using a dummy text! */
      const EnumPropertyItem *item, *item_array;
      bool free;

      RNA_property_enum_items_gettexted(
          layout->root->block->evil_C, ptr, prop, &item_array, NULL, &free);
      for (item = item_array; item->identifier; item++) {
        if (item->identifier[0]) {
          w = max_ii(w, ui_text_icon_width(layout, item->name, item->icon, compact));
        }
      }
      if (free) {
        MEM_freeN((void *)item_array);
      }
    }
  }

  if (!w) {
    if (type == PROP_ENUM && icon_only) {
      w = ui_text_icon_width(layout, "", ICON_BLANK1, compact);
      if (index != RNA_ENUM_VALUE) {
        w += 0.6f * UI_UNIT_X;
      }
    }
    else {
      /* not compact for float/int buttons, looks too squashed */
      w = ui_text_icon_width(
          layout, name, icon, ELEM(type, PROP_FLOAT, PROP_INT) ? false : compact);
    }
  }
  h = UI_UNIT_Y;

  /* increase height for arrays */
  if (index == RNA_NO_INDEX && len > 0) {
    if (!name[0] && icon == ICON_NONE) {
      h = 0;
    }
    if (layout->item.flag & UI_ITEM_PROP_SEP) {
      h = 0;
    }
    if (ELEM(subtype, PROP_LAYER, PROP_LAYER_MEMBER)) {
      h += 2 * UI_UNIT_Y;
    }
    else if (subtype == PROP_MATRIX) {
      h += ceilf(sqrtf(len)) * UI_UNIT_Y;
    }
    else {
      h += len * UI_UNIT_Y;
    }
  }

  /* Increase width requirement if in a variable size layout. */
  if (ui_layout_variable_size(layout)) {
    if (type == PROP_BOOLEAN && name[0]) {
      w += UI_UNIT_X / 5;
    }
    else if (is_checkbox_only) {
      w -= UI_UNIT_X / 4;
    }
    else if (type == PROP_ENUM && !icon_only) {
      w += UI_UNIT_X / 4;
    }
    else if (type == PROP_FLOAT || type == PROP_INT) {
      w += UI_UNIT_X * 3;
    }
  }

  *r_w = w;
  *r_h = h;
}

static bool ui_item_rna_is_expand(PropertyRNA *prop, int index, int item_flag)
{
  const bool is_array = RNA_property_array_check(prop);
  const int subtype = RNA_property_subtype(prop);
  return is_array && (index == RNA_NO_INDEX) &&
         ((item_flag & UI_ITEM_R_EXPAND) ||
          !ELEM(subtype, PROP_COLOR, PROP_COLOR_GAMMA, PROP_DIRECTION));
}

/**
 * Find first layout ancestor (or self) with a heading set.
 *
 * \returns the layout to add the heading to as fallback (i.e. if it can't be placed in a split
 *          layout). Its #uiLayout.heading member can be cleared to mark the heading as added (so
 *          it's not added multiple times). Returns a pointer to the heading
 */
static uiLayout *ui_layout_heading_find(uiLayout *cur_layout)
{
  for (uiLayout *parent = cur_layout; parent; parent = parent->parent) {
    if (parent->heading[0]) {
      return parent;
    }
  }

  return NULL;
}

static void ui_layout_heading_label_add(uiLayout *layout,
                                        uiLayout *heading_layout,
                                        bool right_align,
                                        bool respect_prop_split)
{
  const int prev_alignment = layout->alignment;

  if (right_align) {
    uiLayoutSetAlignment(layout, UI_LAYOUT_ALIGN_RIGHT);
  }

  if (respect_prop_split) {
    uiItemL_respect_property_split(layout, heading_layout->heading, ICON_NONE);
  }
  else {
    uiItemL(layout, heading_layout->heading, ICON_NONE);
  }
  /* After adding the heading label, we have to mark it somehow as added, so it's not added again
   * for other items in this layout. For now just clear it. */
  heading_layout->heading[0] = '\0';

  layout->alignment = prev_alignment;
}

/**
 * Hack to add further items in a row into the second part of the split layout, so the label part
 * keeps a fixed size.
 * \return The layout to place further items in for the split layout.
 */
static uiLayout *ui_item_prop_split_layout_hack(uiLayout *layout_parent, uiLayout *layout_split)
{
  /* Tag item as using property split layout, this is inherited to children so they can get special
   * treatment if needed. */
  layout_parent->item.flag |= UI_ITEM_INSIDE_PROP_SEP;

  if (layout_parent->item.type == ITEM_LAYOUT_ROW) {
    /* Prevent further splits within the row. */
    uiLayoutSetPropSep(layout_parent, false);

    layout_parent->child_items_layout = uiLayoutRow(layout_split, true);
    return layout_parent->child_items_layout;
  }
  return layout_split;
}

void uiItemFullR(uiLayout *layout,
                 PointerRNA *ptr,
                 PropertyRNA *prop,
                 int index,
                 int value,
                 int flag,
                 const char *name,
                 int icon)
{
  uiBlock *block = layout->root->block;
  char namestr[UI_MAX_NAME_STR];
  const bool use_prop_sep = ((layout->item.flag & UI_ITEM_PROP_SEP) != 0);
  const bool inside_prop_sep = ((layout->item.flag & UI_ITEM_INSIDE_PROP_SEP) != 0);
  /* Columns can define a heading to insert. If the first item added to a split layout doesn't have
   * a label to display in the first column, the heading is inserted there. Otherwise it's inserted
   * as a new row before the first item. */
  uiLayout *heading_layout = ui_layout_heading_find(layout);
  /* Although checkboxes use the split layout, they are an exception and should only place their
   * label in the second column, to not make that almost empty.
   *
   * Keep using 'use_prop_sep' instead of disabling it entirely because
   * we need the ability to have decorators still. */
  bool use_prop_sep_split_label = use_prop_sep;
  bool use_split_empty_name = (flag & UI_ITEM_R_SPLIT_EMPTY_NAME);

#ifdef UI_PROP_DECORATE
  struct {
    bool use_prop_decorate;
    int len;
    uiLayout *layout;
    uiBut *but;
  } ui_decorate = {
      .use_prop_decorate = (((layout->item.flag & UI_ITEM_PROP_DECORATE) != 0) && use_prop_sep),
  };
#endif /* UI_PROP_DECORATE */

  UI_block_layout_set_current(block, layout);
  layout_root_new_button_group(layout->root);

  /* retrieve info */
  const PropertyType type = RNA_property_type(prop);
  const bool is_array = RNA_property_array_check(prop);
  const int len = (is_array) ? RNA_property_array_length(ptr, prop) : 0;

  const bool icon_only = (flag & UI_ITEM_R_ICON_ONLY) != 0;

  /* Boolean with -1 to signify that the value depends on the presence of an icon. */
  const int toggle = ((flag & UI_ITEM_R_TOGGLE) ? 1 : ((flag & UI_ITEM_R_ICON_NEVER) ? 0 : -1));
  const bool no_icon = (toggle == 0);

  /* set name and icon */
  if (!name) {
    if (!icon_only) {
      name = RNA_property_ui_name(prop);
    }
    else {
      name = "";
    }
  }

  if (type != PROP_BOOLEAN) {
    flag &= ~UI_ITEM_R_CHECKBOX_INVERT;
  }

  if (flag & UI_ITEM_R_ICON_ONLY) {
    /* pass */
  }
  else if (ELEM(type, PROP_INT, PROP_FLOAT, PROP_STRING, PROP_POINTER)) {
    if (use_prop_sep == false) {
      name = ui_item_name_add_colon(name, namestr);
    }
  }
  else if (type == PROP_BOOLEAN && is_array && index == RNA_NO_INDEX) {
    if (use_prop_sep == false) {
      name = ui_item_name_add_colon(name, namestr);
    }
  }
  else if (type == PROP_ENUM && index != RNA_ENUM_VALUE) {
    if (flag & UI_ITEM_R_COMPACT) {
      name = "";
    }
    else {
      if (use_prop_sep == false) {
        name = ui_item_name_add_colon(name, namestr);
      }
    }
  }

  if (no_icon == false) {
    if (icon == ICON_NONE) {
      icon = RNA_property_ui_icon(prop);
    }

    /* Menus and pie-menus don't show checkbox without this. */
    if ((layout->root->type == UI_LAYOUT_MENU) ||
        /* Use checkboxes only as a fallback in pie-menu's, when no icon is defined. */
        ((layout->root->type == UI_LAYOUT_PIEMENU) && (icon == ICON_NONE))) {
      const int prop_flag = RNA_property_flag(prop);
      if (type == PROP_BOOLEAN) {
        if ((is_array == false) || (index != RNA_NO_INDEX)) {
          if (prop_flag & PROP_ICONS_CONSECUTIVE) {
            icon = ICON_CHECKBOX_DEHLT; /* but->iconadd will set to correct icon */
          }
          else if (is_array) {
            icon = (RNA_property_boolean_get_index(ptr, prop, index)) ? ICON_CHECKBOX_HLT :
                                                                        ICON_CHECKBOX_DEHLT;
          }
          else {
            icon = (RNA_property_boolean_get(ptr, prop)) ? ICON_CHECKBOX_HLT : ICON_CHECKBOX_DEHLT;
          }
        }
      }
      else if (type == PROP_ENUM) {
        if (index == RNA_ENUM_VALUE) {
          const int enum_value = RNA_property_enum_get(ptr, prop);
          if (prop_flag & PROP_ICONS_CONSECUTIVE) {
            icon = ICON_CHECKBOX_DEHLT; /* but->iconadd will set to correct icon */
          }
          else if (prop_flag & PROP_ENUM_FLAG) {
            icon = (enum_value & value) ? ICON_CHECKBOX_HLT : ICON_CHECKBOX_DEHLT;
          }
          else {
            icon = (enum_value == value) ? ICON_CHECKBOX_HLT : ICON_CHECKBOX_DEHLT;
          }
        }
      }
    }
  }

#ifdef UI_PROP_SEP_ICON_WIDTH_EXCEPTION
  if (use_prop_sep) {
    if (type == PROP_BOOLEAN && (icon == ICON_NONE) && !icon_only) {
      use_prop_sep_split_label = false;
      /* For check-boxes we make an exception: We allow showing them in a split row even without
       * label. It typically relates to its neighbor items, so no need for an extra label. */
      use_split_empty_name = true;
    }
  }
#endif

  if ((type == PROP_ENUM) && (RNA_property_flag(prop) & PROP_ENUM_FLAG)) {
    flag |= UI_ITEM_R_EXPAND;
  }

  const bool slider = (flag & UI_ITEM_R_SLIDER) != 0;
  const bool expand = (flag & UI_ITEM_R_EXPAND) != 0;
  const bool no_bg = (flag & UI_ITEM_R_NO_BG) != 0;
  const bool compact = (flag & UI_ITEM_R_COMPACT) != 0;

  /* get size */
  int w, h;
  ui_item_rna_size(layout, name, icon, ptr, prop, index, icon_only, compact, &w, &h);

  const int prev_emboss = layout->emboss;
  if (no_bg) {
    layout->emboss = UI_EMBOSS_NONE;
  }

  uiBut *but = NULL;

  /* Split the label / property. */
  uiLayout *layout_parent = layout;

  if (use_prop_sep) {
    uiLayout *layout_row = NULL;
#ifdef UI_PROP_DECORATE
    if (ui_decorate.use_prop_decorate) {
      layout_row = uiLayoutRow(layout, true);
      layout_row->space = 0;
      ui_decorate.len = max_ii(1, len);
    }
#endif /* UI_PROP_DECORATE */

    if ((name[0] == '\0') && !use_split_empty_name) {
      /* Ensure we get a column when text is not set. */
      layout = uiLayoutColumn(layout_row ? layout_row : layout, true);
      layout->space = 0;
      if (heading_layout) {
        ui_layout_heading_label_add(layout, heading_layout, false, false);
      }
    }
    else {
      uiLayout *layout_split = uiLayoutSplit(
          layout_row ? layout_row : layout, UI_ITEM_PROP_SEP_DIVIDE, true);
      bool label_added = false;
      layout_split->space = 0;
      uiLayout *layout_sub = uiLayoutColumn(layout_split, true);
      layout_sub->space = 0;

      if (!use_prop_sep_split_label) {
        /* Pass */
      }
      else if (ui_item_rna_is_expand(prop, index, flag)) {
        char name_with_suffix[UI_MAX_DRAW_STR + 2];
        char str[2] = {'\0'};
        for (int a = 0; a < len; a++) {
          str[0] = RNA_property_array_item_char(prop, a);
          const bool use_prefix = (a == 0 && name && name[0]);
          if (use_prefix) {
            char *s = name_with_suffix;
            s += STRNCPY_RLEN(name_with_suffix, name);
            *s++ = ' ';
            *s++ = str[0];
            *s++ = '\0';
          }
          but = uiDefBut(block,
                         UI_BTYPE_LABEL,
                         0,
                         use_prefix ? name_with_suffix : str,
                         0,
                         0,
                         w,
                         UI_UNIT_Y,
                         NULL,
                         0.0,
                         0.0,
                         0,
                         0,
                         "");
          but->drawflag |= UI_BUT_TEXT_RIGHT;
          but->drawflag &= ~UI_BUT_TEXT_LEFT;

          label_added = true;
        }
      }
      else {
        if (name) {
          but = uiDefBut(
              block, UI_BTYPE_LABEL, 0, name, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
          but->drawflag |= UI_BUT_TEXT_RIGHT;
          but->drawflag &= ~UI_BUT_TEXT_LEFT;

          label_added = true;
        }
      }

      if (!label_added && heading_layout) {
        ui_layout_heading_label_add(layout_sub, heading_layout, true, false);
      }

      layout_split = ui_item_prop_split_layout_hack(layout_parent, layout_split);

      /* Watch out! We can only write into the new layout now. */
      if ((type == PROP_ENUM) && (flag & UI_ITEM_R_EXPAND)) {
        /* Expanded enums each have their own name. */

        /* Often expanded enum's are better arranged into a row,
         * so check the existing layout. */
        if (uiLayoutGetLocalDir(layout) == UI_LAYOUT_HORIZONTAL) {
          layout = uiLayoutRow(layout_split, true);
        }
        else {
          layout = uiLayoutColumn(layout_split, true);
        }
      }
      else {
        if (use_prop_sep_split_label) {
          name = "";
        }
        layout = uiLayoutColumn(layout_split, true);
      }
      layout->space = 0;
    }

#ifdef UI_PROP_DECORATE
    if (ui_decorate.use_prop_decorate) {
      ui_decorate.layout = uiLayoutColumn(layout_row, true);
      ui_decorate.layout->space = 0;
      UI_block_layout_set_current(block, layout);
      ui_decorate.but = block->buttons.last;

      /* Clear after. */
      layout->item.flag |= UI_ITEM_PROP_DECORATE_NO_PAD;
    }
#endif /* UI_PROP_DECORATE */
  }
  /* End split. */
  else if (heading_layout) {
    /* Could not add heading to split layout, fallback to inserting it to the layout with the
     * heading itself. */
    ui_layout_heading_label_add(heading_layout, heading_layout, false, false);
  }

  /* array property */
  if (index == RNA_NO_INDEX && is_array) {
    if (inside_prop_sep) {
      /* Within a split row, add array items to a column so they match the column layout of
       * previous items (e.g. transform vector with lock icon for each item). */
      layout = uiLayoutColumn(layout, true);
    }

    ui_item_array(layout,
                  block,
                  name,
                  icon,
                  ptr,
                  prop,
                  len,
                  0,
                  0,
                  w,
                  h,
                  expand,
                  slider,
                  toggle,
                  icon_only,
                  compact,
                  !use_prop_sep_split_label);
  }
  /* enum item */
  else if (type == PROP_ENUM && index == RNA_ENUM_VALUE) {
    if (icon && name[0] && !icon_only) {
      uiDefIconTextButR_prop(
          block, UI_BTYPE_ROW, 0, icon, name, 0, 0, w, h, ptr, prop, -1, 0, value, -1, -1, NULL);
    }
    else if (icon) {
      uiDefIconButR_prop(
          block, UI_BTYPE_ROW, 0, icon, 0, 0, w, h, ptr, prop, -1, 0, value, -1, -1, NULL);
    }
    else {
      uiDefButR_prop(
          block, UI_BTYPE_ROW, 0, name, 0, 0, w, h, ptr, prop, -1, 0, value, -1, -1, NULL);
    }
  }
  /* expanded enum */
  else if (type == PROP_ENUM && expand) {
    ui_item_enum_expand(layout, block, ptr, prop, name, h, icon_only);
  }
  /* property with separate label */
  else if (type == PROP_ENUM || type == PROP_STRING || type == PROP_POINTER) {
    but = ui_item_with_label(layout, block, name, icon, ptr, prop, index, 0, 0, w, h, flag);
    but = ui_but_add_search(but, ptr, prop, NULL, NULL);

    if (layout->redalert) {
      UI_but_flag_enable(but, UI_BUT_REDALERT);
    }

    if (layout->activate_init) {
      UI_but_flag_enable(but, UI_BUT_ACTIVATE_ON_INIT);
    }
  }
  /* single button */
  else {
    but = uiDefAutoButR(block, ptr, prop, index, name, icon, 0, 0, w, h);

    if (slider && but->type == UI_BTYPE_NUM) {
      uiButNumber *num_but = (uiButNumber *)but;

      but->a1 = num_but->step_size;
      but = ui_but_change_type(but, UI_BTYPE_NUM_SLIDER);
    }

    if (flag & UI_ITEM_R_CHECKBOX_INVERT) {
      if (ELEM(but->type,
               UI_BTYPE_CHECKBOX,
               UI_BTYPE_CHECKBOX_N,
               UI_BTYPE_ICON_TOGGLE,
               UI_BTYPE_ICON_TOGGLE_N)) {
        but->drawflag |= UI_BUT_CHECKBOX_INVERT;
      }
    }

    if ((toggle == 1) && but->type == UI_BTYPE_CHECKBOX) {
      but->type = UI_BTYPE_TOGGLE;
    }

    if (layout->redalert) {
      UI_but_flag_enable(but, UI_BUT_REDALERT);
    }

    if (layout->activate_init) {
      UI_but_flag_enable(but, UI_BUT_ACTIVATE_ON_INIT);
    }
  }

  /* The resulting button may have the icon set since boolean button drawing
   * is being 'helpful' and adding an icon for us.
   * In this case we want the ability not to have an icon.
   *
   * We could pass an argument not to set the icon to begin with however this is the one case
   * the functionality is needed.  */
  if (but && no_icon) {
    if ((icon == ICON_NONE) && (but->icon != ICON_NONE)) {
      ui_def_but_icon_clear(but);
    }
  }

  /* Mark non-embossed textfields inside a listbox. */
  if (but && (block->flag & UI_BLOCK_LIST_ITEM) && (but->type == UI_BTYPE_TEXT) &&
      (but->emboss & UI_EMBOSS_NONE)) {
    UI_but_flag_enable(but, UI_BUT_LIST_ITEM);
  }

#ifdef UI_PROP_DECORATE
  if (ui_decorate.use_prop_decorate) {
    uiBut *but_decorate = ui_decorate.but ? ui_decorate.but->next : block->buttons.first;
    const bool use_blank_decorator = (flag & UI_ITEM_R_FORCE_BLANK_DECORATE);
    uiLayout *layout_col = uiLayoutColumn(ui_decorate.layout, false);
    layout_col->space = 0;
    layout_col->emboss = UI_EMBOSS_NONE;

    int i;
    for (i = 0; i < ui_decorate.len && but_decorate; i++) {
      PointerRNA *ptr_dec = use_blank_decorator ? NULL : &but_decorate->rnapoin;
      PropertyRNA *prop_dec = use_blank_decorator ? NULL : but_decorate->rnaprop;

      /* The icons are set in 'ui_but_anim_flag' */
      uiItemDecoratorR_prop(layout_col, ptr_dec, prop_dec, but_decorate->rnaindex);
      but = block->buttons.last;

      /* Order the decorator after the button we decorate, this is used so we can always
       * do a quick lookup. */
      BLI_remlink(&block->buttons, but);
      BLI_insertlinkafter(&block->buttons, but_decorate, but);
      but_decorate = but->next;
    }
    BLI_assert(ELEM(i, 1, ui_decorate.len));

    layout->item.flag &= ~UI_ITEM_PROP_DECORATE_NO_PAD;
  }
#endif /* UI_PROP_DECORATE */

  if (no_bg) {
    layout->emboss = prev_emboss;
  }

  /* ensure text isn't added to icon_only buttons */
  if (but && icon_only) {
    BLI_assert(but->str[0] == '\0');
  }
}

void uiItemR(
    uiLayout *layout, PointerRNA *ptr, const char *propname, int flag, const char *name, int icon)
{
  PropertyRNA *prop = RNA_struct_find_property(ptr, propname);

  if (!prop) {
    ui_item_disabled(layout, propname);
    RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }

  uiItemFullR(layout, ptr, prop, RNA_NO_INDEX, 0, flag, name, icon);
}

/**
 * Use a wrapper function since re-implementing all the logic in this function would be messy.
 */
void uiItemFullR_with_popover(uiLayout *layout,
                              PointerRNA *ptr,
                              PropertyRNA *prop,
                              int index,
                              int value,
                              int flag,
                              const char *name,
                              int icon,
                              const char *panel_type)
{
  uiBlock *block = layout->root->block;
  uiBut *but = block->buttons.last;
  uiItemFullR(layout, ptr, prop, index, value, flag, name, icon);
  but = but->next;
  while (but) {
    if (but->rnaprop == prop && ELEM(but->type, UI_BTYPE_MENU, UI_BTYPE_COLOR)) {
      ui_but_rna_menu_convert_to_panel_type(but, panel_type);
      break;
    }
    but = but->next;
  }
  if (but == NULL) {
    const char *propname = RNA_property_identifier(prop);
    ui_item_disabled(layout, panel_type);
    RNA_warning("property could not use a popover: %s.%s (%s)",
                RNA_struct_identifier(ptr->type),
                propname,
                panel_type);
  }
}

void uiItemFullR_with_menu(uiLayout *layout,
                           PointerRNA *ptr,
                           PropertyRNA *prop,
                           int index,
                           int value,
                           int flag,
                           const char *name,
                           int icon,
                           const char *menu_type)
{
  uiBlock *block = layout->root->block;
  uiBut *but = block->buttons.last;
  uiItemFullR(layout, ptr, prop, index, value, flag, name, icon);
  but = but->next;
  while (but) {
    if (but->rnaprop == prop && but->type == UI_BTYPE_MENU) {
      ui_but_rna_menu_convert_to_menu_type(but, menu_type);
      break;
    }
    but = but->next;
  }
  if (but == NULL) {
    const char *propname = RNA_property_identifier(prop);
    ui_item_disabled(layout, menu_type);
    RNA_warning("property could not use a menu: %s.%s (%s)",
                RNA_struct_identifier(ptr->type),
                propname,
                menu_type);
  }
}

void uiItemEnumR_prop(uiLayout *layout,
                      const char *name,
                      int icon,
                      struct PointerRNA *ptr,
                      PropertyRNA *prop,
                      int value)
{
  if (RNA_property_type(prop) != PROP_ENUM) {
    const char *propname = RNA_property_identifier(prop);
    ui_item_disabled(layout, propname);
    RNA_warning("property not an enum: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }

  uiItemFullR(layout, ptr, prop, RNA_ENUM_VALUE, value, 0, name, icon);
}

void uiItemEnumR(uiLayout *layout,
                 const char *name,
                 int icon,
                 struct PointerRNA *ptr,
                 const char *propname,
                 int value)
{
  PropertyRNA *prop = RNA_struct_find_property(ptr, propname);

  if (prop == NULL) {
    ui_item_disabled(layout, propname);
    RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }

  uiItemFullR(layout, ptr, prop, RNA_ENUM_VALUE, value, 0, name, icon);
}

void uiItemEnumR_string_prop(uiLayout *layout,
                             struct PointerRNA *ptr,
                             PropertyRNA *prop,
                             const char *value,
                             const char *name,
                             int icon)
{
  const EnumPropertyItem *item;
  int ivalue, a;
  bool free;

  if (UNLIKELY(RNA_property_type(prop) != PROP_ENUM)) {
    const char *propname = RNA_property_identifier(prop);
    ui_item_disabled(layout, propname);
    RNA_warning("not an enum property: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }

  RNA_property_enum_items(layout->root->block->evil_C, ptr, prop, &item, NULL, &free);

  if (!RNA_enum_value_from_id(item, value, &ivalue)) {
    const char *propname = RNA_property_identifier(prop);
    if (free) {
      MEM_freeN((void *)item);
    }
    ui_item_disabled(layout, propname);
    RNA_warning("enum property value not found: %s", value);
    return;
  }

  for (a = 0; item[a].identifier; a++) {
    if (item[a].identifier[0] == '\0') {
      /* Skip enum item separators. */
      continue;
    }
    if (item[a].value == ivalue) {
      const char *item_name = name ?
                                  name :
                                  CTX_IFACE_(RNA_property_translation_context(prop), item[a].name);
      const int flag = item_name[0] ? 0 : UI_ITEM_R_ICON_ONLY;

      uiItemFullR(
          layout, ptr, prop, RNA_ENUM_VALUE, ivalue, flag, item_name, icon ? icon : item[a].icon);
      break;
    }
  }

  if (free) {
    MEM_freeN((void *)item);
  }
}

void uiItemEnumR_string(uiLayout *layout,
                        struct PointerRNA *ptr,
                        const char *propname,
                        const char *value,
                        const char *name,
                        int icon)
{
  PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
  if (UNLIKELY(prop == NULL)) {
    ui_item_disabled(layout, propname);
    RNA_warning("enum property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }
  uiItemEnumR_string_prop(layout, ptr, prop, value, name, icon);
}

void uiItemsEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname)
{
  PropertyRNA *prop;
  uiBlock *block = layout->root->block;
  uiBut *bt;

  prop = RNA_struct_find_property(ptr, propname);

  if (!prop) {
    ui_item_disabled(layout, propname);
    RNA_warning("enum property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }

  if (RNA_property_type(prop) != PROP_ENUM) {
    RNA_warning("not an enum property: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }

  const EnumPropertyItem *item;
  int totitem;
  bool free;
  uiLayout *split = uiLayoutSplit(layout, 0.0f, false);
  uiLayout *column = uiLayoutColumn(split, false);

  RNA_property_enum_items_gettexted(block->evil_C, ptr, prop, &item, &totitem, &free);

  for (int i = 0; i < totitem; i++) {
    if (item[i].identifier[0]) {
      uiItemEnumR_prop(column, item[i].name, item[i].icon, ptr, prop, item[i].value);
      ui_but_tip_from_enum_item(block->buttons.last, &item[i]);
    }
    else {
      if (item[i].name) {
        if (i != 0) {
          column = uiLayoutColumn(split, false);
          /* inconsistent, but menus with labels do not look good flipped */
          block->flag |= UI_BLOCK_NO_FLIP;
        }

        uiItemL(column, item[i].name, ICON_NONE);
        bt = block->buttons.last;
        bt->drawflag = UI_BUT_TEXT_LEFT;

        ui_but_tip_from_enum_item(bt, &item[i]);
      }
      else {
        uiItemS(column);
      }
    }
  }

  if (free) {
    MEM_freeN((void *)item);
  }

  /* intentionally don't touch UI_BLOCK_IS_FLIP here,
   * we don't know the context this is called in */
}

/* Pointer RNA button with search */

static void search_id_collection(StructRNA *ptype, PointerRNA *r_ptr, PropertyRNA **r_prop)
{
  StructRNA *srna;

  /* look for collection property in Main */
  /* Note: using global Main is OK-ish here, UI shall not access other Mains anyay... */
  RNA_main_pointer_create(G_MAIN, r_ptr);

  *r_prop = NULL;

  RNA_STRUCT_BEGIN (r_ptr, iprop) {
    /* if it's a collection and has same pointer type, we've got it */
    if (RNA_property_type(iprop) == PROP_COLLECTION) {
      srna = RNA_property_pointer_type(r_ptr, iprop);

      if (ptype == srna) {
        *r_prop = iprop;
        break;
      }
    }
  }
  RNA_STRUCT_END;
}

static void ui_rna_collection_search_arg_free_fn(void *ptr)
{
  uiRNACollectionSearch *coll_search = ptr;
  UI_butstore_free(coll_search->butstore_block, coll_search->butstore);
  MEM_freeN(ptr);
}

/**
 * \note May reallocate \a but, so the possibly new address is returned.
 */
uiBut *ui_but_add_search(
    uiBut *but, PointerRNA *ptr, PropertyRNA *prop, PointerRNA *searchptr, PropertyRNA *searchprop)
{
  StructRNA *ptype;
  PointerRNA sptr;

  /* for ID's we do automatic lookup */
  if (!searchprop) {
    if (RNA_property_type(prop) == PROP_POINTER) {
      ptype = RNA_property_pointer_type(ptr, prop);
      search_id_collection(ptype, &sptr, &searchprop);
      searchptr = &sptr;
    }
  }

  /* turn button into search button */
  if (searchprop) {
    uiRNACollectionSearch *coll_search = MEM_mallocN(sizeof(*coll_search), __func__);
    uiButSearch *search_but;

    but = ui_but_change_type(but, UI_BTYPE_SEARCH_MENU);
    search_but = (uiButSearch *)but;
    search_but->rnasearchpoin = *searchptr;
    search_but->rnasearchprop = searchprop;
    but->hardmax = MAX2(but->hardmax, 256.0f);
    but->drawflag |= UI_BUT_ICON_LEFT | UI_BUT_TEXT_LEFT;
    if (RNA_property_is_unlink(prop)) {
      but->flag |= UI_BUT_VALUE_CLEAR;
    }

    coll_search->target_ptr = *ptr;
    coll_search->target_prop = prop;
    coll_search->search_ptr = *searchptr;
    coll_search->search_prop = searchprop;
    coll_search->search_but = but;
    coll_search->butstore_block = but->block;
    coll_search->butstore = UI_butstore_create(coll_search->butstore_block);
    UI_butstore_register(coll_search->butstore, &coll_search->search_but);

    if (RNA_property_type(prop) == PROP_ENUM) {
      /* XXX, this will have a menu string,
       * but in this case we just want the text */
      but->str[0] = 0;
    }

    UI_but_func_search_set(but,
                           ui_searchbox_create_generic,
                           ui_rna_collection_search_update_fn,
                           coll_search,
                           ui_rna_collection_search_arg_free_fn,
                           NULL,
                           NULL);
  }
  else if (but->type == UI_BTYPE_SEARCH_MENU) {
    /* In case we fail to find proper searchprop,
     * so other code might have already set but->type to search menu... */
    but->flag |= UI_BUT_DISABLED;
  }

  return but;
}

void uiItemPointerR_prop(uiLayout *layout,
                         PointerRNA *ptr,
                         PropertyRNA *prop,
                         PointerRNA *searchptr,
                         PropertyRNA *searchprop,
                         const char *name,
                         int icon)
{
  PropertyType type;
  uiBut *but;
  uiBlock *block;
  StructRNA *icontype;
  int w, h;
  char namestr[UI_MAX_NAME_STR];
  const bool use_prop_sep = ((layout->item.flag & UI_ITEM_PROP_SEP) != 0);

  layout_root_new_button_group(layout->root);

  type = RNA_property_type(prop);
  if (!ELEM(type, PROP_POINTER, PROP_STRING, PROP_ENUM)) {
    RNA_warning("Property %s.%s must be a pointer, string or enum",
                RNA_struct_identifier(ptr->type),
                RNA_property_identifier(prop));
    return;
  }
  if (RNA_property_type(searchprop) != PROP_COLLECTION) {
    RNA_warning("search collection property is not a collection type: %s.%s",
                RNA_struct_identifier(searchptr->type),
                RNA_property_identifier(searchprop));
    return;
  }

  /* get icon & name */
  if (icon == ICON_NONE) {
    if (type == PROP_POINTER) {
      icontype = RNA_property_pointer_type(ptr, prop);
    }
    else {
      icontype = RNA_property_pointer_type(searchptr, searchprop);
    }

    icon = RNA_struct_ui_icon(icontype);
  }
  if (!name) {
    name = RNA_property_ui_name(prop);
  }

  if (use_prop_sep == false) {
    name = ui_item_name_add_colon(name, namestr);
  }

  /* create button */
  block = uiLayoutGetBlock(layout);

  ui_item_rna_size(layout, name, icon, ptr, prop, 0, 0, false, &w, &h);
  w += UI_UNIT_X; /* X icon needs more space */
  but = ui_item_with_label(layout, block, name, icon, ptr, prop, 0, 0, 0, w, h, 0);

  ui_but_add_search(but, ptr, prop, searchptr, searchprop);
}

void uiItemPointerR(uiLayout *layout,
                    PointerRNA *ptr,
                    const char *propname,
                    PointerRNA *searchptr,
                    const char *searchpropname,
                    const char *name,
                    int icon)
{
  PropertyRNA *prop, *searchprop;

  /* validate arguments */
  prop = RNA_struct_find_property(ptr, propname);
  if (!prop) {
    RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }
  searchprop = RNA_struct_find_property(searchptr, searchpropname);
  if (!searchprop) {
    RNA_warning("search collection property not found: %s.%s",
                RNA_struct_identifier(searchptr->type),
                searchpropname);
    return;
  }

  uiItemPointerR_prop(layout, ptr, prop, searchptr, searchprop, name, icon);
}

/* menu item */
void ui_item_menutype_func(bContext *C, uiLayout *layout, void *arg_mt)
{
  MenuType *mt = (MenuType *)arg_mt;

  UI_menutype_draw(C, mt, layout);

  /* menus are created flipped (from event handling pov) */
  layout->root->block->flag ^= UI_BLOCK_IS_FLIP;
}

void ui_item_paneltype_func(bContext *C, uiLayout *layout, void *arg_pt)
{
  PanelType *pt = (PanelType *)arg_pt;
  UI_paneltype_draw(C, pt, layout);

  /* panels are created flipped (from event handling pov) */
  layout->root->block->flag ^= UI_BLOCK_IS_FLIP;
}

static uiBut *ui_item_menu(uiLayout *layout,
                           const char *name,
                           int icon,
                           uiMenuCreateFunc func,
                           void *arg,
                           void *argN,
                           const char *tip,
                           bool force_menu)
{
  uiBlock *block = layout->root->block;
  uiLayout *heading_layout = ui_layout_heading_find(layout);
  uiBut *but;
  int w, h;

  UI_block_layout_set_current(block, layout);
  layout_root_new_button_group(layout->root);

  if (!name) {
    name = "";
  }
  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  w = ui_text_icon_width(layout, name, icon, 1);
  h = UI_UNIT_Y;

  if (layout->root->type == UI_LAYOUT_HEADER) { /* ugly .. */
    if (icon == ICON_NONE && force_menu) {
      /* pass */
    }
    else if (force_menu) {
      w += 0.6f * UI_UNIT_X;
    }
    else {
      if (name[0]) {
        w -= UI_UNIT_X / 2;
      }
    }
  }

  if (heading_layout) {
    ui_layout_heading_label_add(layout, heading_layout, true, true);
  }

  if (name[0] && icon) {
    but = uiDefIconTextMenuBut(block, func, arg, icon, name, 0, 0, w, h, tip);
  }
  else if (icon) {
    but = uiDefIconMenuBut(block, func, arg, icon, 0, 0, w, h, tip);
    if (force_menu && name[0]) {
      UI_but_drawflag_enable(but, UI_BUT_ICON_LEFT);
    }
  }
  else {
    but = uiDefMenuBut(block, func, arg, name, 0, 0, w, h, tip);
  }

  if (argN) {
    /* ugly .. */
    if (arg != argN) {
      but->poin = (char *)but;
    }
    but->func_argN = argN;
  }

  if (ELEM(layout->root->type, UI_LAYOUT_PANEL, UI_LAYOUT_TOOLBAR) ||
      /* We never want a dropdown in menu! */
      (force_menu && layout->root->type != UI_LAYOUT_MENU)) {
    UI_but_type_set_menu_from_pulldown(but);
  }

  return but;
}

void uiItemM_ptr(uiLayout *layout, MenuType *mt, const char *name, int icon)
{
  if (!name) {
    name = CTX_IFACE_(mt->translation_context, mt->label);
  }

  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  ui_item_menu(layout,
               name,
               icon,
               ui_item_menutype_func,
               mt,
               NULL,
               mt->description ? TIP_(mt->description) : "",
               false);
}

void uiItemM(uiLayout *layout, const char *menuname, const char *name, int icon)
{
  MenuType *mt = WM_menutype_find(menuname, false);
  if (mt == NULL) {
    RNA_warning("not found %s", menuname);
    return;
  }
  uiItemM_ptr(layout, mt, name, icon);
}

void uiItemMContents(uiLayout *layout, const char *menuname)
{
  MenuType *mt = WM_menutype_find(menuname, false);
  if (mt == NULL) {
    RNA_warning("not found %s", menuname);
    return;
  }

  uiBlock *block = layout->root->block;
  bContext *C = block->evil_C;
  UI_menutype_draw(C, mt, layout);
}

/**
 * Insert a decorator item for a button with the same property as \a prop.
 * To force inserting a blank dummy element, NULL can be passed for \a ptr and \a prop.
 */
void uiItemDecoratorR_prop(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index)
{
  uiBlock *block = layout->root->block;
  uiLayout *col;

  UI_block_layout_set_current(block, layout);
  col = uiLayoutColumn(layout, false);
  col->space = 0;
  col->emboss = UI_EMBOSS_NONE;

  if (ELEM(NULL, ptr, prop) || !RNA_property_animateable(ptr, prop)) {
    uiBut *but = uiDefIconBut(block,
                              UI_BTYPE_DECORATOR,
                              0,
                              ICON_BLANK1,
                              0,
                              0,
                              UI_UNIT_X,
                              UI_UNIT_Y,
                              NULL,
                              0.0,
                              0.0,
                              0.0,
                              0.0,
                              "");
    but->flag |= UI_BUT_DISABLED;
    return;
  }

  const bool is_expand = ui_item_rna_is_expand(prop, index, 0);
  const bool is_array = RNA_property_array_check(prop);

  /* Loop for the array-case, but only do in case of an expanded array. */
  for (int i = 0; i < (is_expand ? RNA_property_array_length(ptr, prop) : 1); i++) {
    uiButDecorator *decorator_but = (uiButDecorator *)uiDefIconBut(block,
                                                                   UI_BTYPE_DECORATOR,
                                                                   0,
                                                                   ICON_DOT,
                                                                   0,
                                                                   0,
                                                                   UI_UNIT_X,
                                                                   UI_UNIT_Y,
                                                                   NULL,
                                                                   0.0,
                                                                   0.0,
                                                                   0.0,
                                                                   0.0,
                                                                   TIP_("Animate property"));

    UI_but_func_set(&decorator_but->but, ui_but_anim_decorate_cb, decorator_but, NULL);
    decorator_but->but.flag |= UI_BUT_UNDO | UI_BUT_DRAG_LOCK;
    /* Reusing RNA search members, setting actual RNA data has many side-effects. */
    decorator_but->rnapoin = *ptr;
    decorator_but->rnaprop = prop;
    /* ui_def_but_rna() sets non-array buttons to have a RNA index of 0. */
    decorator_but->rnaindex = (!is_array || is_expand) ? i : index;
  }
}

/**
 * Insert a decorator item for a button with the same property as \a prop.
 * To force inserting a blank dummy element, NULL can be passed for \a ptr and \a propname.
 */
void uiItemDecoratorR(uiLayout *layout, PointerRNA *ptr, const char *propname, int index)
{
  PropertyRNA *prop = NULL;

  if (ptr && propname) {
    /* validate arguments */
    prop = RNA_struct_find_property(ptr, propname);
    if (!prop) {
      ui_item_disabled(layout, propname);
      RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
      return;
    }
  }

  /* ptr and prop are allowed to be NULL here. */
  uiItemDecoratorR_prop(layout, ptr, prop, index);
}

/* popover */
void uiItemPopoverPanel_ptr(
    uiLayout *layout, bContext *C, PanelType *pt, const char *name, int icon)
{
  if (!name) {
    name = CTX_IFACE_(pt->translation_context, pt->label);
  }

  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  const bool ok = (pt->poll == NULL) || pt->poll(C, pt);
  if (ok && (pt->draw_header != NULL)) {
    layout = uiLayoutRow(layout, true);
    Panel panel = {
        .type = pt,
        .layout = layout,
        .flag = PNL_POPOVER,
    };
    pt->draw_header(C, &panel);
  }
  uiBut *but = ui_item_menu(layout, name, icon, ui_item_paneltype_func, pt, NULL, NULL, true);
  but->type = UI_BTYPE_POPOVER;
  if (!ok) {
    but->flag |= UI_BUT_DISABLED;
  }
}

void uiItemPopoverPanel(
    uiLayout *layout, bContext *C, const char *panel_type, const char *name, int icon)
{
  PanelType *pt = WM_paneltype_find(panel_type, true);
  if (pt == NULL) {
    RNA_warning("Panel type not found '%s'", panel_type);
    return;
  }
  uiItemPopoverPanel_ptr(layout, C, pt, name, icon);
}

void uiItemPopoverPanelFromGroup(uiLayout *layout,
                                 bContext *C,
                                 int space_id,
                                 int region_id,
                                 const char *context,
                                 const char *category)
{
  SpaceType *st = BKE_spacetype_from_id(space_id);
  if (st == NULL) {
    RNA_warning("space type not found %d", space_id);
    return;
  }
  ARegionType *art = BKE_regiontype_from_id(st, region_id);
  if (art == NULL) {
    RNA_warning("region type not found %d", region_id);
    return;
  }

  LISTBASE_FOREACH (PanelType *, pt, &art->paneltypes) {
    /* Causes too many panels, check context. */
    if (pt->parent_id[0] == '\0') {
      if (/* (*context == '\0') || */ STREQ(pt->context, context)) {
        if ((*category == '\0') || STREQ(pt->category, category)) {
          if (pt->poll == NULL || pt->poll(C, pt)) {
            uiItemPopoverPanel_ptr(layout, C, pt, NULL, ICON_NONE);
          }
        }
      }
    }
  }
}

/* label item */
static uiBut *uiItemL_(uiLayout *layout, const char *name, int icon)
{
  uiBlock *block = layout->root->block;
  uiBut *but;
  int w;

  UI_block_layout_set_current(block, layout);
  layout_root_new_button_group(layout->root);

  if (!name) {
    name = "";
  }
  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  w = ui_text_icon_width(layout, name, icon, 0);

  if (icon && name[0]) {
    but = uiDefIconTextBut(
        block, UI_BTYPE_LABEL, 0, icon, name, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, NULL);
  }
  else if (icon) {
    but = uiDefIconBut(
        block, UI_BTYPE_LABEL, 0, icon, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, NULL);
  }
  else {
    but = uiDefBut(block, UI_BTYPE_LABEL, 0, name, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, NULL);
  }

  /* to compensate for string size padding in ui_text_icon_width,
   * make text aligned right if the layout is aligned right.
   */
  if (uiLayoutGetAlignment(layout) == UI_LAYOUT_ALIGN_RIGHT) {
    but->drawflag &= ~UI_BUT_TEXT_LEFT; /* default, needs to be unset */
    but->drawflag |= UI_BUT_TEXT_RIGHT;
  }

  /* Mark as a label inside a listbox. */
  if (block->flag & UI_BLOCK_LIST_ITEM) {
    but->flag |= UI_BUT_LIST_ITEM;
  }

  if (layout->redalert) {
    UI_but_flag_enable(but, UI_BUT_REDALERT);
  }

  return but;
}

void uiItemL_ex(
    uiLayout *layout, const char *name, int icon, const bool highlight, const bool redalert)
{
  uiBut *but = uiItemL_(layout, name, icon);

  if (highlight) {
    /* TODO: add another flag for this. */
    UI_but_flag_enable(but, UI_SELECT_DRAW);
  }

  if (redalert) {
    UI_but_flag_enable(but, UI_BUT_REDALERT);
  }
}

void uiItemL(uiLayout *layout, const char *name, int icon)
{
  uiItemL_(layout, name, icon);
}

/**
 * Normally, we handle the split layout in #uiItemFullR(), but there are other cases where the
 * logic is needed. Ideally, #uiItemFullR() could just call this, but it currently has too many
 * special needs.
 */
uiPropertySplitWrapper uiItemPropertySplitWrapperCreate(uiLayout *parent_layout)
{
  uiPropertySplitWrapper split_wrapper = {NULL};

  uiLayout *layout_row = uiLayoutRow(parent_layout, true);
  uiLayout *layout_split = uiLayoutSplit(layout_row, UI_ITEM_PROP_SEP_DIVIDE, true);

  layout_split->space = 0;
  split_wrapper.label_column = uiLayoutColumn(layout_split, true);
  split_wrapper.label_column->alignment = UI_LAYOUT_ALIGN_RIGHT;
  split_wrapper.property_row = ui_item_prop_split_layout_hack(parent_layout, layout_split);
  split_wrapper.decorate_column = uiLayoutColumn(layout_row, true);

  return split_wrapper;
}

/*
 * Helper to add a label and creates a property split layout if needed.
 */
uiLayout *uiItemL_respect_property_split(uiLayout *layout, const char *text, int icon)
{
  if (layout->item.flag & UI_ITEM_PROP_SEP) {
    uiBlock *block = uiLayoutGetBlock(layout);
    const uiPropertySplitWrapper split_wrapper = uiItemPropertySplitWrapperCreate(layout);
    /* Further items added to 'layout' will automatically be added to split_wrapper.property_row */

    uiItemL_(split_wrapper.label_column, text, icon);
    UI_block_layout_set_current(block, split_wrapper.property_row);

    return split_wrapper.decorate_column;
  }

  char namestr[UI_MAX_NAME_STR];
  if (text) {
    text = ui_item_name_add_colon(text, namestr);
  }
  uiItemL_(layout, text, icon);

  return layout;
}

void uiItemLDrag(uiLayout *layout, PointerRNA *ptr, const char *name, int icon)
{
  uiBut *but = uiItemL_(layout, name, icon);

  if (ptr && ptr->type) {
    if (RNA_struct_is_ID(ptr->type)) {
      UI_but_drag_set_id(but, ptr->owner_id);
    }
  }
}

/* value item */
void uiItemV(uiLayout *layout, const char *name, int icon, int argval)
{
  /* label */
  uiBlock *block = layout->root->block;
  int *retvalue = (block->handle) ? &block->handle->retvalue : NULL;
  int w;

  UI_block_layout_set_current(block, layout);

  if (!name) {
    name = "";
  }
  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  w = ui_text_icon_width(layout, name, icon, 0);

  if (icon && name[0]) {
    uiDefIconTextButI(block,
                      UI_BTYPE_BUT,
                      argval,
                      icon,
                      name,
                      0,
                      0,
                      w,
                      UI_UNIT_Y,
                      retvalue,
                      0.0,
                      0.0,
                      0,
                      -1,
                      "");
  }
  else if (icon) {
    uiDefIconButI(
        block, UI_BTYPE_BUT, argval, icon, 0, 0, w, UI_UNIT_Y, retvalue, 0.0, 0.0, 0, -1, "");
  }
  else {
    uiDefButI(
        block, UI_BTYPE_BUT, argval, name, 0, 0, w, UI_UNIT_Y, retvalue, 0.0, 0.0, 0, -1, "");
  }
}

/* separator item */
void uiItemS_ex(uiLayout *layout, float factor)
{
  uiBlock *block = layout->root->block;
  const bool is_menu = ui_block_is_menu(block);
  if (is_menu && !UI_block_can_add_separator(block)) {
    return;
  }
  int space = (is_menu) ? 0.45f * UI_UNIT_X : 0.3f * UI_UNIT_X;
  space *= factor;

  UI_block_layout_set_current(block, layout);
  uiDefBut(block,
           (is_menu) ? UI_BTYPE_SEPR_LINE : UI_BTYPE_SEPR,
           0,
           "",
           0,
           0,
           space,
           space,
           NULL,
           0.0,
           0.0,
           0,
           0,
           "");
}

/* separator item */
void uiItemS(uiLayout *layout)
{
  uiItemS_ex(layout, 1.0f);
}

/* Flexible spacing. */
void uiItemSpacer(uiLayout *layout)
{
  uiBlock *block = layout->root->block;
  const bool is_popup = ui_block_is_popup_any(block);

  if (is_popup) {
    printf("Error: separator_spacer() not supported in popups.\n");
    return;
  }

  if (block->direction & UI_DIR_RIGHT) {
    printf("Error: separator_spacer() only supported in horizontal blocks.\n");
    return;
  }

  UI_block_layout_set_current(block, layout);
  uiDefBut(block,
           UI_BTYPE_SEPR_SPACER,
           0,
           "",
           0,
           0,
           0.3f * UI_UNIT_X,
           UI_UNIT_Y,
           NULL,
           0.0,
           0.0,
           0,
           0,
           "");
}

/* level items */
void uiItemMenuF(uiLayout *layout, const char *name, int icon, uiMenuCreateFunc func, void *arg)
{
  if (!func) {
    return;
  }

  ui_item_menu(layout, name, icon, func, arg, NULL, "", false);
}

/**
 * Version of #uiItemMenuF that free's `argN`.
 */
void uiItemMenuFN(uiLayout *layout, const char *name, int icon, uiMenuCreateFunc func, void *argN)
{
  if (!func) {
    return;
  }

  /* Second 'argN' only ensures it gets freed. */
  ui_item_menu(layout, name, icon, func, argN, argN, "", false);
}

typedef struct MenuItemLevel {
  int opcontext;
  /* don't use pointers to the strings because python can dynamically
   * allocate strings and free before the menu draws, see [#27304] */
  char opname[OP_MAX_TYPENAME];
  char propname[MAX_IDPROP_NAME];
  PointerRNA rnapoin;
} MenuItemLevel;

static void menu_item_enum_opname_menu(bContext *UNUSED(C), uiLayout *layout, void *arg)
{
  MenuItemLevel *lvl = (MenuItemLevel *)(((uiBut *)arg)->func_argN);

  uiLayoutSetOperatorContext(layout, lvl->opcontext);
  uiItemsEnumO(layout, lvl->opname, lvl->propname);

  layout->root->block->flag |= UI_BLOCK_IS_FLIP;

  /* override default, needed since this was assumed pre 2.70 */
  UI_block_direction_set(layout->root->block, UI_DIR_DOWN);
}

void uiItemMenuEnumO_ptr(uiLayout *layout,
                         bContext *C,
                         wmOperatorType *ot,
                         const char *propname,
                         const char *name,
                         int icon)
{
  MenuItemLevel *lvl;
  uiBut *but;

  /* Caller must check */
  BLI_assert(ot->srna != NULL);

  if (name == NULL) {
    name = WM_operatortype_name(ot, NULL);
  }

  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  lvl = MEM_callocN(sizeof(MenuItemLevel), "MenuItemLevel");
  BLI_strncpy(lvl->opname, ot->idname, sizeof(lvl->opname));
  BLI_strncpy(lvl->propname, propname, sizeof(lvl->propname));
  lvl->opcontext = layout->root->opcontext;

  but = ui_item_menu(layout, name, icon, menu_item_enum_opname_menu, NULL, lvl, NULL, true);

  /* add hotkey here, lower UI code can't detect it */
  if ((layout->root->block->flag & UI_BLOCK_LOOP) && (ot->prop && ot->invoke)) {
    char keybuf[128];
    if (WM_key_event_operator_string(
            C, ot->idname, layout->root->opcontext, NULL, false, keybuf, sizeof(keybuf))) {
      ui_but_add_shortcut(but, keybuf, false);
    }
  }
}

void uiItemMenuEnumO(uiLayout *layout,
                     bContext *C,
                     const char *opname,
                     const char *propname,
                     const char *name,
                     int icon)
{
  wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */

  UI_OPERATOR_ERROR_RET(ot, opname, return );

  if (!ot->srna) {
    ui_item_disabled(layout, opname);
    RNA_warning("operator missing srna '%s'", opname);
    return;
  }

  uiItemMenuEnumO_ptr(layout, C, ot, propname, name, icon);
}

static void menu_item_enum_rna_menu(bContext *UNUSED(C), uiLayout *layout, void *arg)
{
  MenuItemLevel *lvl = (MenuItemLevel *)(((uiBut *)arg)->func_argN);

  uiLayoutSetOperatorContext(layout, lvl->opcontext);
  uiItemsEnumR(layout, &lvl->rnapoin, lvl->propname);
  layout->root->block->flag |= UI_BLOCK_IS_FLIP;
}

void uiItemMenuEnumR_prop(
    uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, const char *name, int icon)
{
  MenuItemLevel *lvl;

  if (!name) {
    name = RNA_property_ui_name(prop);
  }
  if (layout->root->type == UI_LAYOUT_MENU && !icon) {
    icon = ICON_BLANK1;
  }

  lvl = MEM_callocN(sizeof(MenuItemLevel), "MenuItemLevel");
  lvl->rnapoin = *ptr;
  BLI_strncpy(lvl->propname, RNA_property_identifier(prop), sizeof(lvl->propname));
  lvl->opcontext = layout->root->opcontext;

  ui_item_menu(layout,
               name,
               icon,
               menu_item_enum_rna_menu,
               NULL,
               lvl,
               RNA_property_description(prop),
               false);
}

void uiItemMenuEnumR(
    uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *name, int icon)
{
  PropertyRNA *prop;

  prop = RNA_struct_find_property(ptr, propname);
  if (!prop) {
    ui_item_disabled(layout, propname);
    RNA_warning("property not found: %s.%s", RNA_struct_identifier(ptr->type), propname);
    return;
  }

  uiItemMenuEnumR_prop(layout, ptr, prop, name, icon);
}

void uiItemTabsEnumR_prop(uiLayout *layout,
                          bContext *C,
                          PointerRNA *ptr,
                          PropertyRNA *prop,
                          PointerRNA *ptr_highlight,
                          PropertyRNA *prop_highlight,
                          bool icon_only)
{
  uiBlock *block = layout->root->block;

  UI_block_layout_set_current(block, layout);
  ui_item_enum_expand_tabs(
      layout, C, block, ptr, prop, ptr_highlight, prop_highlight, NULL, UI_UNIT_Y, icon_only);
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Layout Items
 * \{ */

/* single-row layout */
static void ui_litem_estimate_row(uiLayout *litem)
{
  int itemw, itemh;
  bool min_size_flag = true;

  litem->w = 0;
  litem->h = 0;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);

    min_size_flag = min_size_flag && (item->flag & UI_ITEM_FIXED_SIZE);

    litem->w += itemw;
    litem->h = MAX2(itemh, litem->h);

    if (item->next) {
      litem->w += litem->space;
    }
  }

  if (min_size_flag) {
    litem->item.flag |= UI_ITEM_FIXED_SIZE;
  }
}

static int ui_litem_min_width(int itemw)
{
  return MIN2(2 * UI_UNIT_X, itemw);
}

static void ui_litem_layout_row(uiLayout *litem)
{
  uiItem *last_free_item = NULL;
  int x, y, w, tot, totw, neww, newtotw, itemw, minw, itemh, offset;
  int fixedw, freew, fixedx, freex, flag = 0, lastw = 0;
  float extra_pixel;

  /* x = litem->x; */ /* UNUSED */
  y = litem->y;
  w = litem->w;
  totw = 0;
  tot = 0;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);
    totw += itemw;
    tot++;
  }

  if (totw == 0) {
    return;
  }

  if (w != 0) {
    w -= (tot - 1) * litem->space;
  }
  fixedw = 0;

  /* keep clamping items to fixed minimum size until all are done */
  do {
    freew = 0;
    x = 0;
    flag = 0;
    newtotw = totw;
    extra_pixel = 0.0f;

    LISTBASE_FOREACH (uiItem *, item, &litem->items) {
      if (item->flag & UI_ITEM_AUTO_FIXED_SIZE) {
        continue;
      }

      ui_item_size(item, &itemw, &itemh);
      minw = ui_litem_min_width(itemw);

      if (w - lastw > 0) {
        neww = ui_item_fit(itemw, x, totw, w - lastw, !item->next, litem->alignment, &extra_pixel);
      }
      else {
        neww = 0; /* no space left, all will need clamping to minimum size */
      }

      x += neww;

      bool min_flag = item->flag & UI_ITEM_FIXED_SIZE;
      /* ignore min flag for rows with right or center alignment */
      if (item->type != ITEM_BUTTON &&
          ELEM(((uiLayout *)item)->alignment, UI_LAYOUT_ALIGN_RIGHT, UI_LAYOUT_ALIGN_CENTER) &&
          litem->alignment == UI_LAYOUT_ALIGN_EXPAND &&
          ((uiItem *)litem)->flag & UI_ITEM_FIXED_SIZE) {
        min_flag = false;
      }

      if ((neww < minw || min_flag) && w != 0) {
        /* fixed size */
        item->flag |= UI_ITEM_AUTO_FIXED_SIZE;
        if (item->type != ITEM_BUTTON && item->flag & UI_ITEM_FIXED_SIZE) {
          minw = itemw;
        }
        fixedw += minw;
        flag = 1;
        newtotw -= itemw;
      }
      else {
        /* keep free size */
        item->flag &= ~UI_ITEM_AUTO_FIXED_SIZE;
        freew += itemw;
      }
    }

    totw = newtotw;
    lastw = fixedw;
  } while (flag);

  freex = 0;
  fixedx = 0;
  extra_pixel = 0.0f;
  x = litem->x;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);
    minw = ui_litem_min_width(itemw);

    if (item->flag & UI_ITEM_AUTO_FIXED_SIZE) {
      /* fixed minimum size items */
      if (item->type != ITEM_BUTTON && item->flag & UI_ITEM_FIXED_SIZE) {
        minw = itemw;
      }
      itemw = ui_item_fit(
          minw, fixedx, fixedw, min_ii(w, fixedw), !item->next, litem->alignment, &extra_pixel);
      fixedx += itemw;
    }
    else {
      /* free size item */
      itemw = ui_item_fit(
          itemw, freex, freew, w - fixedw, !item->next, litem->alignment, &extra_pixel);
      freex += itemw;
      last_free_item = item;
    }

    /* align right/center */
    offset = 0;
    if (litem->alignment == UI_LAYOUT_ALIGN_RIGHT) {
      if (freew + fixedw > 0 && freew + fixedw < w) {
        offset = w - (fixedw + freew);
      }
    }
    else if (litem->alignment == UI_LAYOUT_ALIGN_CENTER) {
      if (freew + fixedw > 0 && freew + fixedw < w) {
        offset = (w - (fixedw + freew)) / 2;
      }
    }

    /* position item */
    ui_item_position(item, x + offset, y - itemh, itemw, itemh);

    x += itemw;
    if (item->next) {
      x += litem->space;
    }
  }

  /* add extra pixel */
  uiItem *last_item = litem->items.last;
  extra_pixel = litem->w - (x - litem->x);
  if (extra_pixel > 0 && litem->alignment == UI_LAYOUT_ALIGN_EXPAND && last_free_item &&
      last_item && last_item->flag & UI_ITEM_AUTO_FIXED_SIZE) {
    ui_item_move(last_free_item, 0, extra_pixel);
    for (uiItem *item = last_free_item->next; item; item = item->next) {
      ui_item_move(item, extra_pixel, extra_pixel);
    }
  }

  litem->w = x - litem->x;
  litem->h = litem->y - y;
  litem->x = x;
  litem->y = y;
}

/* single-column layout */
static void ui_litem_estimate_column(uiLayout *litem, bool is_box)
{
  int itemw, itemh;
  bool min_size_flag = true;

  litem->w = 0;
  litem->h = 0;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);

    min_size_flag = min_size_flag && (item->flag & UI_ITEM_FIXED_SIZE);

    litem->w = MAX2(litem->w, itemw);
    litem->h += itemh;

    if (item->next && (!is_box || item != litem->items.first)) {
      litem->h += litem->space;
    }
  }

  if (min_size_flag) {
    litem->item.flag |= UI_ITEM_FIXED_SIZE;
  }
}

static void ui_litem_layout_column(uiLayout *litem, bool is_box)
{
  int itemh, x, y;

  x = litem->x;
  y = litem->y;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, NULL, &itemh);

    y -= itemh;
    ui_item_position(item, x, y, litem->w, itemh);

    if (item->next && (!is_box || item != litem->items.first)) {
      y -= litem->space;
    }

    if (is_box) {
      item->flag |= UI_ITEM_BOX_ITEM;
    }
  }

  litem->h = litem->y - y;
  litem->x = x;
  litem->y = y;
}

/* calculates the angle of a specified button in a radial menu,
 * stores a float vector in unit circle */
static RadialDirection ui_get_radialbut_vec(float vec[2], short itemnum)
{
  RadialDirection dir;

  if (itemnum >= PIE_MAX_ITEMS) {
    itemnum %= PIE_MAX_ITEMS;
    printf("Warning: Pie menus with more than %i items are currently unsupported\n",
           PIE_MAX_ITEMS);
  }

  dir = ui_radial_dir_order[itemnum];
  ui_but_pie_dir(dir, vec);

  return dir;
}

static bool ui_item_is_radial_displayable(uiItem *item)
{

  if ((item->type == ITEM_BUTTON) && (((uiButtonItem *)item)->but->type == UI_BTYPE_LABEL)) {
    return false;
  }

  return true;
}

static bool ui_item_is_radial_drawable(uiButtonItem *bitem)
{

  if (ELEM(bitem->but->type, UI_BTYPE_SEPR, UI_BTYPE_SEPR_LINE, UI_BTYPE_SEPR_SPACER)) {
    return false;
  }

  return true;
}

static void ui_litem_layout_radial(uiLayout *litem)
{
  int itemh, itemw, x, y;
  int itemnum = 0;
  int totitems = 0;

  /* For the radial layout we will use Matt Ebb's design
   * for radiation, see http://mattebb.com/weblog/radiation/
   * also the old code at http://developer.blender.org/T5103
   */

  const int pie_radius = U.pie_menu_radius * UI_DPI_FAC;

  x = litem->x;
  y = litem->y;

  int minx = x, miny = y, maxx = x, maxy = y;

  /* first count total items */
  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    totitems++;
  }

  if (totitems < 5) {
    litem->root->block->pie_data.flags |= UI_PIE_DEGREES_RANGE_LARGE;
  }

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    /* not all button types are drawn in a radial menu, do filtering here */
    if (ui_item_is_radial_displayable(item)) {
      RadialDirection dir;
      float vec[2];
      float factor[2];

      dir = ui_get_radialbut_vec(vec, itemnum);
      factor[0] = (vec[0] > 0.01f) ? 0.0f : ((vec[0] < -0.01f) ? -1.0f : -0.5f);
      factor[1] = (vec[1] > 0.99f) ? 0.0f : ((vec[1] < -0.99f) ? -1.0f : -0.5f);

      itemnum++;

      if (item->type == ITEM_BUTTON) {
        uiButtonItem *bitem = (uiButtonItem *)item;

        bitem->but->pie_dir = dir;
        /* scale the buttons */
        bitem->but->rect.ymax *= 1.5f;
        /* add a little bit more here to include number */
        bitem->but->rect.xmax += 1.5f * UI_UNIT_X;
        /* enable drawing as pie item if supported by widget */
        if (ui_item_is_radial_drawable(bitem)) {
          bitem->but->emboss = UI_EMBOSS_RADIAL;
          bitem->but->drawflag |= UI_BUT_ICON_LEFT;
        }
      }

      ui_item_size(item, &itemw, &itemh);

      ui_item_position(item,
                       x + vec[0] * pie_radius + factor[0] * itemw,
                       y + vec[1] * pie_radius + factor[1] * itemh,
                       itemw,
                       itemh);

      minx = min_ii(minx, x + vec[0] * pie_radius - itemw / 2);
      maxx = max_ii(maxx, x + vec[0] * pie_radius + itemw / 2);
      miny = min_ii(miny, y + vec[1] * pie_radius - itemh / 2);
      maxy = max_ii(maxy, y + vec[1] * pie_radius + itemh / 2);
    }
  }

  litem->x = minx;
  litem->y = miny;
  litem->w = maxx - minx;
  litem->h = maxy - miny;
}

/* root layout */
static void ui_litem_estimate_root(uiLayout *UNUSED(litem))
{
  /* nothing to do */
}

static void ui_litem_layout_root_radial(uiLayout *litem)
{
  /* first item is pie menu title, align on center of menu */
  uiItem *item = litem->items.first;

  if (item->type == ITEM_BUTTON) {
    int itemh, itemw, x, y;
    x = litem->x;
    y = litem->y;

    ui_item_size(item, &itemw, &itemh);

    ui_item_position(
        item, x - itemw / 2, y + U.dpi_fac * (U.pie_menu_threshold + 9.0f), itemw, itemh);
  }
}

static void ui_litem_layout_root(uiLayout *litem)
{
  if (litem->root->type == UI_LAYOUT_HEADER) {
    ui_litem_layout_row(litem);
  }
  else if (litem->root->type == UI_LAYOUT_PIEMENU) {
    ui_litem_layout_root_radial(litem);
  }
  else {
    ui_litem_layout_column(litem, false);
  }
}

/* box layout */
static void ui_litem_estimate_box(uiLayout *litem)
{
  const uiStyle *style = litem->root->style;

  ui_litem_estimate_column(litem, true);

  int boxspace = style->boxspace;
  if (litem->root->type == UI_LAYOUT_HEADER) {
    boxspace = 0;
  }
  litem->w += 2 * boxspace;
  litem->h += 2 * boxspace;
}

static void ui_litem_layout_box(uiLayout *litem)
{
  uiLayoutItemBx *box = (uiLayoutItemBx *)litem;
  const uiStyle *style = litem->root->style;
  uiBut *but;
  int w, h;

  int boxspace = style->boxspace;
  if (litem->root->type == UI_LAYOUT_HEADER) {
    boxspace = 0;
  }

  w = litem->w;
  h = litem->h;

  litem->x += boxspace;
  litem->y -= boxspace;

  if (w != 0) {
    litem->w -= 2 * boxspace;
  }
  if (h != 0) {
    litem->h -= 2 * boxspace;
  }

  ui_litem_layout_column(litem, true);

  litem->x -= boxspace;
  litem->y -= boxspace;

  if (w != 0) {
    litem->w += 2 * boxspace;
  }
  if (h != 0) {
    litem->h += 2 * boxspace;
  }

  /* roundbox around the sublayout */
  but = box->roundbox;
  but->rect.xmin = litem->x;
  but->rect.ymin = litem->y;
  but->rect.xmax = litem->x + litem->w;
  but->rect.ymax = litem->y + litem->h;
}

/* multi-column layout, automatically flowing to the next */
static void ui_litem_estimate_column_flow(uiLayout *litem)
{
  const uiStyle *style = litem->root->style;
  uiLayoutItemFlow *flow = (uiLayoutItemFlow *)litem;
  int col, x, y, emh, emy, miny, itemw, itemh, maxw = 0;
  int toth, totitem;

  /* compute max needed width and total height */
  toth = 0;
  totitem = 0;
  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);
    maxw = MAX2(maxw, itemw);
    toth += itemh;
    totitem++;
  }

  if (flow->number <= 0) {
    /* auto compute number of columns, not very good */
    if (maxw == 0) {
      flow->totcol = 1;
      return;
    }

    flow->totcol = max_ii(litem->root->emw / maxw, 1);
    flow->totcol = min_ii(flow->totcol, totitem);
  }
  else {
    flow->totcol = flow->number;
  }

  /* compute sizes */
  x = 0;
  y = 0;
  emy = 0;
  miny = 0;

  maxw = 0;
  emh = toth / flow->totcol;

  /* create column per column */
  col = 0;
  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);

    y -= itemh + style->buttonspacey;
    miny = min_ii(miny, y);
    emy -= itemh;
    maxw = max_ii(itemw, maxw);

    /* decide to go to next one */
    if (col < flow->totcol - 1 && emy <= -emh) {
      x += maxw + litem->space;
      maxw = 0;
      y = 0;
      emy = 0; /* need to reset height again for next column */
      col++;
    }
  }

  litem->w = x;
  litem->h = litem->y - miny;
}

static void ui_litem_layout_column_flow(uiLayout *litem)
{
  const uiStyle *style = litem->root->style;
  uiLayoutItemFlow *flow = (uiLayoutItemFlow *)litem;
  int col, x, y, w, emh, emy, miny, itemw, itemh;
  int toth, totitem;

  /* compute max needed width and total height */
  toth = 0;
  totitem = 0;
  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);
    toth += itemh;
    totitem++;
  }

  /* compute sizes */
  x = litem->x;
  y = litem->y;
  emy = 0;
  miny = 0;

  w = litem->w - (flow->totcol - 1) * style->columnspace;
  emh = toth / flow->totcol;

  /* create column per column */
  col = 0;
  w = (litem->w - (flow->totcol - 1) * style->columnspace) / flow->totcol;
  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);

    itemw = (litem->alignment == UI_LAYOUT_ALIGN_EXPAND) ? w : min_ii(w, itemw);

    y -= itemh;
    emy -= itemh;
    ui_item_position(item, x, y, itemw, itemh);
    y -= style->buttonspacey;
    miny = min_ii(miny, y);

    /* decide to go to next one */
    if (col < flow->totcol - 1 && emy <= -emh) {
      x += w + style->columnspace;
      y = litem->y;
      emy = 0; /* need to reset height again for next column */
      col++;

      const int remaining_width = litem->w - (x - litem->x);
      const int remaining_width_between_columns = (flow->totcol - col - 1) * style->columnspace;
      const int remaining_columns = flow->totcol - col;
      w = (remaining_width - remaining_width_between_columns) / remaining_columns;
    }
  }

  litem->h = litem->y - miny;
  litem->x = x;
  litem->y = miny;
}

/* multi-column and multi-row layout. */
typedef struct UILayoutGridFlowInput {
  /* General layout control settings. */
  const bool row_major : 1;    /* Fill rows before columns */
  const bool even_columns : 1; /* All columns will have same width. */
  const bool even_rows : 1;    /* All rows will have same height. */
  const int space_x;           /* Space between columns. */
  const int space_y;           /* Space between rows. */
  /* Real data about current position and size of this layout item
   * (either estimated, or final values). */
  const int litem_w; /* Layout item width. */
  const int litem_x; /* Layout item X position. */
  const int litem_y; /* Layout item Y position. */
  /* Actual number of columns and rows to generate (computed from first pass usually). */
  const int tot_columns; /* Number of columns. */
  const int tot_rows;    /* Number of rows. */
} UILayoutGridFlowInput;

typedef struct UILayoutGridFlowOutput {
  int *tot_items; /* Total number of items in this grid layout. */
  /* Width / X pos data. */
  float *global_avg_w; /* Computed average width of the columns. */
  int *cos_x_array;    /* Computed X coordinate of each column. */
  int *widths_array;   /* Computed width of each column. */
  int *tot_w;          /* Computed total width. */
  /* Height / Y pos data. */
  int *global_max_h;  /* Computed height of the tallest item in the grid. */
  int *cos_y_array;   /* Computed Y coordinate of each column. */
  int *heights_array; /* Computed height of each column. */
  int *tot_h;         /* Computed total height. */
} UILayoutGridFlowOutput;

static void ui_litem_grid_flow_compute(ListBase *items,
                                       UILayoutGridFlowInput *parameters,
                                       UILayoutGridFlowOutput *results)
{
  float tot_w = 0.0f, tot_h = 0.0f;
  float global_avg_w = 0.0f, global_totweight_w = 0.0f;
  int global_max_h = 0;

  float *avg_w = NULL, *totweight_w = NULL;
  int *max_h = NULL;

  BLI_assert(
      parameters->tot_columns != 0 ||
      (results->cos_x_array == NULL && results->widths_array == NULL && results->tot_w == NULL));
  BLI_assert(
      parameters->tot_rows != 0 ||
      (results->cos_y_array == NULL && results->heights_array == NULL && results->tot_h == NULL));

  if (results->tot_items) {
    *results->tot_items = 0;
  }

  if (items->first == NULL) {
    if (results->global_avg_w) {
      *results->global_avg_w = 0.0f;
    }
    if (results->global_max_h) {
      *results->global_max_h = 0;
    }
    return;
  }

  if (parameters->tot_columns != 0) {
    avg_w = BLI_array_alloca(avg_w, parameters->tot_columns);
    totweight_w = BLI_array_alloca(totweight_w, parameters->tot_columns);
    memset(avg_w, 0, sizeof(*avg_w) * parameters->tot_columns);
    memset(totweight_w, 0, sizeof(*totweight_w) * parameters->tot_columns);
  }
  if (parameters->tot_rows != 0) {
    max_h = BLI_array_alloca(max_h, parameters->tot_rows);
    memset(max_h, 0, sizeof(*max_h) * parameters->tot_rows);
  }

  int i = 0;
  LISTBASE_FOREACH (uiItem *, item, items) {
    int item_w, item_h;
    ui_item_size(item, &item_w, &item_h);

    global_avg_w += (float)(item_w * item_w);
    global_totweight_w += (float)item_w;
    global_max_h = max_ii(global_max_h, item_h);

    if (parameters->tot_rows != 0 && parameters->tot_columns != 0) {
      const int index_col = parameters->row_major ? i % parameters->tot_columns :
                                                    i / parameters->tot_rows;
      const int index_row = parameters->row_major ? i / parameters->tot_columns :
                                                    i % parameters->tot_rows;

      avg_w[index_col] += (float)(item_w * item_w);
      totweight_w[index_col] += (float)item_w;

      max_h[index_row] = max_ii(max_h[index_row], item_h);
    }

    if (results->tot_items) {
      (*results->tot_items)++;
    }
    i++;
  }

  /* Finalize computing of column average sizes */
  global_avg_w /= global_totweight_w;
  if (parameters->tot_columns != 0) {
    for (i = 0; i < parameters->tot_columns; i++) {
      avg_w[i] /= totweight_w[i];
      tot_w += avg_w[i];
    }
    if (parameters->even_columns) {
      tot_w = ceilf(global_avg_w) * parameters->tot_columns;
    }
  }
  /* Finalize computing of rows max sizes */
  if (parameters->tot_rows != 0) {
    for (i = 0; i < parameters->tot_rows; i++) {
      tot_h += max_h[i];
    }
    if (parameters->even_rows) {
      tot_h = global_max_h * parameters->tot_columns;
    }
  }

  /* Compute positions and sizes of all cells. */
  if (results->cos_x_array != NULL && results->widths_array != NULL) {
    /* We enlarge/narrow columns evenly to match available width. */
    const float wfac = (float)(parameters->litem_w -
                               (parameters->tot_columns - 1) * parameters->space_x) /
                       tot_w;

    for (int col = 0; col < parameters->tot_columns; col++) {
      results->cos_x_array[col] = (col ? results->cos_x_array[col - 1] +
                                             results->widths_array[col - 1] + parameters->space_x :
                                         parameters->litem_x);
      if (parameters->even_columns) {
        /* (< remaining width > - < space between remaining columns >) / < remaining columns > */
        results->widths_array[col] = (((parameters->litem_w -
                                        (results->cos_x_array[col] - parameters->litem_x)) -
                                       (parameters->tot_columns - col - 1) * parameters->space_x) /
                                      (parameters->tot_columns - col));
      }
      else if (col == parameters->tot_columns - 1) {
        /* Last column copes width rounding errors... */
        results->widths_array[col] = parameters->litem_w -
                                     (results->cos_x_array[col] - parameters->litem_x);
      }
      else {
        results->widths_array[col] = (int)(avg_w[col] * wfac);
      }
    }
  }
  if (results->cos_y_array != NULL && results->heights_array != NULL) {
    for (int row = 0; row < parameters->tot_rows; row++) {
      if (parameters->even_rows) {
        results->heights_array[row] = global_max_h;
      }
      else {
        results->heights_array[row] = max_h[row];
      }
      results->cos_y_array[row] = (row ? results->cos_y_array[row - 1] - parameters->space_y -
                                             results->heights_array[row] :
                                         parameters->litem_y - results->heights_array[row]);
    }
  }

  if (results->global_avg_w) {
    *results->global_avg_w = global_avg_w;
  }
  if (results->global_max_h) {
    *results->global_max_h = global_max_h;
  }
  if (results->tot_w) {
    *results->tot_w = (int)tot_w + parameters->space_x * (parameters->tot_columns - 1);
  }
  if (results->tot_h) {
    *results->tot_h = tot_h + parameters->space_y * (parameters->tot_rows - 1);
  }
}

static void ui_litem_estimate_grid_flow(uiLayout *litem)
{
  const uiStyle *style = litem->root->style;
  uiLayoutItemGridFlow *gflow = (uiLayoutItemGridFlow *)litem;

  const int space_x = style->columnspace;
  const int space_y = style->buttonspacey;

  /* Estimate average needed width and height per item. */
  {
    float avg_w;
    int max_h;

    ui_litem_grid_flow_compute(&litem->items,
                               &((UILayoutGridFlowInput){
                                   .row_major = gflow->row_major,
                                   .even_columns = gflow->even_columns,
                                   .even_rows = gflow->even_rows,
                                   .litem_w = litem->w,
                                   .litem_x = litem->x,
                                   .litem_y = litem->y,
                                   .space_x = space_x,
                                   .space_y = space_y,
                               }),
                               &((UILayoutGridFlowOutput){
                                   .tot_items = &gflow->tot_items,
                                   .global_avg_w = &avg_w,
                                   .global_max_h = &max_h,
                               }));

    if (gflow->tot_items == 0) {
      litem->w = litem->h = 0;
      gflow->tot_columns = gflow->tot_rows = 0;
      return;
    }

    /* Even in varying column width case,
     * we fix our columns number from weighted average width of items,
     * a proper solving of required width would be too costly,
     * and this should give reasonably good results in all reasonable cases. */
    if (gflow->columns_len > 0) {
      gflow->tot_columns = gflow->columns_len;
    }
    else {
      if (avg_w == 0.0f) {
        gflow->tot_columns = 1;
      }
      else {
        gflow->tot_columns = min_ii(max_ii((int)(litem->w / avg_w), 1), gflow->tot_items);
      }
    }
    gflow->tot_rows = (int)ceilf((float)gflow->tot_items / gflow->tot_columns);

    /* Try to tweak number of columns and rows to get better filling of last column or row,
     * and apply 'modulo' value to number of columns or rows.
     * Note that modulo does not prevent ending with fewer columns/rows than modulo, if mandatory
     * to avoid empty column/row. */
    {
      const int modulo = (gflow->columns_len < -1) ? -gflow->columns_len : 0;
      const int step = modulo ? modulo : 1;

      if (gflow->row_major) {
        /* Adjust number of columns to be multiple of given modulo. */
        if (modulo && gflow->tot_columns % modulo != 0 && gflow->tot_columns > modulo) {
          gflow->tot_columns = gflow->tot_columns - (gflow->tot_columns % modulo);
        }
        /* Find smallest number of columns conserving computed optimal number of rows. */
        for (gflow->tot_rows = (int)ceilf((float)gflow->tot_items / gflow->tot_columns);
             (gflow->tot_columns - step) > 0 &&
             (int)ceilf((float)gflow->tot_items / (gflow->tot_columns - step)) <= gflow->tot_rows;
             gflow->tot_columns -= step) {
          /* pass */
        }
      }
      else {
        /* Adjust number of rows to be multiple of given modulo. */
        if (modulo && gflow->tot_rows % modulo != 0) {
          gflow->tot_rows = min_ii(gflow->tot_rows + modulo - (gflow->tot_rows % modulo),
                                   gflow->tot_items);
        }
        /* Find smallest number of rows conserving computed optimal number of columns. */
        for (gflow->tot_columns = (int)ceilf((float)gflow->tot_items / gflow->tot_rows);
             (gflow->tot_rows - step) > 0 &&
             (int)ceilf((float)gflow->tot_items / (gflow->tot_rows - step)) <= gflow->tot_columns;
             gflow->tot_rows -= step) {
          /* pass */
        }
      }
    }

    /* Set evenly-spaced axes size
     * (quick optimization in case we have even columns and rows). */
    if (gflow->even_columns && gflow->even_rows) {
      litem->w = (int)(gflow->tot_columns * avg_w) + space_x * (gflow->tot_columns - 1);
      litem->h = (int)(gflow->tot_rows * max_h) + space_y * (gflow->tot_rows - 1);
      return;
    }
  }

  /* Now that we have our final number of columns and rows,
   * we can compute actual needed space for non-evenly sized axes. */
  {
    int tot_w, tot_h;

    ui_litem_grid_flow_compute(&litem->items,
                               &((UILayoutGridFlowInput){
                                   .row_major = gflow->row_major,
                                   .even_columns = gflow->even_columns,
                                   .even_rows = gflow->even_rows,
                                   .litem_w = litem->w,
                                   .litem_x = litem->x,
                                   .litem_y = litem->y,
                                   .space_x = space_x,
                                   .space_y = space_y,
                                   .tot_columns = gflow->tot_columns,
                                   .tot_rows = gflow->tot_rows,
                               }),
                               &((UILayoutGridFlowOutput){
                                   .tot_w = &tot_w,
                                   .tot_h = &tot_h,
                               }));

    litem->w = tot_w;
    litem->h = tot_h;
  }
}

static void ui_litem_layout_grid_flow(uiLayout *litem)
{
  const uiStyle *style = litem->root->style;
  uiLayoutItemGridFlow *gflow = (uiLayoutItemGridFlow *)litem;

  if (gflow->tot_items == 0) {
    litem->w = litem->h = 0;
    return;
  }

  BLI_assert(gflow->tot_columns > 0);
  BLI_assert(gflow->tot_rows > 0);

  const int space_x = style->columnspace;
  const int space_y = style->buttonspacey;

  int *widths = BLI_array_alloca(widths, gflow->tot_columns);
  int *heights = BLI_array_alloca(heights, gflow->tot_rows);
  int *cos_x = BLI_array_alloca(cos_x, gflow->tot_columns);
  int *cos_y = BLI_array_alloca(cos_y, gflow->tot_rows);

  /* This time we directly compute coordinates and sizes of all cells. */
  ui_litem_grid_flow_compute(&litem->items,
                             &((UILayoutGridFlowInput){
                                 .row_major = gflow->row_major,
                                 .even_columns = gflow->even_columns,
                                 .even_rows = gflow->even_rows,
                                 .litem_w = litem->w,
                                 .litem_x = litem->x,
                                 .litem_y = litem->y,
                                 .space_x = space_x,
                                 .space_y = space_y,
                                 .tot_columns = gflow->tot_columns,
                                 .tot_rows = gflow->tot_rows,
                             }),
                             &((UILayoutGridFlowOutput){
                                 .cos_x_array = cos_x,
                                 .cos_y_array = cos_y,
                                 .widths_array = widths,
                                 .heights_array = heights,
                             }));

  int i;
  LISTBASE_FOREACH_INDEX (uiItem *, item, &litem->items, i) {
    const int col = gflow->row_major ? i % gflow->tot_columns : i / gflow->tot_rows;
    const int row = gflow->row_major ? i / gflow->tot_columns : i % gflow->tot_rows;
    int item_w, item_h;
    ui_item_size(item, &item_w, &item_h);

    const int w = widths[col];
    const int h = heights[row];

    item_w = (litem->alignment == UI_LAYOUT_ALIGN_EXPAND) ? w : min_ii(w, item_w);
    item_h = (litem->alignment == UI_LAYOUT_ALIGN_EXPAND) ? h : min_ii(h, item_h);

    ui_item_position(item, cos_x[col], cos_y[row], item_w, item_h);
  }

  litem->h = litem->y - cos_y[gflow->tot_rows - 1];
  litem->x = (cos_x[gflow->tot_columns - 1] - litem->x) + widths[gflow->tot_columns - 1];
  litem->y = litem->y - litem->h;
}

/* free layout */
static void ui_litem_estimate_absolute(uiLayout *litem)
{
  int itemx, itemy, itemw, itemh, minx, miny;

  minx = 1e6;
  miny = 1e6;
  litem->w = 0;
  litem->h = 0;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_offset(item, &itemx, &itemy);
    ui_item_size(item, &itemw, &itemh);

    minx = min_ii(minx, itemx);
    miny = min_ii(miny, itemy);

    litem->w = MAX2(litem->w, itemx + itemw);
    litem->h = MAX2(litem->h, itemy + itemh);
  }

  litem->w -= minx;
  litem->h -= miny;
}

static void ui_litem_layout_absolute(uiLayout *litem)
{
  float scalex = 1.0f, scaley = 1.0f;
  int x, y, newx, newy, itemx, itemy, itemh, itemw, minx, miny, totw, toth;

  minx = 1e6;
  miny = 1e6;
  totw = 0;
  toth = 0;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_offset(item, &itemx, &itemy);
    ui_item_size(item, &itemw, &itemh);

    minx = min_ii(minx, itemx);
    miny = min_ii(miny, itemy);

    totw = max_ii(totw, itemx + itemw);
    toth = max_ii(toth, itemy + itemh);
  }

  totw -= minx;
  toth -= miny;

  if (litem->w && totw > 0) {
    scalex = (float)litem->w / (float)totw;
  }
  if (litem->h && toth > 0) {
    scaley = (float)litem->h / (float)toth;
  }

  x = litem->x;
  y = litem->y - scaley * toth;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_offset(item, &itemx, &itemy);
    ui_item_size(item, &itemw, &itemh);

    if (scalex != 1.0f) {
      newx = (itemx - minx) * scalex;
      itemw = (itemx - minx + itemw) * scalex - newx;
      itemx = minx + newx;
    }

    if (scaley != 1.0f) {
      newy = (itemy - miny) * scaley;
      itemh = (itemy - miny + itemh) * scaley - newy;
      itemy = miny + newy;
    }

    ui_item_position(item, x + itemx - minx, y + itemy - miny, itemw, itemh);
  }

  litem->w = scalex * totw;
  litem->h = litem->y - y;
  litem->x = x + litem->w;
  litem->y = y;
}

/* split layout */
static void ui_litem_estimate_split(uiLayout *litem)
{
  ui_litem_estimate_row(litem);
  litem->item.flag &= ~UI_ITEM_FIXED_SIZE;
}

static void ui_litem_layout_split(uiLayout *litem)
{
  uiLayoutItemSplit *split = (uiLayoutItemSplit *)litem;
  float percentage, extra_pixel = 0.0f;
  const int tot = BLI_listbase_count(&litem->items);
  int itemh, x, y, w, colw = 0;

  if (tot == 0) {
    return;
  }

  x = litem->x;
  y = litem->y;

  percentage = (split->percentage == 0.0f) ? 1.0f / (float)tot : split->percentage;

  w = (litem->w - (tot - 1) * litem->space);
  colw = w * percentage;
  colw = MAX2(colw, 0);

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, NULL, &itemh);

    ui_item_position(item, x, y - itemh, colw, itemh);
    x += colw;

    if (item->next) {
      const float width = extra_pixel + (w - (int)(w * percentage)) / ((float)tot - 1);
      extra_pixel = width - (int)width;
      colw = (int)width;
      colw = MAX2(colw, 0);

      x += litem->space;
    }
  }

  litem->w = x - litem->x;
  litem->h = litem->y - y;
  litem->x = x;
  litem->y = y;
}

/* overlap layout */
static void ui_litem_estimate_overlap(uiLayout *litem)
{
  int itemw, itemh;

  litem->w = 0;
  litem->h = 0;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);

    litem->w = MAX2(itemw, litem->w);
    litem->h = MAX2(itemh, litem->h);
  }
}

static void ui_litem_layout_overlap(uiLayout *litem)
{
  int itemw, itemh, x, y;

  x = litem->x;
  y = litem->y;

  LISTBASE_FOREACH (uiItem *, item, &litem->items) {
    ui_item_size(item, &itemw, &itemh);
    ui_item_position(item, x, y - itemh, litem->w, itemh);

    litem->h = MAX2(litem->h, itemh);
  }

  litem->x = x;
  litem->y = y - litem->h;
}

static void ui_litem_init_from_parent(uiLayout *litem, uiLayout *layout, int align)
{
  litem->root = layout->root;
  litem->align = align;
  /* Children of gridflow layout shall never have "ideal big size" returned as estimated size. */
  litem->variable_size = layout->variable_size || layout->item.type == ITEM_LAYOUT_GRID_FLOW;
  litem->active = true;
  litem->enabled = true;
  litem->context = layout->context;
  litem->redalert = layout->redalert;
  litem->w = layout->w;
  litem->emboss = layout->emboss;
  litem->item.flag = (layout->item.flag &
                      (UI_ITEM_PROP_SEP | UI_ITEM_PROP_DECORATE | UI_ITEM_INSIDE_PROP_SEP));

  if (layout->child_items_layout) {
    BLI_addtail(&layout->child_items_layout->items, litem);
    litem->parent = layout->child_items_layout;
  }
  else {
    BLI_addtail(&layout->items, litem);
    litem->parent = layout;
  }
}

static void ui_layout_heading_set(uiLayout *layout, const char *heading)
{
  BLI_assert(layout->heading[0] == '\0');
  if (heading) {
    STRNCPY(layout->heading, heading);
  }
}

/* layout create functions */
uiLayout *uiLayoutRow(uiLayout *layout, bool align)
{
  uiLayout *litem;

  litem = MEM_callocN(sizeof(uiLayout), "uiLayoutRow");
  ui_litem_init_from_parent(litem, layout, align);

  litem->item.type = ITEM_LAYOUT_ROW;
  litem->space = (align) ? 0 : layout->root->style->buttonspacex;

  UI_block_layout_set_current(layout->root->block, litem);

  return litem;
}

/**
 * See #uiLayoutColumnWithHeading().
 */
uiLayout *uiLayoutRowWithHeading(uiLayout *layout, bool align, const char *heading)
{
  uiLayout *litem = uiLayoutRow(layout, align);
  ui_layout_heading_set(litem, heading);
  return litem;
}

uiLayout *uiLayoutColumn(uiLayout *layout, bool align)
{
  uiLayout *litem;

  litem = MEM_callocN(sizeof(uiLayout), "uiLayoutColumn");
  ui_litem_init_from_parent(litem, layout, align);

  litem->item.type = ITEM_LAYOUT_COLUMN;
  litem->space = (align) ? 0 : layout->root->style->buttonspacey;

  UI_block_layout_set_current(layout->root->block, litem);

  return litem;
}

/**
 * Variant of #uiLayoutColumn() that sets a heading label for the layout if the first item is
 * added through #uiItemFullR(). If split layout is used and the item has no string to add to the
 * first split-column, the heading is added there instead. Otherwise the heading inserted with a
 * new row.
 */
uiLayout *uiLayoutColumnWithHeading(uiLayout *layout, bool align, const char *heading)
{
  uiLayout *litem = uiLayoutColumn(layout, align);
  ui_layout_heading_set(litem, heading);
  return litem;
}

uiLayout *uiLayoutColumnFlow(uiLayout *layout, int number, bool align)
{
  uiLayoutItemFlow *flow;

  flow = MEM_callocN(sizeof(uiLayoutItemFlow), "uiLayoutItemFlow");
  ui_litem_init_from_parent(&flow->litem, layout, align);

  flow->litem.item.type = ITEM_LAYOUT_COLUMN_FLOW;
  flow->litem.space = (flow->litem.align) ? 0 : layout->root->style->columnspace;
  flow->number = number;

  UI_block_layout_set_current(layout->root->block, &flow->litem);

  return &flow->litem;
}

uiLayout *uiLayoutGridFlow(uiLayout *layout,
                           bool row_major,
                           int columns_len,
                           bool even_columns,
                           bool even_rows,
                           bool align)
{
  uiLayoutItemGridFlow *flow;

  flow = MEM_callocN(sizeof(uiLayoutItemGridFlow), __func__);
  flow->litem.item.type = ITEM_LAYOUT_GRID_FLOW;
  ui_litem_init_from_parent(&flow->litem, layout, align);

  flow->litem.space = (flow->litem.align) ? 0 : layout->root->style->columnspace;
  flow->row_major = row_major;
  flow->columns_len = columns_len;
  flow->even_columns = even_columns;
  flow->even_rows = even_rows;

  UI_block_layout_set_current(layout->root->block, &flow->litem);

  return &flow->litem;
}

static uiLayoutItemBx *ui_layout_box(uiLayout *layout, int type)
{
  uiLayoutItemBx *box;

  box = MEM_callocN(sizeof(uiLayoutItemBx), "uiLayoutItemBx");
  ui_litem_init_from_parent(&box->litem, layout, false);

  box->litem.item.type = ITEM_LAYOUT_BOX;
  box->litem.space = layout->root->style->columnspace;

  UI_block_layout_set_current(layout->root->block, &box->litem);

  box->roundbox = uiDefBut(layout->root->block, type, 0, "", 0, 0, 0, 0, NULL, 0.0, 0.0, 0, 0, "");

  return box;
}

uiLayout *uiLayoutRadial(uiLayout *layout)
{
  uiLayout *litem;

  /* radial layouts are only valid for radial menus */
  if (layout->root->type != UI_LAYOUT_PIEMENU) {
    return ui_item_local_sublayout(layout, layout, 0);
  }

  /* only one radial wheel per root layout is allowed, so check and return that, if it exists */
  LISTBASE_FOREACH (uiItem *, item, &layout->root->layout->items) {
    litem = (uiLayout *)item;
    if (litem->item.type == ITEM_LAYOUT_RADIAL) {
      UI_block_layout_set_current(layout->root->block, litem);
      return litem;
    }
  }

  litem = MEM_callocN(sizeof(uiLayout), "uiLayoutRadial");
  ui_litem_init_from_parent(litem, layout, false);

  litem->item.type = ITEM_LAYOUT_RADIAL;

  UI_block_layout_set_current(layout->root->block, litem);

  return litem;
}

uiLayout *uiLayoutBox(uiLayout *layout)
{
  return (uiLayout *)ui_layout_box(layout, UI_BTYPE_ROUNDBOX);
}

/**
 * Check all buttons defined in this layout,
 * and set any button flagged as UI_BUT_LIST_ITEM as active/selected.
 * Needed to handle correctly text colors of active (selected) list item.
 */
void ui_layout_list_set_labels_active(uiLayout *layout)
{
  LISTBASE_FOREACH (uiButtonItem *, bitem, &layout->items) {
    if (bitem->item.type != ITEM_BUTTON) {
      ui_layout_list_set_labels_active((uiLayout *)(&bitem->item));
    }
    else if (bitem->but->flag & UI_BUT_LIST_ITEM) {
      UI_but_flag_enable(bitem->but, UI_SELECT);
    }
  }
}

uiLayout *uiLayoutListBox(uiLayout *layout,
                          uiList *ui_list,
                          PointerRNA *actptr,
                          PropertyRNA *actprop)
{
  uiLayoutItemBx *box = ui_layout_box(layout, UI_BTYPE_LISTBOX);
  uiBut *but = box->roundbox;

  but->custom_data = ui_list;

  but->rnapoin = *actptr;
  but->rnaprop = actprop;

  /* only for the undo string */
  if (but->flag & UI_BUT_UNDO) {
    but->tip = RNA_property_description(actprop);
  }

  return (uiLayout *)box;
}

uiLayout *uiLayoutAbsolute(uiLayout *layout, bool align)
{
  uiLayout *litem;

  litem = MEM_callocN(sizeof(uiLayout), "uiLayoutAbsolute");
  ui_litem_init_from_parent(litem, layout, align);

  litem->item.type = ITEM_LAYOUT_ABSOLUTE;

  UI_block_layout_set_current(layout->root->block, litem);

  return litem;
}

uiBlock *uiLayoutAbsoluteBlock(uiLayout *layout)
{
  uiBlock *block;

  block = uiLayoutGetBlock(layout);
  uiLayoutAbsolute(layout, false);

  return block;
}

uiLayout *uiLayoutOverlap(uiLayout *layout)
{
  uiLayout *litem;

  litem = MEM_callocN(sizeof(uiLayout), "uiLayoutOverlap");
  ui_litem_init_from_parent(litem, layout, false);

  litem->item.type = ITEM_LAYOUT_OVERLAP;

  UI_block_layout_set_current(layout->root->block, litem);

  return litem;
}

uiLayout *uiLayoutSplit(uiLayout *layout, float percentage, bool align)
{
  uiLayoutItemSplit *split;

  split = MEM_callocN(sizeof(uiLayoutItemSplit), "uiLayoutItemSplit");
  ui_litem_init_from_parent(&split->litem, layout, align);

  split->litem.item.type = ITEM_LAYOUT_SPLIT;
  split->litem.space = layout->root->style->columnspace;
  split->percentage = percentage;

  UI_block_layout_set_current(layout->root->block, &split->litem);

  return &split->litem;
}

void uiLayoutSetActive(uiLayout *layout, bool active)
{
  layout->active = active;
}

void uiLayoutSetActiveDefault(uiLayout *layout, bool active_default)
{
  layout->active_default = active_default;
}

void uiLayoutSetActivateInit(uiLayout *layout, bool activate_init)
{
  layout->activate_init = activate_init;
}

void uiLayoutSetEnabled(uiLayout *layout, bool enabled)
{
  layout->enabled = enabled;
}

void uiLayoutSetRedAlert(uiLayout *layout, bool redalert)
{
  layout->redalert = redalert;
}

void uiLayoutSetKeepAspect(uiLayout *layout, bool keepaspect)
{
  layout->keepaspect = keepaspect;
}

void uiLayoutSetAlignment(uiLayout *layout, char alignment)
{
  layout->alignment = alignment;
}

void uiLayoutSetScaleX(uiLayout *layout, float scale)
{
  layout->scale[0] = scale;
}

void uiLayoutSetScaleY(uiLayout *layout, float scale)
{
  layout->scale[1] = scale;
}

void uiLayoutSetUnitsX(uiLayout *layout, float unit)
{
  layout->units[0] = unit;
}

void uiLayoutSetUnitsY(uiLayout *layout, float unit)
{
  layout->units[1] = unit;
}

void uiLayoutSetEmboss(uiLayout *layout, char emboss)
{
  layout->emboss = emboss;
}

bool uiLayoutGetPropSep(uiLayout *layout)
{
  return (layout->item.flag & UI_ITEM_PROP_SEP) != 0;
}

void uiLayoutSetPropSep(uiLayout *layout, bool is_sep)
{
  SET_FLAG_FROM_TEST(layout->item.flag, is_sep, UI_ITEM_PROP_SEP);
}

bool uiLayoutGetPropDecorate(uiLayout *layout)
{
  return (layout->item.flag & UI_ITEM_PROP_DECORATE) != 0;
}

void uiLayoutSetPropDecorate(uiLayout *layout, bool is_sep)
{
  SET_FLAG_FROM_TEST(layout->item.flag, is_sep, UI_ITEM_PROP_DECORATE);
}

bool uiLayoutGetActive(uiLayout *layout)
{
  return layout->active;
}

bool uiLayoutGetActiveDefault(uiLayout *layout)
{
  return layout->active_default;
}

bool uiLayoutGetActivateInit(uiLayout *layout)
{
  return layout->activate_init;
}

bool uiLayoutGetEnabled(uiLayout *layout)
{
  return layout->enabled;
}

bool uiLayoutGetRedAlert(uiLayout *layout)
{
  return layout->redalert;
}

bool uiLayoutGetKeepAspect(uiLayout *layout)
{
  return layout->keepaspect;
}

int uiLayoutGetAlignment(uiLayout *layout)
{
  return layout->alignment;
}

int uiLayoutGetWidth(uiLayout *layout)
{
  return layout->w;
}

float uiLayoutGetScaleX(uiLayout *layout)
{
  return layout->scale[0];
}

float uiLayoutGetScaleY(uiLayout *layout)
{
  return layout->scale[1];
}

float uiLayoutGetUnitsX(uiLayout *layout)
{
  return layout->units[0];
}

float uiLayoutGetUnitsY(uiLayout *layout)
{
  return layout->units[1];
}

int uiLayoutGetEmboss(uiLayout *layout)
{
  if (layout->emboss == UI_EMBOSS_UNDEFINED) {
    return layout->root->block->emboss;
  }
  return layout->emboss;
}

/**
 * Tags the layout root as search only, meaning the search process will run, but not the rest of
 * the layout process. Use in situations where part of the block's contents normally wouldn't be
 * drawn, but must be searched anyway, like the contents of closed panels with headers.
 */
void uiLayoutRootSetSearchOnly(uiLayout *layout, bool search_only)
{
  layout->root->search_only = search_only;
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Block Layout Search Filtering
 * \{ */

static void layout_root_free(uiLayoutRoot *root);

// #define PROPERTY_SEARCH_USE_TOOLTIPS

static bool block_search_panel_label_matches(const uiBlock *block)
{
  if ((block->panel != NULL) && (block->panel->type != NULL)) {
    if (BLI_strcasestr(block->panel->type->label, block->search_filter)) {
      return true;
    }
  }
  return false;
}

/**
 * Buttons for search only layouts (closed panel subpanels) have still been added from the
 * layout functions, but they need to be hidden. Theoretically they could be removed too.
 */
static void layout_free_and_hide_buttons(uiLayout *layout)
{
  LISTBASE_FOREACH_MUTABLE (uiItem *, item, &layout->items) {
    if (item->type == ITEM_BUTTON) {
      uiButtonItem *button_item = (uiButtonItem *)item;
      BLI_assert(button_item->but != NULL);
      button_item->but->flag |= UI_HIDDEN;
      MEM_freeN(item);
    }
    else {
      layout_free_and_hide_buttons((uiLayout *)item);
    }
  }

  MEM_freeN(layout);
}

/**
 * Remove layouts used only for search and hide their buttons.
 */
static void block_search_remove_search_only_roots(uiBlock *block)
{
  LISTBASE_FOREACH_MUTABLE (uiLayoutRoot *, root, &block->layouts) {
    if (root->search_only) {
      layout_free_and_hide_buttons(root->layout);
      BLI_remlink(&block->layouts, root);
      layout_root_free(root);
    }
  }
}

/**
 * Returns true if a button or the data / operator it represents matches the search filter.
 */
static bool button_matches_search_filter(uiBut *but, const char *search_filter)
{
  /* Do the shorter checks first for performance reasons. */
  if (BLI_strcasestr(but->str, search_filter)) {
    return true;
  }

  if (but->optype != NULL) {
    if (BLI_strcasestr(but->optype->name, search_filter)) {
      return true;
    }
  }

  if (but->rnaprop != NULL) {
    if (BLI_strcasestr(RNA_property_ui_name(but->rnaprop), search_filter)) {
      return true;
    }
#ifdef PROPERTY_SEARCH_USE_TOOLTIPS
    if (BLI_strcasestr(RNA_property_description(but->rnaprop), search_filter)) {
      return true;
    }
#endif

    /* Search through labels of enum property items if they are in a dropdown menu.
     * Unfortunately we have no context here so we cannot search through RNA enums
     * with dynamic entries (or "itemf" functions) which require context. */
    if (but->type == UI_BTYPE_MENU) {
      PointerRNA *ptr = &but->rnapoin;
      PropertyRNA *enum_prop = but->rnaprop;

      int items_len;
      const EnumPropertyItem *items_array = NULL;
      bool free;
      RNA_property_enum_items_gettexted(NULL, ptr, enum_prop, &items_array, &items_len, &free);

      if (items_array == NULL) {
        return false;
      }

      for (int i = 0; i < items_len; i++) {
        if (BLI_strcasestr(items_array[i].name, search_filter)) {
          return true;
        }
      }
      if (free) {
        MEM_freeN((EnumPropertyItem *)items_array);
      }
    }
  }

  return false;
}

/**
 * Test for a search result within the a specific button group.
 */
static bool button_group_has_search_match(uiButtonGroup *button_group, const char *search_filter)
{
  LISTBASE_FOREACH (LinkData *, link, &button_group->buttons) {
    uiBut *but = link->data;
    if (button_matches_search_filter(but, search_filter)) {
      return true;
    }
  }

  return false;
}

/**
 * Apply the search filter, tagging all buttons with whether they match or not.
 * Tag every button in the group as a search match if any button matches.
 *
 * \note It would be great to return early here if we found a match, but because
 * the results could be visible we have to continue searching the entire block.
 *
 * \return Whether the block has any search results.
 */
static bool block_search_filter_tag_buttons(uiBlock *block)
{
  bool has_result = false;
  LISTBASE_FOREACH (uiLayoutRoot *, root, &block->layouts) {
    LISTBASE_FOREACH (uiButtonGroup *, button_group, &root->button_groups) {
      if (button_group_has_search_match(button_group, block->search_filter)) {
        LISTBASE_FOREACH (LinkData *, link, &button_group->buttons) {
          uiBut *but = link->data;
          but->flag |= UI_SEARCH_FILTER_MATCHES;
        }
        has_result = true;
      }
    }
  }
  return has_result;
}

static void block_search_deactivate_buttons(uiBlock *block)
{
  LISTBASE_FOREACH (uiBut *, but, &block->buttons) {
    if (!(but->flag & UI_SEARCH_FILTER_MATCHES)) {
      but->flag |= UI_BUT_INACTIVE;
    }
  }
}

/**
 * Apply property search behavior, setting panel flags and deactivating buttons that don't match.
 *
 * \note Must be run before #UI_block_layout_resolve.
 */
void UI_block_apply_search_filter(uiBlock *block)
{
  if (!(block->search_filter && block->search_filter[0])) {
    return;
  }

  const bool panel_label_matches = block_search_panel_label_matches(block);

  const bool has_result = panel_label_matches ? true : block_search_filter_tag_buttons(block);

  block_search_remove_search_only_roots(block);

  if (block->panel != NULL) {
    ui_panel_set_search_filter_match(block->panel, has_result);
  }

  if (!panel_label_matches) {
    block_search_deactivate_buttons(block);
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Layout
 * \{ */

static void ui_item_scale(uiLayout *litem, const float scale[2])
{
  int x, y, w, h;

  LISTBASE_FOREACH_BACKWARD (uiItem *, item, &litem->items) {
    if (item->type != ITEM_BUTTON) {
      uiLayout *subitem = (uiLayout *)item;
      ui_item_scale(subitem, scale);
    }

    ui_item_size(item, &w, &h);
    ui_item_offset(item, &x, &y);

    if (scale[0] != 0.0f) {
      x *= scale[0];
      w *= scale[0];
    }

    if (scale[1] != 0.0f) {
      y *= scale[1];
      h *= scale[1];
    }

    ui_item_position(item, x, y, w, h);
  }
}

static void ui_item_estimate(uiItem *item)
{
  if (item->type != ITEM_BUTTON) {
    uiLayout *litem = (uiLayout *)item;

    LISTBASE_FOREACH (uiItem *, subitem, &litem->items) {
      ui_item_estimate(subitem);
    }

    if (BLI_listbase_is_empty(&litem->items)) {
      litem->w = 0;
      litem->h = 0;
      return;
    }

    if (litem->scale[0] != 0.0f || litem->scale[1] != 0.0f) {
      ui_item_scale(litem, litem->scale);
    }

    switch (litem->item.type) {
      case ITEM_LAYOUT_COLUMN:
        ui_litem_estimate_column(litem, false);
        break;
      case ITEM_LAYOUT_COLUMN_FLOW:
        ui_litem_estimate_column_flow(litem);
        break;
      case ITEM_LAYOUT_GRID_FLOW:
        ui_litem_estimate_grid_flow(litem);
        break;
      case ITEM_LAYOUT_ROW:
        ui_litem_estimate_row(litem);
        break;
      case ITEM_LAYOUT_BOX:
        ui_litem_estimate_box(litem);
        break;
      case ITEM_LAYOUT_ROOT:
        ui_litem_estimate_root(litem);
        break;
      case ITEM_LAYOUT_ABSOLUTE:
        ui_litem_estimate_absolute(litem);
        break;
      case ITEM_LAYOUT_SPLIT:
        ui_litem_estimate_split(litem);
        break;
      case ITEM_LAYOUT_OVERLAP:
        ui_litem_estimate_overlap(litem);
        break;
      default:
        break;
    }

    /* Force fixed size. */
    if (litem->units[0] > 0) {
      litem->w = UI_UNIT_X * litem->units[0];
    }
    if (litem->units[1] > 0) {
      litem->h = UI_UNIT_Y * litem->units[1];
    }
  }
}

static void ui_item_align(uiLayout *litem, short nr)
{
  uiButtonItem *bitem;
  uiLayoutItemBx *box;

  LISTBASE_FOREACH_BACKWARD (uiItem *, item, &litem->items) {
    if (item->type == ITEM_BUTTON) {
      bitem = (uiButtonItem *)item;
#ifndef USE_UIBUT_SPATIAL_ALIGN
      if (ui_but_can_align(bitem->but))
#endif
      {
        if (!bitem->but->alignnr) {
          bitem->but->alignnr = nr;
        }
      }
    }
    else if (item->type == ITEM_LAYOUT_ABSOLUTE) {
      /* pass */
    }
    else if (item->type == ITEM_LAYOUT_OVERLAP) {
      /* pass */
    }
    else if (item->type == ITEM_LAYOUT_BOX) {
      box = (uiLayoutItemBx *)item;
      if (!box->roundbox->alignnr) {
        box->roundbox->alignnr = nr;
      }
    }
    else if (((uiLayout *)item)->align) {
      ui_item_align((uiLayout *)item, nr);
    }
  }
}

static void ui_item_flag(uiLayout *litem, int flag)
{
  uiButtonItem *bitem;

  LISTBASE_FOREACH_BACKWARD (uiItem *, item, &litem->items) {
    if (item->type == ITEM_BUTTON) {
      bitem = (uiButtonItem *)item;
      bitem->but->flag |= flag;
    }
    else {
      ui_item_flag((uiLayout *)item, flag);
    }
  }
}

static void ui_item_layout(uiItem *item)
{
  if (item->type != ITEM_BUTTON) {
    uiLayout *litem = (uiLayout *)item;

    if (BLI_listbase_is_empty(&litem->items)) {
      return;
    }

    if (litem->align) {
      ui_item_align(litem, ++litem->root->block->alignnr);
    }
    if (!litem->active) {
      ui_item_flag(litem, UI_BUT_INACTIVE);
    }
    if (!litem->enabled) {
      ui_item_flag(litem, UI_BUT_DISABLED);
    }

    switch (litem->item.type) {
      case ITEM_LAYOUT_COLUMN:
        ui_litem_layout_column(litem, false);
        break;
      case ITEM_LAYOUT_COLUMN_FLOW:
        ui_litem_layout_column_flow(litem);
        break;
      case ITEM_LAYOUT_GRID_FLOW:
        ui_litem_layout_grid_flow(litem);
        break;
      case ITEM_LAYOUT_ROW:
        ui_litem_layout_row(litem);
        break;
      case ITEM_LAYOUT_BOX:
        ui_litem_layout_box(litem);
        break;
      case ITEM_LAYOUT_ROOT:
        ui_litem_layout_root(litem);
        break;
      case ITEM_LAYOUT_ABSOLUTE:
        ui_litem_layout_absolute(litem);
        break;
      case ITEM_LAYOUT_SPLIT:
        ui_litem_layout_split(litem);
        break;
      case ITEM_LAYOUT_OVERLAP:
        ui_litem_layout_overlap(litem);
        break;
      case ITEM_LAYOUT_RADIAL:
        ui_litem_layout_radial(litem);
        break;
      default:
        break;
    }

    LISTBASE_FOREACH (uiItem *, subitem, &litem->items) {
      if (item->flag & UI_ITEM_BOX_ITEM) {
        subitem->flag |= UI_ITEM_BOX_ITEM;
      }
      ui_item_layout(subitem);
    }
  }
  else {
    if (item->flag & UI_ITEM_BOX_ITEM) {
      uiButtonItem *bitem = (uiButtonItem *)item;
      bitem->but->drawflag |= UI_BUT_BOX_ITEM;
    }
  }
}

static void ui_layout_end(uiBlock *block, uiLayout *layout, int *r_x, int *r_y)
{
  if (layout->root->handlefunc) {
    UI_block_func_handle_set(block, layout->root->handlefunc, layout->root->argv);
  }

  ui_item_estimate(&layout->item);
  ui_item_layout(&layout->item);

  if (r_x) {
    *r_x = layout->x;
  }
  if (r_y) {
    *r_y = layout->y;
  }
}

static void ui_layout_free(uiLayout *layout)
{
  LISTBASE_FOREACH_MUTABLE (uiItem *, item, &layout->items) {
    if (item->type == ITEM_BUTTON) {
      MEM_freeN(item);
    }
    else {
      ui_layout_free((uiLayout *)item);
    }
  }

  MEM_freeN(layout);
}

static void layout_root_free(uiLayoutRoot *root)
{
  LISTBASE_FOREACH_MUTABLE (uiButtonGroup *, button_group, &root->button_groups) {
    button_group_free(button_group);
  }
  MEM_freeN(root);
}

static void ui_layout_add_padding_button(uiLayoutRoot *root)
{
  if (root->padding) {
    /* add an invisible button for padding */
    uiBlock *block = root->block;
    uiLayout *prev_layout = block->curlayout;

    block->curlayout = root->layout;
    uiDefBut(
        block, UI_BTYPE_SEPR, 0, "", 0, 0, root->padding, root->padding, NULL, 0.0, 0.0, 0, 0, "");
    block->curlayout = prev_layout;
  }
}

uiLayout *UI_block_layout(uiBlock *block,
                          int dir,
                          int type,
                          int x,
                          int y,
                          int size,
                          int em,
                          int padding,
                          const uiStyle *style)
{
  uiLayout *layout;
  uiLayoutRoot *root;

  root = MEM_callocN(sizeof(uiLayoutRoot), "uiLayoutRoot");
  root->type = type;
  root->style = style;
  root->block = block;
  root->padding = padding;
  root->opcontext = WM_OP_INVOKE_REGION_WIN;

  BLI_listbase_clear(&root->button_groups);
  layout_root_new_button_group(root);

  layout = MEM_callocN(sizeof(uiLayout), "uiLayout");
  layout->item.type = (type == UI_LAYOUT_VERT_BAR) ? ITEM_LAYOUT_COLUMN : ITEM_LAYOUT_ROOT;

  /* Only used when 'UI_ITEM_PROP_SEP' is set. */
  layout->item.flag = UI_ITEM_PROP_DECORATE;

  layout->x = x;
  layout->y = y;
  layout->root = root;
  layout->space = style->templatespace;
  layout->active = 1;
  layout->enabled = 1;
  layout->context = NULL;
  layout->emboss = UI_EMBOSS_UNDEFINED;

  if (type == UI_LAYOUT_MENU || type == UI_LAYOUT_PIEMENU) {
    layout->space = 0;
  }

  if (dir == UI_LAYOUT_HORIZONTAL) {
    layout->h = size;
    layout->root->emh = em * UI_UNIT_Y;
  }
  else {
    layout->w = size;
    layout->root->emw = em * UI_UNIT_X;
  }

  block->curlayout = layout;
  root->layout = layout;
  BLI_addtail(&block->layouts, root);

  ui_layout_add_padding_button(root);

  return layout;
}

uiBlock *uiLayoutGetBlock(uiLayout *layout)
{
  return layout->root->block;
}

int uiLayoutGetOperatorContext(uiLayout *layout)
{
  return layout->root->opcontext;
}

void UI_block_layout_set_current(uiBlock *block, uiLayout *layout)
{
  block->curlayout = layout;
}

void ui_layout_add_but(uiLayout *layout, uiBut *but)
{
  uiButtonItem *bitem;

  bitem = MEM_callocN(sizeof(uiButtonItem), "uiButtonItem");
  bitem->item.type = ITEM_BUTTON;
  bitem->but = but;

  int w, h;
  ui_item_size((uiItem *)bitem, &w, &h);
  /* XXX uiBut hasn't scaled yet
   * we can flag the button as not expandable, depending on its size */
  if (w <= 2 * UI_UNIT_X && (!but->str || but->str[0] == '\0')) {
    bitem->item.flag |= UI_ITEM_FIXED_SIZE;
  }

  if (layout->child_items_layout) {
    BLI_addtail(&layout->child_items_layout->items, bitem);
  }
  else {
    BLI_addtail(&layout->items, bitem);
  }
  but->layout = layout;

  if (layout->context) {
    but->context = layout->context;
    but->context->used = true;
  }

  if (layout->emboss != UI_EMBOSS_UNDEFINED) {
    but->emboss = layout->emboss;
  }

  button_group_add_but(layout->root, but);
}

bool ui_layout_replace_but_ptr(uiLayout *layout, const void *old_but_ptr, uiBut *new_but)
{
  ListBase *child_list = layout->child_items_layout ? &layout->child_items_layout->items :
                                                      &layout->items;

  LISTBASE_FOREACH (uiItem *, item, child_list) {
    if (item->type == ITEM_BUTTON) {
      uiButtonItem *bitem = (uiButtonItem *)item;

      if (bitem->but == old_but_ptr) {
        bitem->but = new_but;
        return true;
      }
    }
    else {
      if (ui_layout_replace_but_ptr((uiLayout *)item, old_but_ptr, new_but)) {
        return true;
      }
    }
  }

  return false;
}

void uiLayoutSetFixedSize(uiLayout *layout, bool fixed_size)
{
  if (fixed_size) {
    layout->item.flag |= UI_ITEM_FIXED_SIZE;
  }
  else {
    layout->item.flag &= ~UI_ITEM_FIXED_SIZE;
  }
}

bool uiLayoutGetFixedSize(uiLayout *layout)
{
  return (layout->item.flag & UI_ITEM_FIXED_SIZE) != 0;
}

void uiLayoutSetOperatorContext(uiLayout *layout, int opcontext)
{
  layout->root->opcontext = opcontext;
}

void uiLayoutSetFunc(uiLayout *layout, uiMenuHandleFunc handlefunc, void *argv)
{
  layout->root->handlefunc = handlefunc;
  layout->root->argv = argv;
}

void UI_block_layout_resolve(uiBlock *block, int *r_x, int *r_y)
{
  BLI_assert(block->active);

  if (r_x) {
    *r_x = 0;
  }
  if (r_y) {
    *r_y = 0;
  }

  block->curlayout = NULL;

  LISTBASE_FOREACH_MUTABLE (uiLayoutRoot *, root, &block->layouts) {
    /* Seach only roots should be removed by #UI_block_apply_search_filter. */
    BLI_assert(!root->search_only);

    ui_layout_add_padding_button(root);

    /* NULL in advance so we don't interfere when adding button */
    ui_layout_end(block, root->layout, r_x, r_y);
    ui_layout_free(root->layout);
    layout_root_free(root);
  }

  BLI_listbase_clear(&block->layouts);

  /* XXX silly trick, interface_templates.c doesn't get linked
   * because it's not used by other files in this module? */
  {
    UI_template_fix_linking();
  }
}

void uiLayoutSetContextPointer(uiLayout *layout, const char *name, PointerRNA *ptr)
{
  uiBlock *block = layout->root->block;
  layout->context = CTX_store_add(&block->contexts, name, ptr);
}

void uiLayoutContextCopy(uiLayout *layout, bContextStore *context)
{
  uiBlock *block = layout->root->block;
  layout->context = CTX_store_add_all(&block->contexts, context);
}

void uiLayoutSetContextFromBut(uiLayout *layout, uiBut *but)
{
  if (but->opptr) {
    uiLayoutSetContextPointer(layout, "button_operator", but->opptr);
  }

  if (but->rnapoin.data && but->rnaprop) {
    /* TODO: index could be supported as well */
    PointerRNA ptr_prop;
    RNA_pointer_create(NULL, &RNA_Property, but->rnaprop, &ptr_prop);
    uiLayoutSetContextPointer(layout, "button_prop", &ptr_prop);
    uiLayoutSetContextPointer(layout, "button_pointer", &but->rnapoin);
  }
}

/* this is a bit of a hack but best keep it in one place at least */
wmOperatorType *UI_but_operatortype_get_from_enum_menu(uiBut *but, PropertyRNA **r_prop)
{
  if (r_prop != NULL) {
    *r_prop = NULL;
  }

  if (but->menu_create_func == menu_item_enum_opname_menu) {
    MenuItemLevel *lvl = but->func_argN;
    wmOperatorType *ot = WM_operatortype_find(lvl->opname, false);
    if ((ot != NULL) && (r_prop != NULL)) {
      *r_prop = RNA_struct_type_find_property(ot->srna, lvl->propname);
    }
    return ot;
  }
  return NULL;
}

/* this is a bit of a hack but best keep it in one place at least */
MenuType *UI_but_menutype_get(uiBut *but)
{
  if (but->menu_create_func == ui_item_menutype_func) {
    return (MenuType *)but->poin;
  }
  return NULL;
}

/* this is a bit of a hack but best keep it in one place at least */
PanelType *UI_but_paneltype_get(uiBut *but)
{
  if (but->menu_create_func == ui_item_paneltype_func) {
    return (PanelType *)but->poin;
  }
  return NULL;
}

void UI_menutype_draw(bContext *C, MenuType *mt, struct uiLayout *layout)
{
  Menu menu = {
      .layout = layout,
      .type = mt,
  };

  if (G.debug & G_DEBUG_WM) {
    printf("%s: opening menu \"%s\"\n", __func__, mt->idname);
  }

  if (layout->context) {
    CTX_store_set(C, layout->context);
  }

  mt->draw(C, &menu);

  if (layout->context) {
    CTX_store_set(C, NULL);
  }
}

static bool ui_layout_has_panel_label(const uiLayout *layout, const PanelType *pt)
{
  LISTBASE_FOREACH (uiItem *, subitem, &layout->items) {
    if (subitem->type == ITEM_BUTTON) {
      uiButtonItem *bitem = (uiButtonItem *)subitem;
      if (!(bitem->but->flag & UI_HIDDEN) && STREQ(bitem->but->str, pt->label)) {
        return true;
      }
    }
    else {
      uiLayout *litem = (uiLayout *)subitem;
      if (ui_layout_has_panel_label(litem, pt)) {
        return true;
      }
    }
  }

  return false;
}

static void ui_paneltype_draw_impl(bContext *C, PanelType *pt, uiLayout *layout, bool show_header)
{
  Panel *panel = MEM_callocN(sizeof(Panel), "popover panel");
  panel->type = pt;
  panel->flag = PNL_POPOVER;

  uiLayout *last_item = layout->items.last;

  /* Draw main panel. */
  if (show_header) {
    uiLayout *row = uiLayoutRow(layout, false);
    if (pt->draw_header) {
      panel->layout = row;
      pt->draw_header(C, panel);
      panel->layout = NULL;
    }

    /* draw_header() is often used to add a checkbox to the header. If we add the label like below
     * the label is disconnected from the checkbox, adding a weird looking gap. As workaround, let
     * the checkbox add the label instead. */
    if (!ui_layout_has_panel_label(row, pt)) {
      uiItemL(row, CTX_IFACE_(pt->translation_context, pt->label), ICON_NONE);
    }
  }

  panel->layout = layout;
  pt->draw(C, panel);
  panel->layout = NULL;
  BLI_assert(panel->runtime.custom_data_ptr == NULL);

  MEM_freeN(panel);

  /* Draw child panels. */
  LISTBASE_FOREACH (LinkData *, link, &pt->children) {
    PanelType *child_pt = link->data;

    if (child_pt->poll == NULL || child_pt->poll(C, child_pt)) {
      /* Add space if something was added to the layout. */
      if (last_item != layout->items.last) {
        uiItemS(layout);
        last_item = layout->items.last;
      }

      uiLayout *col = uiLayoutColumn(layout, false);
      ui_paneltype_draw_impl(C, child_pt, col, true);
    }
  }
}

/**
 * Used for popup panels only.
 */
void UI_paneltype_draw(bContext *C, PanelType *pt, uiLayout *layout)
{
  if (layout->context) {
    CTX_store_set(C, layout->context);
  }

  ui_paneltype_draw_impl(C, pt, layout, false);

  if (layout->context) {
    CTX_store_set(C, NULL);
  }
}

/** \} */

/* -------------------------------------------------------------------- */
/** \name Layout (Debugging/Introspection)
 *
 * Serialize the layout as a Python compatible dictionary,
 *
 * \note Proper string escaping isn't used,
 * triple quotes are used to prevent single quotes from interfering with Python syntax.
 * If we want this to be fool-proof, we would need full Python compatible string escape support.
 * As we don't use triple quotes in the UI it's good-enough in practice.
 * \{ */

static void ui_layout_introspect_button(DynStr *ds, uiButtonItem *bitem)
{
  uiBut *but = bitem->but;
  BLI_dynstr_appendf(ds, "'type':%d, ", (int)but->type);
  BLI_dynstr_appendf(ds, "'draw_string':'''%s''', ", but->drawstr);
  /* Not exactly needed, rna has this. */
  BLI_dynstr_appendf(ds, "'tip':'''%s''', ", but->tip ? but->tip : "");

  if (but->optype) {
    char *opstr = WM_operator_pystring_ex(
        but->block->evil_C, NULL, false, true, but->optype, but->opptr);
    BLI_dynstr_appendf(ds, "'operator':'''%s''', ", opstr ? opstr : "");
    MEM_freeN(opstr);
  }

  {
    PropertyRNA *prop = NULL;
    wmOperatorType *ot = UI_but_operatortype_get_from_enum_menu(but, &prop);
    if (ot) {
      char *opstr = WM_operator_pystring_ex(but->block->evil_C, NULL, false, true, ot, NULL);
      BLI_dynstr_appendf(ds, "'operator':'''%s''', ", opstr ? opstr : "");
      BLI_dynstr_appendf(ds, "'property':'''%s''', ", prop ? RNA_property_identifier(prop) : "");
      MEM_freeN(opstr);
    }
  }

  if (but->rnaprop) {
    BLI_dynstr_appendf(ds,
                       "'rna':'%s.%s[%d]', ",
                       RNA_struct_identifier(but->rnapoin.type),
                       RNA_property_identifier(but->rnaprop),
                       but->rnaindex);
  }
}

static void ui_layout_introspect_items(DynStr *ds, ListBase *lb)
{
  uiItem *item;

  BLI_dynstr_append(ds, "[");

  for (item = lb->first; item; item = item->next) {

    BLI_dynstr_append(ds, "{");

#define CASE_ITEM(id) \
  case id: { \
    const char *id_str = STRINGIFY(id); \
    BLI_dynstr_append(ds, "'type': '"); \
    /* Skip 'ITEM_'. */ \
    BLI_dynstr_append(ds, id_str + 5); \
    BLI_dynstr_append(ds, "', "); \
    break; \
  } \
    ((void)0)

    switch (item->type) {
      CASE_ITEM(ITEM_BUTTON);
      CASE_ITEM(ITEM_LAYOUT_ROW);
      CASE_ITEM(ITEM_LAYOUT_COLUMN);
      CASE_ITEM(ITEM_LAYOUT_COLUMN_FLOW);
      CASE_ITEM(ITEM_LAYOUT_ROW_FLOW);
      CASE_ITEM(ITEM_LAYOUT_BOX);
      CASE_ITEM(ITEM_LAYOUT_ABSOLUTE);
      CASE_ITEM(ITEM_LAYOUT_SPLIT);
      CASE_ITEM(ITEM_LAYOUT_OVERLAP);
      CASE_ITEM(ITEM_LAYOUT_ROOT);
      CASE_ITEM(ITEM_LAYOUT_GRID_FLOW);
      CASE_ITEM(ITEM_LAYOUT_RADIAL);
    }

#undef CASE_ITEM

    switch (item->type) {
      case ITEM_BUTTON:
        ui_layout_introspect_button(ds, (uiButtonItem *)item);
        break;
      default:
        BLI_dynstr_append(ds, "'items':");
        ui_layout_introspect_items(ds, &((uiLayout *)item)->items);
        break;
    }

    BLI_dynstr_append(ds, "}");

    if (item != lb->last) {
      BLI_dynstr_append(ds, ", ");
    }
  }
  /* Don't use a comma here as it's not needed and
   * causes the result to evaluate to a tuple of 1. */
  BLI_dynstr_append(ds, "]");
}

/**
 * Evaluate layout items as a Python dictionary.
 */
const char *UI_layout_introspect(uiLayout *layout)
{
  DynStr *ds = BLI_dynstr_new();
  uiLayout layout_copy = *layout;
  layout_copy.item.next = NULL;
  layout_copy.item.prev = NULL;
  ListBase layout_dummy_list = {&layout_copy, &layout_copy};
  ui_layout_introspect_items(ds, &layout_dummy_list);
  const char *result = BLI_dynstr_get_cstring(ds);
  BLI_dynstr_free(ds);
  return result;
}

/** \} */