zng_app/widget/builder.rs
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
//! Widget and property builder types.
use crate::{handler::WidgetHandler, widget::node::WhenUiNodeListBuilder};
use std::{
any::{Any, TypeId},
collections::{hash_map, HashMap},
fmt, ops,
sync::Arc,
};
#[doc(hidden)]
pub use zng_var::{getter_var, state_var};
///<span data-del-macro-root></span> New [`SourceLocation`] that represents the location you call this macro.
///
/// This value is used by widget info to mark the property and `when` block declaration source code.
#[macro_export]
macro_rules! source_location {
() => {
$crate::widget::builder::SourceLocation {
file: std::file!(),
line: std::line!(),
column: std::column!(),
}
};
}
#[doc(inline)]
pub use crate::source_location;
/// A location in source-code.
///
/// This value is used by widget info to mark the property and `when` block declaration source code.
///
/// Use [`source_location!`] to construct.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct SourceLocation {
/// [`std::file!`]
pub file: &'static str,
/// [`std::line!`]
pub line: u32,
/// [`std::column!`]
pub column: u32,
}
impl fmt::Display for SourceLocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}:{}", self.file, self.line, self.column)
}
}
#[doc(hidden)]
pub fn when_condition_expr_var(expr_var: impl Var<bool>) -> BoxedVar<bool> {
expr_var.boxed()
}
#[doc(hidden)]
pub struct WgtInfo;
impl WidgetExt for WgtInfo {
fn ext_property__(&mut self, _: Box<dyn PropertyArgs>) {
panic!("WgtInfo is for extracting info only")
}
fn ext_property_unset__(&mut self, _: PropertyId) {
panic!("WgtInfo is for extracting info only")
}
}
///<span data-del-macro-root></span> New [`PropertyId`] that represents the type and name.
///
/// # Syntax
///
/// * `path::property`: Gets the ID for the property function.
/// * `Self::property`: Gets the ID for the property method on the widget.
///
/// # Examples
///
/// ```
/// # use zng_app::{*, widget::{node::*, builder::*, property, widget}};
/// # use zng_var::*;
/// # pub mod path {
/// # use super::*;
/// # #[property(CONTEXT)]
/// # pub fn foo(child: impl UiNode, bar: impl IntoValue<bool>) -> impl UiNode {
/// # child
/// # }
/// # }
/// # #[widget($crate::FooWgt)]
/// # pub struct FooWgt(zng_app::widget::base::WidgetBase);
/// # #[property(CONTEXT, widget_impl(FooWgt))]
/// # pub fn bar(child: impl UiNode, bar: impl IntoValue<bool>) -> impl UiNode {
/// # child
/// # }
/// # fn main() {
/// let foo_id = property_id!(path::foo);
/// let bar_id = property_id!(bar);
///
/// assert_ne!(foo_id, bar_id);
/// # }
/// ```
#[macro_export]
macro_rules! property_id {
($($tt:tt)*) => {
$crate::widget::property_meta!($($tt)*).id()
}
}
#[doc(inline)]
pub use crate::property_id;
///<span data-del-macro-root></span> New [`PropertyInfo`] from property path.
///
/// # Syntax
///
/// * `path::property`: Gets the info for the property function.
/// * `Self::property`: Gets the info for the property method on the widget.
///
/// # Examples
///
/// ```
/// # use zng_app::{*, widget::{node::*, builder::*, property}};
/// # use zng_var::*;
/// # pub mod path {
/// # use super::*;
/// #[property(CONTEXT)]
/// pub fn foo(child: impl UiNode, bar: impl IntoValue<bool>) -> impl UiNode {
/// // ..
/// # child
/// }
/// # }
/// # fn main() {
/// #
///
/// assert_eq!(property_info!(path::foo).inputs[0].name, "bar");
/// # }
/// ```
#[macro_export]
macro_rules! property_info {
($($property:ident)::+ <$($generics:ty),*>) => {
$crate::widget::property_meta!($($property)::+).info::<$($generics),*>()
};
($($tt:tt)*) => {
$crate::widget::property_meta!($($tt)*).info()
}
}
#[doc(inline)]
pub use crate::property_info;
///<span data-del-macro-root></span> Gets the strong input storage types from a property path.
///
/// See [`PropertyInputTypes<Tuple>`] for more details.
///
/// # Syntax
///
/// * `property::path`: Gets the input types for the property function.
/// * `Self::property`: Gets the input types for the property method on the widget.
#[macro_export]
macro_rules! property_input_types {
($($tt:tt)*) => {
$crate::widget::property_meta!($($tt)*).input_types()
}
}
#[doc(inline)]
pub use crate::property_input_types;
///<span data-del-macro-root></span> New [`Box<PropertyArgs>`](PropertyArgs) box from a property and value.
///
/// # Syntax
///
/// The syntax is similar to a property assign in a widget.
///
/// * `property::path = <value>;` - Args for the property function.
/// * `property::path;` - Args for property with input of the same name, `path` here.
///
/// The `<value>` is the standard property init expression or named fields patterns that are used in widget assigns.
///
/// * `property = "value-0", "value-1";` - Unnamed args.
/// * `property = { value_0: "value-0", value_1: "value-1" }` - Named args.
///
/// # Panics
///
/// Panics if `unset!` is used as property value.
#[macro_export]
macro_rules! property_args {
($($property:ident)::+ = $($value:tt)*) => {
{
$crate::widget::builder::PropertyArgsGetter! {
$($property)::+ = $($value)*
}
}
};
($($property:ident)::+ ::<$($generics:ty),*> = $($value:tt)*) => {
{
$crate::widget::builder::PropertyArgsGetter! {
$($property)::+ ::<$($generics),*> = $($value)*
}
}
};
($property:ident $(;)?) => {
{
$crate::widget::builder::PropertyArgsGetter! {
$property
}
}
}
}
#[doc(inline)]
pub use crate::property_args;
///<span data-del-macro-root></span> Gets the [`WidgetType`] info of a widget.
#[macro_export]
macro_rules! widget_type {
($($widget:ident)::+) => {
$($widget)::+::widget_type()
};
}
use parking_lot::Mutex;
#[doc(inline)]
pub use widget_type;
use zng_app_context::context_local;
use zng_app_proc_macros::widget;
use zng_txt::{formatx, Txt};
use zng_unique_id::{unique_id_32, IdEntry, IdMap, IdSet};
use zng_var::{
impl_from_and_into_var,
types::{AnyWhenVarBuilder, ContextualizedVar, WeakContextInitHandle},
AnyVar, AnyVarValue, BoxedAnyVar, BoxedVar, ContextInitHandle, IntoValue, IntoVar, LocalVar, Var, VarValue,
};
use super::{
base::{WidgetBase, WidgetExt},
node::{
with_new_context_init_id, ArcNode, ArcNodeList, BoxedUiNode, BoxedUiNodeList, FillUiNode, UiNode, UiNodeList, WhenUiNodeBuilder,
},
};
#[doc(hidden)]
#[widget($crate::widget::builder::PropertyArgsGetter)]
pub struct PropertyArgsGetter(WidgetBase);
impl PropertyArgsGetter {
pub fn widget_build(&mut self) -> Box<dyn PropertyArgs> {
let mut wgt = self.widget_take();
if !wgt.p.items.is_empty() {
if wgt.p.items.len() > 1 {
tracing::error!("properties ignored, `property_args!` only collects args for first property");
}
match wgt.p.items.remove(0).item {
WidgetItem::Property { args, .. } => args,
WidgetItem::Intrinsic { .. } => unreachable!(),
}
} else if wgt.unset.is_empty() {
panic!("missing property");
} else {
panic!("cannot use `unset!` in `property_args!`")
}
}
}
/// Represents the sort index of a property or intrinsic node in a widget instance.
///
/// Each node "wraps" the next one, so the sort defines `(context#0 (context#1 (event (size (border..)))))`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub struct NestPosition {
/// The major position.
pub group: NestGroup,
/// Extra sorting within items of the same group.
pub index: u16,
}
impl NestPosition {
/// Default index used for intrinsic nodes, is `u16::MAX / 3`.
pub const INTRINSIC_INDEX: u16 = u16::MAX / 3;
/// Default index used for properties, is `INTRINSIC_INDEX * 2`.
pub const PROPERTY_INDEX: u16 = Self::INTRINSIC_INDEX * 2;
/// New position for property.
pub fn property(group: NestGroup) -> Self {
NestPosition {
group,
index: Self::PROPERTY_INDEX,
}
}
/// New position for intrinsic node.
pub fn intrinsic(group: NestGroup) -> Self {
NestPosition {
group,
index: Self::INTRINSIC_INDEX,
}
}
}
impl fmt::Debug for NestPosition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct IndexName(u16);
impl fmt::Debug for IndexName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
NestPosition::INTRINSIC_INDEX => write!(f, "INTRINSIC_INDEX"),
NestPosition::PROPERTY_INDEX => write!(f, "PROPERTY_INDEX"),
i => write!(f, "{i}"),
}
}
}
f.debug_struct("NestPosition")
.field("group", &self.group)
.field("index", &IndexName(self.index))
.finish()
}
}
macro_rules! nest_group_items {
() => {
/// Minimal nest position, property is outside even context properties and is only inside the widget node.
///
/// This is rarely used, prefer using `CONTEXT-n` if you must have a property outside the widget context.
pub const WIDGET: NestGroup = NestGroup(0);
/// Property defines a contextual value or variable.
///
/// Usually these properties don't define behavior, they just configure the widget. A common pattern
/// is defining all widget config as context vars, that are all used by a widget intrinsic node.
///
/// These properties are not expected to affect layout or render, if they do some errors may be logged by the default widget base.
pub const CONTEXT: NestGroup = NestGroup(NestGroup::NEXT_GROUP);
/// Property defines an event handler, or state monitor, they are placed inside all context properties, so can be configured
/// by context, but are still outside of the layout and render nodes.
///
/// Event handlers can be notified before or after the inner child delegation, if handled before the event is said to be *preview*.
/// Implementers can use this intrinsic feature of the UI tree to interrupt notification for child properties and widgets.
///
/// These properties are not expected to affect layout or render, if they do some errors may be logged by the default widget base.
pub const EVENT: NestGroup = NestGroup(NestGroup::CONTEXT.0 + NestGroup::NEXT_GROUP);
/// Property defines the position and size of the widget inside the space made available by the parent widget.
///
/// These properties must accumulatively affect the measure and layout, they must avoid rendering. The computed layout is
/// usually rendered by the widget as a single transform, the layout properties don't need to render transforms.
pub const LAYOUT: NestGroup = NestGroup(NestGroup::EVENT.0 + NestGroup::NEXT_GROUP);
/// Property strongly enforces a widget size.
///
/// Usually the widget final size is a side-effect of all the layout properties, but some properties may enforce a size, they
/// can use this group to ensure that they are inside the other layout properties.
pub const SIZE: NestGroup = NestGroup(NestGroup::LAYOUT.0 + NestGroup::NEXT_GROUP);
/// Minimal widget visual position, any property or node can render, but usually only properties inside
/// this position render. For example, borders will only render correctly inside this nest position.
///
/// This is rarely used, prefer using `BORDER-n` to declare properties that are visually outside the bounds, only
/// use this node for intrinsics that define some inner context or service for the visual properties.
pub const WIDGET_INNER: NestGroup = NestGroup(NestGroup::SIZE.0 + NestGroup::NEXT_GROUP);
/// Property renders a border visual.
///
/// Borders are strictly coordinated, see the [`border`] module for more details. All nodes of this group
/// may render at will, the renderer is already configured to apply the final layout and size.
///
/// [`border`]: crate::widget::border
pub const BORDER: NestGroup = NestGroup(NestGroup::WIDGET_INNER.0 + NestGroup::NEXT_GROUP);
/// Property defines a visual of the widget.
///
/// This is the main render group, it usually defines things like a background fill, but it can render over child nodes simply
/// by choosing to render after the render is delegated to the inner child.
pub const FILL: NestGroup = NestGroup(NestGroup::BORDER.0 + NestGroup::NEXT_GROUP);
/// Property defines contextual value or variable for the inner child or children widgets. Config set here does not affect
/// the widget where it is set, it only affects the descendants.
pub const CHILD_CONTEXT: NestGroup = NestGroup(NestGroup::FILL.0 + NestGroup::NEXT_GROUP);
/// Property defines the layout and size of the child or children widgets. These properties don't affect the layout
/// of the widget where they are set. Some properties are functionally the same, only changing their effect depending on their
/// group, the `margin` and `padding` properties are like this, `margin` is `LAYOUT` and `padding` is `CHILD_LAYOUT`.
pub const CHILD_LAYOUT: NestGroup = NestGroup(NestGroup::CHILD_CONTEXT.0 + NestGroup::NEXT_GROUP);
/// Maximum nest position, property is inside all others and only wraps the widget child node.
///
/// Properties that insert child nodes may use this group, properties that only affect the child layout and want
/// to be inside other child layout should use `CHILD_LAYOUT+n` instead.
pub const CHILD: NestGroup = NestGroup(u16::MAX);
};
}
#[doc(hidden)]
pub mod nest_group_items {
// properties import this const items in their nest group expr, unfortunately we can't import associated const items, so
// they are duplicated here.
use super::NestGroup;
nest_group_items!();
}
/// Property nest position group.
///
/// Each group has `u16::MAX / 9` in between, custom groups can be created using the +/- operations, `SIZE+1` is
/// still outside `BORDER`, but slightly inside `SIZE`.
///
/// See [`NestPosition`] for more details.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct NestGroup(u16);
impl NestGroup {
const NEXT_GROUP: u16 = u16::MAX / 10;
nest_group_items!();
/// All groups, from outermost([`WIDGET`]) to innermost([`CHILD`]).
///
/// [`WIDGET`]: Self::WIDGET
/// [`CHILD`]: Self::CHILD
pub const ITEMS: [Self; 11] = [
Self::WIDGET,
Self::CONTEXT,
Self::EVENT,
Self::LAYOUT,
Self::SIZE,
Self::WIDGET_INNER,
Self::BORDER,
Self::FILL,
Self::CHILD_CONTEXT,
Self::CHILD_LAYOUT,
Self::CHILD,
];
fn exact_name(self) -> &'static str {
if self.0 == Self::WIDGET.0 {
"WIDGET"
} else if self.0 == Self::CONTEXT.0 {
"CONTEXT"
} else if self.0 == Self::EVENT.0 {
"EVENT"
} else if self.0 == Self::LAYOUT.0 {
"LAYOUT"
} else if self.0 == Self::SIZE.0 {
"SIZE"
} else if self.0 == Self::WIDGET_INNER.0 {
"WIDGET_INNER"
} else if self.0 == Self::BORDER.0 {
"BORDER"
} else if self.0 == Self::FILL.0 {
"FILL"
} else if self.0 == Self::CHILD_CONTEXT.0 {
"CHILD_CONTEXT"
} else if self.0 == Self::CHILD_LAYOUT.0 {
"CHILD_LAYOUT"
} else if self.0 == Self::CHILD.0 {
"CHILD"
} else {
""
}
}
/// Group name.
pub fn name(self) -> Txt {
let name = self.exact_name();
if name.is_empty() {
let closest = Self::ITEMS
.into_iter()
.min_by_key(|i| ((self.0 as i32 - i.0 as i32).abs()))
.unwrap();
let diff = self.0 as i32 - closest.0 as i32;
let name = closest.exact_name();
debug_assert!(!name.is_empty());
formatx!("{closest}{diff:+}")
} else {
Txt::from_static(name)
}
}
}
impl fmt::Debug for NestGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(f, "NestGroup::")?;
}
write!(f, "{}", self.name())
}
}
impl fmt::Display for NestGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl ops::Add<i16> for NestGroup {
type Output = Self;
fn add(self, rhs: i16) -> Self::Output {
let r = (self.0 as i32) + rhs as i32;
Self(r.clamp(0, u16::MAX as i32) as u16)
}
}
impl ops::Sub<i16> for NestGroup {
type Output = Self;
fn sub(self, rhs: i16) -> Self::Output {
let r = (self.0 as i32) - rhs as i32;
Self(r.clamp(0, u16::MAX as i32) as u16)
}
}
impl ops::AddAssign<i16> for NestGroup {
fn add_assign(&mut self, rhs: i16) {
*self = *self + rhs;
}
}
impl ops::SubAssign<i16> for NestGroup {
fn sub_assign(&mut self, rhs: i16) {
*self = *self - rhs;
}
}
#[test]
fn nest_group_spacing() {
let mut expected = NestGroup::NEXT_GROUP;
for g in &NestGroup::ITEMS[1..NestGroup::ITEMS.len() - 1] {
assert_eq!(expected, g.0);
expected += NestGroup::NEXT_GROUP;
}
assert_eq!(expected, (u16::MAX / 10) * 10); // 65530
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum NestGroupSerde<'s> {
Named(&'s str),
Unnamed(u16),
}
impl serde::Serialize for NestGroup {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
self.name().serialize(serializer)
} else {
self.0.serialize(serializer)
}
}
}
impl<'de> serde::Deserialize<'de> for NestGroup {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
match NestGroupSerde::deserialize(deserializer)? {
NestGroupSerde::Named(n) => match n.parse() {
Ok(g) => Ok(g),
Err(e) => Err(D::Error::custom(e)),
},
NestGroupSerde::Unnamed(i) => Ok(NestGroup(i)),
}
}
}
impl std::str::FromStr for NestGroup {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut name = s;
let mut add = 0i16;
if let Some((n, a)) = s.split_once('+') {
add = a.parse().map_err(|e| format!("{e}"))?;
name = n;
} else if let Some((n, s)) = s.split_once('-') {
add = -s.parse().map_err(|e| format!("{e}"))?;
name = n;
}
match name {
"WIDGET" => Ok(NestGroup::WIDGET + add),
"CONTEXT" => Ok(NestGroup::CONTEXT + add),
"EVENT" => Ok(NestGroup::EVENT + add),
"LAYOUT" => Ok(NestGroup::LAYOUT + add),
"SIZE" => Ok(NestGroup::SIZE + add),
"BORDER" => Ok(NestGroup::BORDER + add),
"FILL" => Ok(NestGroup::FILL + add),
"CHILD_CONTEXT" => Ok(NestGroup::CHILD_CONTEXT + add),
"CHILD_LAYOUT" => Ok(NestGroup::CHILD_LAYOUT + add),
"CHILD" => Ok(NestGroup::CHILD + add),
ukn => Err(format!("unknown nest group {ukn:?}")),
}
}
}
/// Kind of property input.
#[derive(PartialEq, Eq, Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub enum InputKind {
/// Input is `impl IntoVar<T>`, build value is `BoxedVar<T>`.
Var,
/// Input is `impl IntoValue<T>`, build value is `T`.
Value,
/// Input is `impl UiNode`, build value is `ArcNode<BoxedUiNode>`.
UiNode,
/// Input is `impl UiNodeList`, build value is `ArcNodeList<BoxedUiNodeList>`.
UiNodeList,
/// Input is `impl WidgetHandler<A>`, build value is `ArcWidgetHandler<A>`.
WidgetHandler,
}
/// Represents a [`WidgetHandler<A>`] that can be reused.
///
/// Note that [`hn_once!`] will still only be used once, and [`async_hn!`] tasks are bound to the specific widget
/// context that spawned them. This `struct` is cloneable to support handler properties in styleable widgets, but the
/// general expectation is that the handler will be used on one property instance at a time.
///
/// [`hn_once!`]: macro@crate::handler::hn_once
/// [`async_hn!`]: macro@crate::handler::async_hn
#[derive(Clone)]
pub struct ArcWidgetHandler<A: Clone + 'static>(Arc<Mutex<dyn WidgetHandler<A>>>);
impl<A: Clone + 'static> ArcWidgetHandler<A> {
/// New from `handler`.
pub fn new(handler: impl WidgetHandler<A>) -> Self {
Self(Arc::new(Mutex::new(handler)))
}
}
impl<A: Clone + 'static> WidgetHandler<A> for ArcWidgetHandler<A> {
fn event(&mut self, args: &A) -> bool {
self.0.lock().event(args)
}
fn update(&mut self) -> bool {
self.0.lock().update()
}
}
/// Represents a type erased [`ArcWidgetHandler<A>`].
pub trait AnyArcWidgetHandler: Any {
/// Access to `dyn Any` methods.
fn as_any(&self) -> &dyn Any;
/// Access to `Box<dyn Any>` methods.
fn into_any(self: Box<Self>) -> Box<dyn Any>;
/// Clone the handler reference.
fn clone_boxed(&self) -> Box<dyn AnyArcWidgetHandler>;
}
impl<A: Clone + 'static> AnyArcWidgetHandler for ArcWidgetHandler<A> {
fn clone_boxed(&self) -> Box<dyn AnyArcWidgetHandler> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
}
/// A `when` builder for [`AnyArcWidgetHandler`] values.
///
/// This builder is used to generate a composite handler that redirects to active `when` matched property values.
pub struct AnyWhenArcWidgetHandlerBuilder {
default: Box<dyn AnyArcWidgetHandler>,
conditions: Vec<(BoxedVar<bool>, Box<dyn AnyArcWidgetHandler>)>,
}
impl AnyWhenArcWidgetHandlerBuilder {
/// New from default value.
pub fn new(default: Box<dyn AnyArcWidgetHandler>) -> Self {
Self {
default,
conditions: vec![],
}
}
/// Push a conditional handler.
pub fn push(&mut self, condition: BoxedVar<bool>, handler: Box<dyn AnyArcWidgetHandler>) {
self.conditions.push((condition, handler));
}
/// Build the handler.
pub fn build<A: Clone + 'static>(self) -> ArcWidgetHandler<A> {
match self.default.into_any().downcast::<ArcWidgetHandler<A>>() {
Ok(default) => {
let mut conditions = Vec::with_capacity(self.conditions.len());
for (c, h) in self.conditions {
match h.into_any().downcast::<ArcWidgetHandler<A>>() {
Ok(h) => conditions.push((c, *h)),
Err(_) => continue,
}
}
ArcWidgetHandler::new(WhenWidgetHandler {
default: *default,
conditions,
})
}
Err(_) => panic!("unexpected build type in widget handler when builder"),
}
}
}
struct WhenWidgetHandler<A: Clone + 'static> {
default: ArcWidgetHandler<A>,
conditions: Vec<(BoxedVar<bool>, ArcWidgetHandler<A>)>,
}
impl<A: Clone + 'static> WidgetHandler<A> for WhenWidgetHandler<A> {
fn event(&mut self, args: &A) -> bool {
for (c, h) in &mut self.conditions {
if c.get() {
return h.event(args);
}
}
self.default.event(args)
}
fn update(&mut self) -> bool {
let mut pending = self.default.update();
for (_, h) in &mut self.conditions {
pending |= h.update();
}
pending
}
}
/// Property build actions that must be applied to property args.
///
/// See [`PropertyNewArgs::build_actions`] for more details.
pub type PropertyBuildActions = Vec<Vec<Box<dyn AnyPropertyBuildAction>>>;
/// Data for property build actions associated with when conditions.
///
/// See [`PropertyNewArgs::build_actions_when_data`] for more details.
pub type PropertyBuildActionsWhenData = Vec<Vec<Option<WhenBuildActionData>>>;
/// Args for [`PropertyInfo::new`].
pub struct PropertyNewArgs {
/// Values for each input in the same order they appear in [`PropertyInfo::inputs`], types must match
/// the input kind and type, the function panics if the types don't match or not all inputs are provided.
///
/// The expected types for each [`InputKind`] are:
///
/// | Kind | Expected Type
/// |---------------------|-------------------------------------------------
/// | [`Var`] | `Box<BoxedVar<T>>` or `Box<AnyWhenVarBuilder>`
/// | [`Value`] | `Box<T>`
/// | [`UiNode`] | `Box<ArcNode<BoxedUiNode>>` or `Box<WhenUiNodeBuilder>`
/// | [`UiNodeList`] | `Box<ArcNodeList<BoxedUiNodeList>>` or `Box<WhenUiNodeListBuilder>`
/// | [`WidgetHandler`] | `Box<ArcWidgetHandler<A>>` or `Box<AnyWhenArcWidgetHandlerBuilder>`
///
/// The new function will downcast and unbox the args.
///
/// [`Var`]: InputKind::Var
/// [`Value`]: InputKind::Value
/// [`UiNode`]: InputKind::UiNode
/// [`UiNodeList`]: InputKind::UiNodeList
/// [`WidgetHandler`]: InputKind::WidgetHandler
pub args: Vec<Box<dyn Any>>,
/// The property build actions can be empty or each item must contain one builder for each input in the same order they
/// appear in [`PropertyInfo::inputs`], the function panics if the types don't match or not all inputs are provided.
///
/// The expected types for each [`InputKind`] are:
///
/// | Kind | Expected Type
/// |---------------------|-------------------------------------------------
/// | [`Var`] | `Box<PropertyBuildAction<BoxedVar<T>>>`
/// | [`Value`] | `Box<PropertyBuildAction<T>>`
/// | [`UiNode`] | `Box<PropertyBuildAction<ArcNode<BoxedUiNode>>>`
/// | [`UiNodeList`] | `Box<PropertyBuildAction<ArcNodeList<BoxedUiNodeList>>>`
/// | [`WidgetHandler`] | `Box<PropertyBuildAction<ArcWidgetHandler<A>>>`
///
/// The new function will downcast and unbox the args.
///
/// [`Var`]: InputKind::Var
/// [`Value`]: InputKind::Value
/// [`UiNode`]: InputKind::UiNode
/// [`UiNodeList`]: InputKind::UiNodeList
/// [`WidgetHandler`]: InputKind::WidgetHandler
pub build_actions: PropertyBuildActions,
/// When build action data for each [`build_actions`].
///
/// If not empty, each item is the [`PropertyBuildActionArgs::when_conditions_data`] for each action.
///
/// [`build_actions`]: Self::build_actions
pub build_actions_when_data: PropertyBuildActionsWhenData,
}
/// Property info.
///
/// You can use the [`property_info!`] macro to retrieve a property's info.
#[derive(Debug, Clone)]
pub struct PropertyInfo {
/// Property nest position group.
pub group: NestGroup,
/// Property is "capture-only", no standalone implementation is provided, instantiating does not add a node, just returns the child.
///
/// Note that all properties can be captured, but if this is `false` they provide an implementation that works standalone.
pub capture: bool,
/// Unique ID that identifies the property implementation.
pub id: PropertyId,
/// Property name.
pub name: &'static str,
/// Property declaration location.
pub location: SourceLocation,
/// New default property args.
///
/// This is `Some(_)` only if the `#[property(_, default(..))]` was set in the property declaration.
pub default: Option<fn() -> Box<dyn PropertyArgs>>,
/// New property args from dynamically typed args.
///
/// # Instance
///
/// This function outputs property args, not a property node instance.
/// You can use [`PropertyArgs::instantiate`] on the output to generate a property node from the args. If the
/// property is known at compile time you can use [`property_args!`] to generate args instead, and you can just
/// call the property function directly to instantiate a node.
///
pub new: fn(PropertyNewArgs) -> Box<dyn PropertyArgs>,
/// Property inputs info.
pub inputs: Box<[PropertyInput]>,
}
impl PropertyInfo {
/// Gets the index that can be used to get a named property input value in [`PropertyArgs`].
pub fn input_idx(&self, name: &str) -> Option<usize> {
self.inputs.iter().position(|i| i.name == name)
}
}
/// Property input info.
#[derive(Debug, Clone)]
pub struct PropertyInput {
/// Input name.
pub name: &'static str,
/// Input kind.
pub kind: InputKind,
/// Type as defined by kind.
pub ty: TypeId,
/// Type name.
pub ty_name: &'static str,
}
impl PropertyInput {
/// Shorter [`ty_name`].
///
/// [`ty_name`]: Self::ty_name
pub fn display_ty_name(&self) -> Txt {
pretty_type_name::pretty_type_name_str(self.ty_name).into()
}
}
/// Represents a property instantiation request.
pub trait PropertyArgs: Send + Sync {
/// Clones the arguments.
fn clone_boxed(&self) -> Box<dyn PropertyArgs>;
/// Property info.
fn property(&self) -> PropertyInfo;
/// Gets a [`InputKind::Var`].
///
/// Is a `BoxedVar<T>`.
fn var(&self, i: usize) -> &dyn AnyVar {
panic_input(&self.property(), i, InputKind::Var)
}
/// Gets a [`InputKind::Value`].
fn value(&self, i: usize) -> &dyn AnyVarValue {
panic_input(&self.property(), i, InputKind::Value)
}
/// Gets a [`InputKind::UiNode`].
fn ui_node(&self, i: usize) -> &ArcNode<BoxedUiNode> {
panic_input(&self.property(), i, InputKind::UiNode)
}
/// Gets a [`InputKind::UiNodeList`].
fn ui_node_list(&self, i: usize) -> &ArcNodeList<BoxedUiNodeList> {
panic_input(&self.property(), i, InputKind::UiNodeList)
}
/// Gets a [`InputKind::WidgetHandler`].
///
/// Is a `ArcWidgetHandler<A>`.
fn widget_handler(&self, i: usize) -> &dyn AnyArcWidgetHandler {
panic_input(&self.property(), i, InputKind::WidgetHandler)
}
/// Create a property instance with args clone or taken.
///
/// If the property is [`PropertyInfo::capture`] the `child` is returned.
fn instantiate(&self, child: BoxedUiNode) -> BoxedUiNode;
}
impl dyn PropertyArgs + '_ {
/// Unique ID.
pub fn id(&self) -> PropertyId {
self.property().id
}
/// Gets a strongly typed [`value`].
///
/// Panics if the type does not match.
///
/// [`value`]: PropertyArgs::value
pub fn downcast_value<T>(&self, i: usize) -> &T
where
T: VarValue,
{
self.value(i).as_any().downcast_ref::<T>().expect("cannot downcast value to type")
}
/// Gets a strongly typed [`var`].
///
/// Panics if the variable value type does not match.
///
/// [`var`]: PropertyArgs::var
pub fn downcast_var<T>(&self, i: usize) -> &BoxedVar<T>
where
T: VarValue,
{
self.var(i)
.as_any()
.downcast_ref::<BoxedVar<T>>()
.expect("cannot downcast var to type")
}
/// Gets a strongly typed [`widget_handler`].
///
/// Panics if the args type does not match.
///
/// [`widget_handler`]: PropertyArgs::widget_handler
pub fn downcast_handler<A>(&self, i: usize) -> &ArcWidgetHandler<A>
where
A: 'static + Clone,
{
self.widget_handler(i)
.as_any()
.downcast_ref::<ArcWidgetHandler<A>>()
.expect("cannot downcast handler to type")
}
/// Gets the property input as a debug variable.
///
/// If the input is a variable the returned variable will update with it, if not it is a static print.
///
/// Note that you must call this in the widget context to get the correct value.
pub fn live_debug(&self, i: usize) -> BoxedVar<Txt> {
let p = self.property();
match p.inputs[i].kind {
InputKind::Var => self.var(i).map_debug(),
InputKind::Value => LocalVar(formatx!("{:?}", self.value(i))).boxed(),
InputKind::UiNode => LocalVar(Txt::from_static("<impl UiNode>")).boxed(),
InputKind::UiNodeList => LocalVar(Txt::from_static("<impl UiNodeList>")).boxed(),
InputKind::WidgetHandler => LocalVar(formatx!("<impl WidgetHandler<{}>>", p.inputs[i].display_ty_name())).boxed(),
}
}
/// Gets the property input current value as a debug text.
///
/// Note that you must call this in the widget context to get the correct value.
pub fn debug(&self, i: usize) -> Txt {
let p = self.property();
match p.inputs[i].kind {
InputKind::Var => formatx!("{:?}", self.var(i).get_any()),
InputKind::Value => formatx!("{:?}", self.value(i)),
InputKind::UiNode => Txt::from_static("<impl UiNode>"),
InputKind::UiNodeList => Txt::from_static("<impl UiNodeList>"),
InputKind::WidgetHandler => formatx!("<impl WidgetHandler<{}>>", p.inputs[i].display_ty_name()),
}
}
/// Call [`new`] with the same instance info and args, but with the `build_actions` and `build_actions_when_data`.
///
/// [`new`]: PropertyInfo::new
pub fn new_build(
&self,
build_actions: PropertyBuildActions,
build_actions_when_data: PropertyBuildActionsWhenData,
) -> Box<dyn PropertyArgs> {
let p = self.property();
let mut args: Vec<Box<dyn Any>> = Vec::with_capacity(p.inputs.len());
for (i, input) in p.inputs.iter().enumerate() {
match input.kind {
InputKind::Var => args.push(self.var(i).clone_any().double_boxed_any()),
InputKind::Value => args.push(self.value(i).clone_boxed().into_any()),
InputKind::UiNode => args.push(Box::new(self.ui_node(i).clone())),
InputKind::UiNodeList => args.push(Box::new(self.ui_node_list(i).clone())),
InputKind::WidgetHandler => args.push(self.widget_handler(i).clone_boxed().into_any()),
}
}
(p.new)(PropertyNewArgs {
args,
build_actions,
build_actions_when_data,
})
}
}
#[doc(hidden)]
pub fn panic_input(info: &PropertyInfo, i: usize, kind: InputKind) -> ! {
if i > info.inputs.len() {
panic!("index out of bounds, the input len is {}, but the index is {i}", info.inputs.len())
} else if info.inputs[i].kind != kind {
panic!(
"invalid input request `{:?}`, but `{}` is `{:?}`",
kind, info.inputs[i].name, info.inputs[i].kind
)
} else {
panic!("invalid input `{}`", info.inputs[i].name)
}
}
#[doc(hidden)]
pub fn var_to_args<T: VarValue>(var: impl IntoVar<T>) -> BoxedVar<T> {
var.into_var().boxed()
}
#[doc(hidden)]
pub fn value_to_args<T: VarValue>(value: impl IntoValue<T>) -> T {
value.into()
}
#[doc(hidden)]
pub fn ui_node_to_args(node: impl UiNode) -> ArcNode<BoxedUiNode> {
ArcNode::new(node.boxed())
}
#[doc(hidden)]
pub fn ui_node_list_to_args(node_list: impl UiNodeList) -> ArcNodeList<BoxedUiNodeList> {
ArcNodeList::new(node_list.boxed())
}
#[doc(hidden)]
pub fn widget_handler_to_args<A: Clone + 'static>(handler: impl WidgetHandler<A>) -> ArcWidgetHandler<A> {
ArcWidgetHandler::new(handler)
}
#[doc(hidden)]
pub fn iter_input_build_actions<'a>(
actions: &'a PropertyBuildActions,
data: &'a PropertyBuildActionsWhenData,
index: usize,
) -> impl Iterator<Item = (&'a dyn AnyPropertyBuildAction, &'a [Option<WhenBuildActionData>])> {
let mut actions = actions.iter();
let mut data = data.iter();
std::iter::from_fn(move || {
let action = &*actions.next()?[index];
let data = if let Some(data) = data.next() { &data[..] } else { &[None] };
Some((action, data))
})
}
fn apply_build_actions<'a, I: Any + Send>(
mut item: I,
mut actions: impl Iterator<Item = (&'a dyn AnyPropertyBuildAction, &'a [Option<WhenBuildActionData>])>,
) -> I {
if let Some((action, data)) = actions.next() {
let action = action
.as_any()
.downcast_ref::<PropertyBuildAction<I>>()
.expect("property build action type did not match expected var type");
item = action.build(PropertyBuildActionArgs {
input: item,
when_conditions_data: data,
});
}
item
}
#[doc(hidden)]
pub fn new_dyn_var<'a, T: VarValue>(
inputs: &mut std::vec::IntoIter<Box<dyn Any>>,
actions: impl Iterator<Item = (&'a dyn AnyPropertyBuildAction, &'a [Option<WhenBuildActionData>])>,
) -> BoxedVar<T> {
let item = inputs.next().expect("missing input");
let item = match item.downcast::<AnyWhenVarBuilder>() {
Ok(builder) => builder.build::<T>().expect("invalid when builder").boxed(),
Err(item) => *item.downcast::<BoxedVar<T>>().expect("input did not match expected var types"),
};
apply_build_actions(item, actions)
}
#[doc(hidden)]
pub fn new_dyn_ui_node<'a>(
inputs: &mut std::vec::IntoIter<Box<dyn Any>>,
actions: impl Iterator<Item = (&'a dyn AnyPropertyBuildAction, &'a [Option<WhenBuildActionData>])>,
) -> ArcNode<BoxedUiNode> {
let item = inputs.next().expect("missing input");
let item = match item.downcast::<WhenUiNodeBuilder>() {
Ok(builder) => ArcNode::new(builder.build().boxed()),
Err(item) => *item
.downcast::<ArcNode<BoxedUiNode>>()
.expect("input did not match expected UiNode types"),
};
apply_build_actions(item, actions)
}
#[doc(hidden)]
pub fn new_dyn_ui_node_list<'a>(
inputs: &mut std::vec::IntoIter<Box<dyn Any>>,
actions: impl Iterator<Item = (&'a dyn AnyPropertyBuildAction, &'a [Option<WhenBuildActionData>])>,
) -> ArcNodeList<BoxedUiNodeList> {
let item = inputs.next().expect("missing input");
let item = match item.downcast::<WhenUiNodeListBuilder>() {
Ok(builder) => ArcNodeList::new(builder.build().boxed()),
Err(item) => *item
.downcast::<ArcNodeList<BoxedUiNodeList>>()
.expect("input did not match expected UiNodeList types"),
};
apply_build_actions(item, actions)
}
#[doc(hidden)]
pub fn new_dyn_widget_handler<'a, A: Clone + 'static>(
inputs: &mut std::vec::IntoIter<Box<dyn Any>>,
actions: impl Iterator<Item = (&'a dyn AnyPropertyBuildAction, &'a [Option<WhenBuildActionData>])>,
) -> ArcWidgetHandler<A> {
let item = inputs.next().expect("missing input");
let item = match item.downcast::<AnyWhenArcWidgetHandlerBuilder>() {
Ok(builder) => builder.build(),
Err(item) => *item
.downcast::<ArcWidgetHandler<A>>()
.expect("input did not match expected WidgetHandler types"),
};
apply_build_actions(item, actions)
}
#[doc(hidden)]
pub fn new_dyn_other<'a, T: Any + Send>(
inputs: &mut std::vec::IntoIter<Box<dyn Any>>,
actions: impl Iterator<Item = (&'a dyn AnyPropertyBuildAction, &'a [Option<WhenBuildActionData>])>,
) -> T {
let item = *inputs
.next()
.expect("missing input")
.downcast::<T>()
.expect("input did not match expected var type");
apply_build_actions(item, actions)
}
/// Error value used in a reference to an [`UiNode`] property input is made in `when` expression.
///
/// Only variables and values can be referenced in `when` expression.
#[derive(Clone, PartialEq)]
pub struct UiNodeInWhenExprError;
impl fmt::Debug for UiNodeInWhenExprError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for UiNodeInWhenExprError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"cannot ref `impl UiNode` in when expression, only var and value properties allowed"
)
}
}
impl std::error::Error for UiNodeInWhenExprError {}
/// Error value used in a reference to an [`UiNodeList`] property input is made in `when` expression.
///
/// Only variables and values can be referenced in `when` expression.
#[derive(Clone, PartialEq)]
pub struct UiNodeListInWhenExprError;
impl fmt::Debug for UiNodeListInWhenExprError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for UiNodeListInWhenExprError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"cannot ref `impl UiNodeList` in when expression, only var and value properties allowed"
)
}
}
impl std::error::Error for UiNodeListInWhenExprError {}
/// Error value used in a reference to an [`UiNodeList`] property input is made in `when` expression.
///
/// Only variables and values can be referenced in `when` expression.
#[derive(Clone, PartialEq)]
pub struct WidgetHandlerInWhenExprError;
impl fmt::Debug for WidgetHandlerInWhenExprError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for WidgetHandlerInWhenExprError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"cannot ref `impl WidgetHandler<A>` in when expression, only var and value properties allowed"
)
}
}
impl std::error::Error for WidgetHandlerInWhenExprError {}
/*
WIDGET
*/
/// Value that indicates the override importance of a property instance, higher overrides lower.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub struct Importance(pub u32);
impl Importance {
/// Importance of default values defined in the widget declaration.
pub const WIDGET: Importance = Importance(1000);
/// Importance of values defined in the widget instantiation.
pub const INSTANCE: Importance = Importance(1000 * 10);
}
impl_from_and_into_var! {
fn from(imp: u32) -> Importance {
Importance(imp)
}
}
unique_id_32! {
/// Unique ID of a property implementation.
pub struct PropertyId;
}
zng_unique_id::impl_unique_id_bytemuck!(PropertyId);
impl fmt::Debug for PropertyId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("PropertyId").field(&self.get()).finish()
}
}
/// Unique identifier of a widget type.
///
/// Equality and hash is defined by the `type_id` only.
///
/// Widgets generated by `#[widget]` have an associated function that returns the type, `Foo::widget_type()`.
#[derive(Clone, Copy, Debug)]
pub struct WidgetType {
/// Widget type ID.
pub type_id: TypeId,
/// The widget public macro path.
pub path: &'static str,
/// Source code location.
pub location: SourceLocation,
}
impl WidgetType {
/// Get the last part of the path.
pub fn name(&self) -> &'static str {
self.path.rsplit_once(':').map(|(_, n)| n).unwrap_or(self.path)
}
}
impl PartialEq for WidgetType {
fn eq(&self, other: &Self) -> bool {
self.type_id == other.type_id
}
}
impl Eq for WidgetType {}
impl std::hash::Hash for WidgetType {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.type_id.hash(state);
}
}
/// Represents what member and how it was accessed in a [`WhenInput`].
#[derive(Clone, Copy, Debug)]
pub enum WhenInputMember {
/// Member was accessed by name.
Named(&'static str),
/// Member was accessed by index.
Index(usize),
}
/// Input var read in a `when` condition expression.
#[derive(Clone)]
pub struct WhenInput {
/// Property.
pub property: PropertyId,
/// What member and how it was accessed for this input.
pub member: WhenInputMember,
/// Input var.
pub var: WhenInputVar,
/// Constructor that generates the default property instance.
pub property_default: Option<fn() -> Box<dyn PropertyArgs>>,
}
impl fmt::Debug for WhenInput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WhenInput")
.field("property", &self.property)
.field("member", &self.member)
.finish_non_exhaustive()
}
}
struct WhenInputInitData<T: VarValue> {
data: Vec<(WeakContextInitHandle, BoxedVar<T>)>,
}
impl<T: VarValue> WhenInputInitData<T> {
const fn empty() -> Self {
Self { data: vec![] }
}
fn get(&mut self) -> BoxedVar<T> {
let current_id = WHEN_INPUT_CONTEXT_INIT_ID.get();
let current_id = current_id.downgrade();
let mut r = None;
self.data.retain(|(id, val)| {
let retain = id.is_alive();
if retain && id == ¤t_id {
r = Some(val.clone());
}
retain
});
match r {
Some(r) => r,
None => {
if !self.data.is_empty() {
tracing::error!("when input not inited");
let last = self.data.len() - 1;
self.data[last].1.clone()
} else {
panic!("when input not inited")
}
}
}
}
}
context_local! {
static WHEN_INPUT_CONTEXT_INIT_ID: ContextInitHandle = ContextInitHandle::new();
}
impl<T: VarValue> AnyWhenInputVarInner for WhenInputInitData<T> {
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn set(&mut self, handle: WeakContextInitHandle, var: BoxedAnyVar) {
let var = var
.double_boxed_any()
.downcast::<BoxedVar<T>>()
.expect("incorrect when input var type");
if let Some(i) = self.data.iter().position(|(i, _)| i == &handle) {
self.data[i].1 = var;
} else {
self.data.push((handle, var));
}
}
}
trait AnyWhenInputVarInner: Any + Send {
fn as_any(&mut self) -> &mut dyn Any;
fn set(&mut self, handle: WeakContextInitHandle, var: BoxedAnyVar);
}
/// Represents a [`WhenInput`] variable that can be rebound.
#[derive(Clone)]
pub struct WhenInputVar {
var: Arc<Mutex<dyn AnyWhenInputVarInner>>,
}
impl WhenInputVar {
/// New input setter and input var.
///
/// Trying to use the input var outside of the widget will panic.
///
/// [`can_use`]: Self::can_use
pub fn new<T: VarValue>() -> (Self, impl Var<T>) {
let arc: Arc<Mutex<dyn AnyWhenInputVarInner>> = Arc::new(Mutex::new(WhenInputInitData::<T>::empty()));
(
WhenInputVar { var: arc.clone() },
ContextualizedVar::new(move || arc.lock().as_any().downcast_mut::<WhenInputInitData<T>>().unwrap().get()),
)
}
fn set(&self, handle: WeakContextInitHandle, var: BoxedAnyVar) {
self.var.lock().set(handle, var);
}
}
type WhenBuildActionData = Arc<dyn Any + Send + Sync>;
type WhenBuildDefaultAction = Arc<dyn Fn() -> Vec<Box<dyn AnyPropertyBuildAction>> + Send + Sync>;
/// Data for a custom when build action associated with an [`WhenInfo`].
#[derive(Clone)]
pub struct WhenBuildAction {
/// Data for all inputs.
pub data: WhenBuildActionData,
/// Closure that generates the default build actions, used when the final widget has no build action instance.
///
/// The closure must generate an action that behaves like it is not present and then activates when the condition data activates.
///
/// If the final widget has no action and all when data for it has no default, the data is ignored.
pub default_action: Option<WhenBuildDefaultAction>,
}
impl WhenBuildAction {
/// New from strongly typed values.
pub fn new<D, F>(data: D, default_action: F) -> Self
where
D: Any + Send + Sync + 'static,
F: Fn() -> Vec<Box<dyn AnyPropertyBuildAction>> + Send + Sync + 'static,
{
Self {
data: Arc::new(data),
default_action: Some(Arc::new(default_action)),
}
}
/// New from data, is only used if the action is provided by another data or the widget builder.
pub fn new_no_default(data: impl Any + Send + Sync + 'static) -> Self {
Self {
data: Arc::new(data),
default_action: None,
}
}
}
/// Represents a `when` block in a widget.
#[derive(Clone)]
pub struct WhenInfo {
/// Properties referenced in the when condition expression.
///
/// They are type erased `BoxedVar<T>` instances that are *late-inited*, other variable references (`*#{var}`) are embedded in
/// the build expression and cannot be modified. Note that the [`state`] sticks to the first *late-inited* vars that it uses,
/// the variable only updates after clone, this cloning happens naturally when instantiating a widget more then once.
///
/// [`state`]: Self::state
pub inputs: Box<[WhenInput]>,
/// Output of the when expression.
///
/// Panics if used outside of the widget context.
pub state: BoxedVar<bool>,
/// Properties assigned in the `when` block, in the build widget they are joined with the default value and assigns
/// from other `when` blocks into a single property instance set to `when_var!` inputs.
pub assigns: Vec<Box<dyn PropertyArgs>>,
/// Data associated with the when condition in the build action.
pub build_action_data: Vec<((PropertyId, &'static str), WhenBuildAction)>,
/// The condition expression code.
pub expr: &'static str,
/// When declaration location.
pub location: SourceLocation,
}
impl fmt::Debug for WhenInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct DebugBuildActions<'a>(&'a WhenInfo);
impl fmt::Debug for DebugBuildActions<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.build_action_data.iter().map(|(k, _)| k)).finish()
}
}
f.debug_struct("WhenInfo")
.field("inputs", &self.inputs)
.field("state", &self.state.debug())
.field("assigns", &self.assigns)
.field("build_action_data", &DebugBuildActions(self))
.field("expr", &self.expr)
.finish()
}
}
impl Clone for Box<dyn PropertyArgs> {
fn clone(&self) -> Self {
PropertyArgs::clone_boxed(&**self)
}
}
impl fmt::Debug for &dyn PropertyArgs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("dyn PropertyArgs")
.field("property", &self.property())
.finish_non_exhaustive()
}
}
impl fmt::Debug for Box<dyn PropertyArgs> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("dyn PropertyArgs")
.field("property", &self.property())
.finish_non_exhaustive()
}
}
#[derive(Clone)]
struct WidgetItemPositioned {
position: NestPosition,
insert_idx: u32,
item: WidgetItem,
}
impl WidgetItemPositioned {
fn sort_key(&self) -> (NestPosition, u32) {
(self.position, self.insert_idx)
}
}
#[derive(Clone, Debug)]
struct WhenItemPositioned {
importance: Importance,
insert_idx: u32,
when: WhenInfo,
}
impl WhenItemPositioned {
fn sort_key(&self) -> (Importance, u32) {
(self.importance, self.insert_idx)
}
}
enum WidgetItem {
Property {
importance: Importance,
args: Box<dyn PropertyArgs>,
captured: bool,
},
Intrinsic {
name: &'static str,
new: Box<dyn FnOnce(BoxedUiNode) -> BoxedUiNode + Send + Sync>,
},
}
impl Clone for WidgetItem {
fn clone(&self) -> Self {
match self {
Self::Property {
importance,
args,
captured,
} => Self::Property {
importance: *importance,
captured: *captured,
args: args.clone(),
},
Self::Intrinsic { .. } => unreachable!("only WidgetBuilder clones, and it does not insert intrinsic"),
}
}
}
// [(PropertyId, "action-key") => (Importance, Vec<{action for each input}>)]
type PropertyBuildActionsMap = HashMap<(PropertyId, &'static str), (Importance, Vec<Box<dyn AnyPropertyBuildAction>>)>;
type PropertyBuildActionsVec = Vec<((PropertyId, &'static str), (Importance, Vec<Box<dyn AnyPropertyBuildAction>>))>;
/// Widget instance builder.
pub struct WidgetBuilder {
widget_type: WidgetType,
insert_idx: u32,
p: WidgetBuilderProperties,
unset: HashMap<PropertyId, Importance>,
whens: Vec<WhenItemPositioned>,
when_insert_idx: u32,
p_build_actions: PropertyBuildActionsMap,
p_build_actions_unset: HashMap<(PropertyId, &'static str), Importance>,
build_actions: Vec<Arc<Mutex<dyn FnMut(&mut WidgetBuilding) + Send>>>,
custom_build: Option<Arc<Mutex<dyn FnMut(WidgetBuilder) -> BoxedUiNode + Send>>>,
}
impl Clone for WidgetBuilder {
fn clone(&self) -> Self {
Self {
widget_type: self.widget_type,
p: WidgetBuilderProperties { items: self.items.clone() },
p_build_actions: self.p_build_actions.clone(),
insert_idx: self.insert_idx,
unset: self.unset.clone(),
p_build_actions_unset: self.p_build_actions_unset.clone(),
whens: self.whens.clone(),
when_insert_idx: self.when_insert_idx,
build_actions: self.build_actions.clone(),
custom_build: self.custom_build.clone(),
}
}
}
impl fmt::Debug for WidgetBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct PropertiesDebug<'a>(&'a WidgetBuilderProperties);
impl fmt::Debug for PropertiesDebug<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.0.properties()).finish()
}
}
f.debug_struct("WidgetBuilder")
.field("widget_type", &self.widget_type)
.field("properties", &PropertiesDebug(&self.p))
.field("unset", &self.unset)
.field("whens", &self.whens)
.field("build_actions.len", &self.build_actions.len())
.field("is_custom_build", &self.is_custom_build())
.finish()
}
}
impl WidgetBuilder {
/// New empty default.
pub fn new(widget: WidgetType) -> Self {
Self {
widget_type: widget,
p: WidgetBuilderProperties { items: Default::default() },
insert_idx: 0,
unset: Default::default(),
whens: Default::default(),
p_build_actions: Default::default(),
p_build_actions_unset: Default::default(),
when_insert_idx: 0,
build_actions: Default::default(),
custom_build: Default::default(),
}
}
/// The widget that started this builder.
pub fn widget_type(&self) -> WidgetType {
self.widget_type
}
/// Insert/override a property.
///
/// You can use the [`property_args!`] macro to collect args for a property.
pub fn push_property(&mut self, importance: Importance, args: Box<dyn PropertyArgs>) {
let pos = NestPosition::property(args.property().group);
self.push_property_positioned(importance, pos, args);
}
/// Insert property with custom nest position.
pub fn push_property_positioned(&mut self, importance: Importance, position: NestPosition, args: Box<dyn PropertyArgs>) {
self.push_property_positioned_impl(importance, position, args, false)
}
fn push_property_positioned_impl(
&mut self,
importance: Importance,
position: NestPosition,
args: Box<dyn PropertyArgs>,
captured: bool,
) {
let insert_idx = self.insert_idx;
self.insert_idx = insert_idx.wrapping_add(1);
let property_id = args.id();
if let Some(i) = self.p.property_index(property_id) {
match &self.p.items[i].item {
WidgetItem::Property { importance: imp, .. } => {
if *imp <= importance {
// override
self.p.items[i] = WidgetItemPositioned {
position,
insert_idx,
item: WidgetItem::Property {
importance,
args,
captured,
},
};
}
}
WidgetItem::Intrinsic { .. } => unreachable!(),
}
} else {
if let Some(imp) = self.unset.get(&property_id) {
if *imp >= importance {
return; // unset blocks.
}
}
self.p.items.push(WidgetItemPositioned {
position,
insert_idx,
item: WidgetItem::Property {
importance,
args,
captured,
},
});
}
}
/// Insert a `when` block.
pub fn push_when(&mut self, importance: Importance, mut when: WhenInfo) {
let insert_idx = self.when_insert_idx;
self.when_insert_idx = insert_idx.wrapping_add(1);
when.assigns.retain(|a| {
if let Some(imp) = self.unset.get(&a.id()) {
*imp < importance
} else {
true
}
});
if !when.assigns.is_empty() {
self.whens.push(WhenItemPositioned {
importance,
insert_idx,
when,
});
}
}
/// Insert a `name = unset!;` property.
pub fn push_unset(&mut self, importance: Importance, property_id: PropertyId) {
let check;
match self.unset.entry(property_id) {
hash_map::Entry::Occupied(mut e) => {
let i = e.get_mut();
check = *i < importance;
*i = importance;
}
hash_map::Entry::Vacant(e) => {
check = true;
e.insert(importance);
}
}
if check {
if let Some(i) = self.p.property_index(property_id) {
match &self.p.items[i].item {
WidgetItem::Property { importance: imp, .. } => {
if *imp <= importance {
self.p.items.swap_remove(i);
}
}
WidgetItem::Intrinsic { .. } => unreachable!(),
}
}
self.whens.retain_mut(|w| {
if w.importance <= importance {
w.when.assigns.retain(|a| a.id() != property_id);
!w.when.assigns.is_empty()
} else {
true
}
});
}
}
/// Add or override custom builder actions that are called to finalize the inputs for a property.
///
/// The `importance` overrides previous build action of the same name and property. The `input_actions` vec must
/// contain one action for each property input.
pub fn push_property_build_action(
&mut self,
property_id: PropertyId,
action_name: &'static str,
importance: Importance,
input_actions: Vec<Box<dyn AnyPropertyBuildAction>>,
) {
match self.p_build_actions.entry((property_id, action_name)) {
hash_map::Entry::Occupied(mut e) => {
if e.get().0 < importance {
e.insert((importance, input_actions));
}
}
hash_map::Entry::Vacant(e) => {
if let Some(imp) = self.p_build_actions_unset.get(&(property_id, action_name)) {
if *imp >= importance {
// blocked by unset
return;
}
}
e.insert((importance, input_actions));
}
}
}
/// Insert a [property build action] filter.
///
/// [property build action]: Self::push_property_build_action
pub fn push_unset_property_build_action(&mut self, property_id: PropertyId, action_name: &'static str, importance: Importance) {
let mut check = false;
match self.p_build_actions_unset.entry((property_id, action_name)) {
hash_map::Entry::Occupied(mut e) => {
if *e.get() < importance {
e.insert(importance);
check = true;
}
}
hash_map::Entry::Vacant(e) => {
e.insert(importance);
check = true;
}
}
if check {
self.p_build_actions.retain(|_, (imp, _)| *imp > importance);
}
}
/// Remove all registered property build actions.
pub fn clear_property_build_actions(&mut self) {
self.p_build_actions.clear();
}
/// Add an `action` closure that is called every time this builder or a clone of it builds a widget instance.
pub fn push_build_action(&mut self, action: impl FnMut(&mut WidgetBuilding) + Send + 'static) {
self.build_actions.push(Arc::new(Mutex::new(action)))
}
/// Remove all registered build actions.
pub fn clear_build_actions(&mut self) {
self.build_actions.clear();
}
/// Returns `true` if a custom build handler is registered.
pub fn is_custom_build(&self) -> bool {
self.custom_build.is_some()
}
/// Set a `build` closure to run instead of [`default_build`] when [`build`] is called.
///
/// Overrides the previous custom build, if any was set.
///
/// [`build`]: Self::build
/// [`default_build`]: Self::default_build
pub fn set_custom_build<R: UiNode>(&mut self, mut build: impl FnMut(WidgetBuilder) -> R + Send + 'static) {
self.custom_build = Some(Arc::new(Mutex::new(move |b| build(b).boxed())));
}
/// Remove the custom build handler, if any was set.
pub fn clear_custom_build(&mut self) {
self.custom_build = None;
}
/// Apply `other` over `self`.
///
/// All properties, unsets, whens, build actions and custom build of `other` are inserted in `self`,
/// override importance rules apply, `other` items only replace `self` items if they have the
/// same or greater importance.
///
/// Note that properties of the same position index from `other` are pushed after properties of the
/// same position in `self`, this means that fill properties of `other` will render *over* fill properties
/// of `self`.
pub fn extend(&mut self, other: WidgetBuilder) {
for (id, imp) in other.unset {
self.push_unset(imp, id);
}
for ((id, name), imp) in other.p_build_actions_unset {
self.push_unset_property_build_action(id, name, imp);
}
for WidgetItemPositioned { position, item, .. } in other.p.items {
match item {
WidgetItem::Property {
importance,
args,
captured,
} => {
self.push_property_positioned_impl(importance, position, args, captured);
}
WidgetItem::Intrinsic { .. } => unreachable!(),
}
}
for w in other.whens {
self.push_when(w.importance, w.when);
}
for ((id, name), (imp, action)) in other.p_build_actions {
self.push_property_build_action(id, name, imp, action);
}
for act in other.build_actions {
self.build_actions.push(act);
}
if let Some(c) = other.custom_build {
self.custom_build = Some(c);
}
}
/// If any property is present in the builder.
pub fn has_properties(&self) -> bool {
!self.p.items.is_empty()
}
/// If any unset filter is present in the builder.
pub fn has_unsets(&self) -> bool {
!self.unset.is_empty()
}
/// If any when block is present in the builder.
pub fn has_whens(&self) -> bool {
!self.whens.is_empty()
}
/// Move all `properties` to a new builder.
///
/// The properties are removed from `self`, any `when` assign is also moved, properties used in [`WhenInput`] that
/// affect the properties are cloned or moved into the new builder.
///
/// Note that properties can depend on others in the widget contextually, this is not preserved on split-off.
pub fn split_off(&mut self, properties: impl IntoIterator<Item = PropertyId>, out: &mut WidgetBuilder) {
self.split_off_impl(properties.into_iter().collect(), out)
}
fn split_off_impl(&mut self, properties: IdSet<PropertyId>, out: &mut WidgetBuilder) {
let mut found = 0;
// move properties
let mut i = 0;
while i < self.items.len() && found < properties.len() {
match &self.items[i].item {
WidgetItem::Property { args, .. } if properties.contains(&args.id()) => match self.items.swap_remove(i) {
WidgetItemPositioned {
position,
item: WidgetItem::Property { importance, args, .. },
..
} => {
out.push_property_positioned(importance, position, args);
found += 1;
}
_ => unreachable!(),
},
_ => {
i += 1;
continue;
}
}
}
i = 0;
while i < self.whens.len() {
// move when assigns
let mut ai = 0;
let mut moved_assigns = vec![];
while ai < self.whens[i].when.assigns.len() {
if properties.contains(&self.whens[i].when.assigns[ai].id()) {
let args = self.whens[i].when.assigns.remove(ai);
moved_assigns.push(args);
} else {
ai += 1;
}
}
if !moved_assigns.is_empty() {
let out_imp;
let out_when;
if self.whens[i].when.assigns.is_empty() {
// moved all assigns from block, move block
let WhenItemPositioned { importance, mut when, .. } = self.whens.remove(i);
when.assigns = moved_assigns;
out_imp = importance;
out_when = when;
} else {
// when block still used, clone block header for moved assigns.
let WhenItemPositioned { importance, when, .. } = &self.whens[i];
out_imp = *importance;
out_when = WhenInfo {
inputs: when.inputs.clone(),
state: when.state.clone(),
assigns: moved_assigns,
build_action_data: when.build_action_data.clone(),
expr: when.expr,
location: when.location,
};
i += 1;
};
// clone when input properties that are "manually" set.
for input in out_when.inputs.iter() {
if let Some(i) = self.property_index(input.property) {
match &self.items[i] {
WidgetItemPositioned {
position,
item: WidgetItem::Property { importance, args, .. },
..
} => {
out.push_property_positioned(*importance, *position, args.clone());
}
_ => unreachable!(),
}
}
}
out.push_when(out_imp, out_when);
} else {
i += 1;
}
}
// move unsets
for id in properties {
if let Some(imp) = self.unset.remove(&id) {
out.push_unset(imp, id);
}
}
}
/// Instantiate the widget.
///
/// If a custom build is set it is run, unless it is already running, otherwise the [`default_build`] is called.
///
/// [`default_build`]: Self::default_build
pub fn build(self) -> BoxedUiNode {
if let Some(custom) = self.custom_build.clone() {
match custom.try_lock() {
Some(mut c) => c(self),
None => self.default_build(),
}
} else {
self.default_build()
}
}
/// Instantiate the widget.
///
/// Runs all build actions, but ignores custom build.
pub fn default_build(self) -> BoxedUiNode {
#[cfg(feature = "inspector")]
let builder = self.clone();
let mut building = WidgetBuilding {
#[cfg(feature = "inspector")]
builder: Some(builder),
#[cfg(feature = "trace_widget")]
trace_widget: true,
#[cfg(feature = "trace_wgt_item")]
trace_wgt_item: true,
widget_type: self.widget_type,
p: self.p,
child: None,
};
let mut p_build_actions = self.p_build_actions.into_iter().collect();
let mut when_init_context_handle = None;
if !self.whens.is_empty() {
let handle = ContextInitHandle::new();
building.build_whens(self.whens, handle.downgrade(), &mut p_build_actions);
when_init_context_handle = Some(handle);
}
if !p_build_actions.is_empty() {
building.build_p_actions(p_build_actions);
}
for action in self.build_actions {
(action.lock())(&mut building);
}
building.build(when_init_context_handle)
}
}
impl ops::Deref for WidgetBuilder {
type Target = WidgetBuilderProperties;
fn deref(&self) -> &Self::Target {
&self.p
}
}
impl ops::DerefMut for WidgetBuilder {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.p
}
}
/// Represents a finalizing [`WidgetBuilder`].
///
/// Widgets can register a [build action] to get access to this, it provides an opportunity
/// to remove or capture the final properties of a widget, after they have all been resolved and `when` assigns generated.
/// Build actions can also define the child node, intrinsic nodes and a custom builder.
///
/// [build action]: WidgetBuilder::push_build_action
pub struct WidgetBuilding {
#[cfg(feature = "inspector")]
builder: Option<WidgetBuilder>,
#[cfg(feature = "trace_widget")]
trace_widget: bool,
#[cfg(feature = "trace_wgt_item")]
trace_wgt_item: bool,
widget_type: WidgetType,
p: WidgetBuilderProperties,
child: Option<BoxedUiNode>,
}
impl WidgetBuilding {
/// The widget that started this builder.
pub fn widget_type(&self) -> WidgetType {
self.widget_type
}
/// If an innermost node is defined.
///
/// If `false` by the end of build the [`FillUiNode`] is used as the innermost node.
pub fn has_child(&self) -> bool {
self.child.is_some()
}
/// Set/replace the innermost node of the widget.
pub fn set_child(&mut self, node: impl UiNode) {
self.child = Some(node.boxed());
}
/// Don't insert the inspector node and inspector metadata on build.
///
/// The inspector metadata is inserted by default when `feature="inspector"` is active.
#[cfg(feature = "inspector")]
pub fn disable_inspector(&mut self) {
self.builder = None;
}
/// Don't insert the widget trace node on build.
///
/// The trace node is inserted by default when `feature="trace_widget"` is active.
#[cfg(feature = "trace_widget")]
pub fn disable_trace_widget(&mut self) {
self.trace_widget = false;
}
/// Don't insert property/intrinsic trace nodes on build.
///
/// The trace nodes is inserted by default when `feature="trace_wgt_item"` is active.
#[cfg(feature = "trace_wgt_item")]
pub fn disable_trace_wgt_item(&mut self) {
self.trace_wgt_item = false;
}
/// Insert intrinsic node, that is a core functionality node of the widget that cannot be overridden.
///
/// The `name` is used for inspector/trace only, intrinsic nodes are not deduplicated.
pub fn push_intrinsic<I: UiNode>(
&mut self,
group: NestGroup,
name: &'static str,
intrinsic: impl FnOnce(BoxedUiNode) -> I + Send + Sync + 'static,
) {
self.push_intrinsic_positioned(NestPosition::intrinsic(group), name, intrinsic)
}
/// Insert intrinsic node with custom nest position.
///
/// The `name` is used for inspector/trace only, intrinsic nodes are not deduplicated.
pub fn push_intrinsic_positioned<I: UiNode>(
&mut self,
position: NestPosition,
name: &'static str,
intrinsic: impl FnOnce(BoxedUiNode) -> I + Send + Sync + 'static,
) {
self.items.push(WidgetItemPositioned {
position,
insert_idx: u32::MAX,
item: WidgetItem::Intrinsic {
name,
new: Box::new(move |n| intrinsic(n).boxed()),
},
});
}
/// Removes the property.
///
/// Note that if the property can already be captured by another widget component.
pub fn remove_property(&mut self, property_id: PropertyId) -> Option<BuilderProperty> {
if let Some(i) = self.property_index(property_id) {
match self.items.swap_remove(i) {
WidgetItemPositioned {
position,
item:
WidgetItem::Property {
importance,
args,
captured,
},
..
} => Some(BuilderProperty {
importance,
position,
args,
captured,
}),
_ => unreachable!(),
}
} else {
None
}
}
/// Flags the property as captured and returns a reference to it.
///
/// Note that captured properties are not instantiated in the final build, but they also are not removed like *unset*.
/// A property can be "captured" more then once, and if the `"inspector"` feature is enabled they can be inspected.
pub fn capture_property(&mut self, property_id: PropertyId) -> Option<BuilderPropertyRef> {
self.capture_property_impl(property_id)
}
/// Flags the property as captured and downcast the input var.
pub fn capture_var<T>(&mut self, property_id: PropertyId) -> Option<BoxedVar<T>>
where
T: VarValue,
{
let p = self.capture_property(property_id)?;
let var = p.args.downcast_var::<T>(0).clone();
Some(var)
}
/// Flags the property as captured and downcast the input var, or calls `or_else` to generate a fallback.
pub fn capture_var_or_else<T, F>(&mut self, property_id: PropertyId, or_else: impl FnOnce() -> F) -> BoxedVar<T>
where
T: VarValue,
F: IntoVar<T>,
{
match self.capture_var::<T>(property_id) {
Some(var) => var,
None => or_else().into_var().boxed(),
}
}
/// Flags the property as captured and downcast the input var, returns a new one with the default value.
pub fn capture_var_or_default<T>(&mut self, property_id: PropertyId) -> BoxedVar<T>
where
T: VarValue + Default,
{
self.capture_var_or_else(property_id, T::default)
}
/// Flags the property as captured and get the input node.
pub fn capture_ui_node(&mut self, property_id: PropertyId) -> Option<BoxedUiNode> {
let p = self.capture_property(property_id)?;
let node = p.args.ui_node(0).take_on_init().boxed();
Some(node)
}
/// Flags the property as captured and get the input node, or calls `or_else` to generate a fallback node.
pub fn capture_ui_node_or_else<F>(&mut self, property_id: PropertyId, or_else: impl FnOnce() -> F) -> BoxedUiNode
where
F: UiNode,
{
match self.capture_ui_node(property_id) {
Some(u) => u,
None => or_else().boxed(),
}
}
/// Flags the property as captured and get the input list.
pub fn capture_ui_node_list(&mut self, property_id: PropertyId) -> Option<BoxedUiNodeList> {
let p = self.capture_property(property_id)?;
let list = p.args.ui_node_list(0).take_on_init().boxed();
Some(list)
}
/// Flags the property as captured and get the input list, or calls `or_else` to generate a fallback list.
pub fn capture_ui_node_list_or_else<F>(&mut self, property_id: PropertyId, or_else: impl FnOnce() -> F) -> BoxedUiNodeList
where
F: UiNodeList,
{
match self.capture_ui_node_list(property_id) {
Some(u) => u,
None => or_else().boxed(),
}
}
/// Flags the property as captured and get the input list, or returns an empty list.
pub fn capture_ui_node_list_or_empty(&mut self, property_id: PropertyId) -> BoxedUiNodeList {
self.capture_ui_node_list_or_else(property_id, Vec::<BoxedUiNode>::new)
}
/// Flags the property as captured and downcast the input handler.
pub fn capture_widget_handler<A: Clone + 'static>(&mut self, property_id: PropertyId) -> Option<ArcWidgetHandler<A>> {
let p = self.capture_property(property_id)?;
let handler = p.args.downcast_handler::<A>(0).clone();
Some(handler)
}
fn build_whens(
&mut self,
mut whens: Vec<WhenItemPositioned>,
when_init_context_id: WeakContextInitHandle,
build_actions: &mut PropertyBuildActionsVec,
) {
whens.sort_unstable_by_key(|w| w.sort_key());
struct Input<'a> {
input: &'a WhenInput,
item_idx: usize,
}
let mut inputs = vec![];
struct Assign {
item_idx: usize,
builder: Vec<Box<dyn Any>>,
when_count: usize,
/// map of key:action set in the property, in at least one when, and value:Vec of data for each when in order and
/// Option of default action.
actions_data: HashMap<&'static str, (Vec<Option<WhenBuildActionData>>, Option<WhenBuildDefaultAction>)>,
}
let mut assigns = IdMap::default();
// rev so that the last when overrides others, the WhenVar returns the first true condition.
'when: for WhenItemPositioned { when, .. } in whens.iter().rev() {
// bind inputs.
let valid_inputs = inputs.len();
let valid_items = self.p.items.len();
for input in when.inputs.iter() {
if let Some(i) = self.property_index(input.property) {
inputs.push(Input { input, item_idx: i })
} else if let Some(default) = input.property_default {
let args = default();
self.p.items.push(WidgetItemPositioned {
position: NestPosition::property(args.property().group),
insert_idx: u32::MAX,
item: WidgetItem::Property {
importance: Importance::WIDGET,
args,
captured: false,
},
});
inputs.push(Input {
input,
item_idx: self.p.items.len() - 1,
});
} else {
inputs.truncate(valid_inputs);
self.p.items.truncate(valid_items);
continue 'when;
}
}
let mut any_assign = false;
// collect assigns.
'assign: for assign in when.assigns.iter() {
let id = assign.id();
let assign_info;
let i;
if let Some(idx) = self.property_index(id) {
assign_info = assign.property();
i = idx;
} else if let Some(default) = assign.property().default {
let args = default();
assign_info = args.property();
i = self.p.items.len();
self.p.items.push(WidgetItemPositioned {
position: NestPosition::property(args.property().group),
insert_idx: u32::MAX,
item: WidgetItem::Property {
importance: Importance::WIDGET,
args,
captured: false,
},
});
} else {
tracing::warn!(
"property `{}` ignored, it is only set in `when` block and has no default value",
assign.property().name
);
continue;
}
any_assign = true;
let default_args = match &self.items[i].item {
WidgetItem::Property { args, .. } => args,
WidgetItem::Intrinsic { .. } => unreachable!(),
};
let info = default_args.property();
for (default_info, assign_info) in info.inputs.iter().zip(assign_info.inputs.iter()) {
if default_info.ty != assign_info.ty {
// can happen with generic properties.
continue 'assign;
}
}
let entry = match assigns.entry(id) {
IdEntry::Occupied(e) => e.into_mut(),
IdEntry::Vacant(e) => e.insert(Assign {
item_idx: i,
builder: info
.inputs
.iter()
.enumerate()
.map(|(i, input)| match input.kind {
InputKind::Var => Box::new(AnyWhenVarBuilder::new_any(default_args.var(i).clone_any())) as _,
InputKind::UiNode => Box::new(WhenUiNodeBuilder::new(default_args.ui_node(i).take_on_init())) as _,
InputKind::UiNodeList => {
Box::new(WhenUiNodeListBuilder::new(default_args.ui_node_list(i).take_on_init())) as _
}
InputKind::WidgetHandler => {
Box::new(AnyWhenArcWidgetHandlerBuilder::new(default_args.widget_handler(i).clone_boxed())) as _
}
InputKind::Value => panic!("can only assign vars in when blocks"),
})
.collect(),
when_count: 0,
actions_data: Default::default(),
}),
};
entry.when_count += 1;
for (i, (input, entry)) in info.inputs.iter().zip(entry.builder.iter_mut()).enumerate() {
match input.kind {
InputKind::Var => {
let entry = entry.downcast_mut::<AnyWhenVarBuilder>().unwrap();
let value = assign.var(i).clone_any();
entry.push_any(when.state.clone(), value);
}
InputKind::UiNode => {
let entry = entry.downcast_mut::<WhenUiNodeBuilder>().unwrap();
let node = assign.ui_node(i).take_on_init();
entry.push(when.state.clone(), node);
}
InputKind::UiNodeList => {
let entry = entry.downcast_mut::<WhenUiNodeListBuilder>().unwrap();
let list = assign.ui_node_list(i).take_on_init();
entry.push(when.state.clone(), list);
}
InputKind::WidgetHandler => {
let entry = entry.downcast_mut::<AnyWhenArcWidgetHandlerBuilder>().unwrap();
let handler = assign.widget_handler(i).clone_boxed();
entry.push(when.state.clone(), handler);
}
InputKind::Value => panic!("cannot assign `Value` in when blocks"),
}
}
for ((property_id, action_key), action) in &when.build_action_data {
if *property_id == id {
match entry.actions_data.entry(*action_key) {
hash_map::Entry::Occupied(mut e) => {
let e = e.get_mut();
for _ in e.0.len()..(entry.when_count - 1) {
e.0.push(None);
}
e.0.push(Some(action.data.clone()));
if action.default_action.is_some() && e.1.is_none() {
e.1.clone_from(&action.default_action);
}
}
hash_map::Entry::Vacant(e) => {
let mut a = Vec::with_capacity(entry.when_count);
for _ in 0..(entry.when_count - 1) {
a.push(None);
}
a.push(Some(action.data.clone()));
e.insert((a, action.default_action.clone()));
}
}
}
}
}
if !any_assign {
inputs.truncate(valid_inputs);
self.p.items.truncate(valid_items);
}
}
for Input { input, item_idx } in inputs {
let args = match &self.items[item_idx].item {
WidgetItem::Property { args, .. } => args,
WidgetItem::Intrinsic { .. } => unreachable!(),
};
let info = args.property();
let member_i = match input.member {
WhenInputMember::Named(name) => info.input_idx(name).expect("when ref named input not found"),
WhenInputMember::Index(i) => i,
};
let actual = match info.inputs[member_i].kind {
InputKind::Var => args.var(member_i).clone_any(),
InputKind::Value => args.value(member_i).clone_boxed_var(),
_ => panic!("can only ref var or values in when expr"),
};
input.var.set(when_init_context_id.clone(), actual);
}
for (
_,
Assign {
item_idx,
builder,
when_count,
mut actions_data,
},
) in assigns
{
let args = match &mut self.items[item_idx].item {
WidgetItem::Property { args, .. } => args,
WidgetItem::Intrinsic { .. } => unreachable!(),
};
let mut actions = vec![];
let mut b_actions_data = vec![];
if !build_actions.is_empty() {
let p_id = args.id();
while let Some(i) = build_actions.iter().position(|((id, _), _)| *id == p_id) {
let ((_, action_key), (_, a)) = build_actions.swap_remove(i);
actions.push(a);
if let Some(data) = actions_data.remove(action_key) {
let mut data = data.clone();
for _ in data.0.len()..when_count {
data.0.push(None);
}
b_actions_data.push(data.0);
}
}
}
for (_, (mut data, default)) in actions_data {
if let Some(default) = default {
let action = default();
for _ in data.len()..when_count {
data.push(None);
}
actions.push(action);
b_actions_data.push(data);
}
}
*args = (args.property().new)(PropertyNewArgs {
args: builder,
build_actions: actions,
build_actions_when_data: b_actions_data,
});
}
}
fn build_p_actions(&mut self, mut build_actions: PropertyBuildActionsVec) {
while !build_actions.is_empty() {
let ((p_id, _), (_, a)) = build_actions.swap_remove(0);
let mut actions = vec![a];
while let Some(i) = build_actions.iter().position(|((id, _), _)| *id == p_id) {
let (_, (_, a)) = build_actions.swap_remove(i);
actions.push(a);
}
if let Some(i) = self.property_index(p_id) {
match &mut self.items[i].item {
WidgetItem::Property { args, .. } => *args = args.new_build(actions, vec![]),
WidgetItem::Intrinsic { .. } => unreachable!(),
}
}
}
}
fn build(mut self, when_init_context_handle: Option<ContextInitHandle>) -> BoxedUiNode {
// sort by group, index and insert index.
self.items.sort_unstable_by_key(|b| b.sort_key());
#[cfg(feature = "inspector")]
let mut inspector_items = Vec::with_capacity(self.p.items.len());
let mut node = self.child.take().unwrap_or_else(|| FillUiNode.boxed());
for WidgetItemPositioned { position, item, .. } in self.p.items.into_iter().rev() {
match item {
WidgetItem::Property { args, captured, .. } => {
if !captured {
#[cfg(debug_assertions)]
{
let p = args.property();
if p.capture {
tracing::error!(
"capture only property `{}` is not captured in `{}!`, it will have no effect",
p.name,
self.widget_type.name()
);
}
}
node = args.instantiate(node);
#[cfg(feature = "trace_wgt_item")]
if self.trace_wgt_item {
let name = args.property().name;
node = node.trace(move |mtd| crate::update::UpdatesTrace::property_span(name, mtd.mtd_name()));
}
}
#[cfg(feature = "inspector")]
{
if args.property().inputs.iter().any(|i| matches!(i.kind, InputKind::Var)) {
node = crate::widget::inspector::actualize_var_info(node, args.id()).boxed();
}
inspector_items.push(crate::widget::inspector::InstanceItem::Property { args, captured });
}
}
#[allow(unused_variables)] // depends on cfg
WidgetItem::Intrinsic { new, name } => {
node = new(node);
#[cfg(feature = "trace_wgt_item")]
if self.trace_wgt_item {
node = node.trace(move |mtd| crate::update::UpdatesTrace::intrinsic_span(name, mtd.mtd_name()));
}
#[cfg(feature = "inspector")]
inspector_items.push(crate::widget::inspector::InstanceItem::Intrinsic {
group: position.group,
name,
});
#[cfg(not(feature = "inspector"))]
let _ = position;
}
}
}
#[cfg(feature = "inspector")]
if let Some(builder) = self.builder {
node = crate::widget::inspector::insert_widget_builder_info(
node,
crate::widget::inspector::InspectorInfo {
builder,
items: inspector_items.into_boxed_slice(),
actual_vars: crate::widget::inspector::InspectorActualVars::default(),
},
)
.boxed();
}
#[cfg(feature = "trace_widget")]
if self.trace_widget {
let name = self.widget_type.name();
node = node
.trace(move |op| crate::update::UpdatesTrace::widget_span(crate::widget::WIDGET.id(), name, op.mtd_name()))
.boxed();
}
// ensure `when` reuse works, by forcing input refresh on (re)init.
node = with_new_context_init_id(node).boxed();
if let Some(handle) = when_init_context_handle {
// ensure shared/cloned when input expressions work.
let mut handle = Some(Arc::new(handle));
node = crate::widget::node::match_node(node, move |c, op| {
WHEN_INPUT_CONTEXT_INIT_ID.with_context(&mut handle, || c.op(op));
})
.boxed();
}
node
}
}
impl ops::Deref for WidgetBuilding {
type Target = WidgetBuilderProperties;
fn deref(&self) -> &Self::Target {
&self.p
}
}
impl ops::DerefMut for WidgetBuilding {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.p
}
}
/// Represents a property removed from [`WidgetBuilding`].
#[derive(Debug)]
pub struct BuilderProperty {
/// Property importance at the time of removal.
pub importance: Importance,
/// Property group and index at the time of removal.
pub position: NestPosition,
/// Property args.
pub args: Box<dyn PropertyArgs>,
/// If the property was *captured* before removal.
pub captured: bool,
}
/// Represents a property in [`WidgetBuilder`] or [`WidgetBuilding`].
#[derive(Debug)]
pub struct BuilderPropertyRef<'a> {
/// Property current importance.
pub importance: Importance,
/// Property current group and index.
pub position: NestPosition,
/// Property args.
pub args: &'a dyn PropertyArgs,
/// If the property was *captured*.
///
/// This can only be `true` in [`WidgetBuilding`].
pub captured: bool,
}
/// Represents a mutable reference to property in [`WidgetBuilder`] or [`WidgetBuilding`].
#[derive(Debug)]
pub struct BuilderPropertyMut<'a> {
/// Property current importance.
pub importance: &'a mut Importance,
/// Property current group and index.
pub position: &'a mut NestPosition,
/// Property args.
pub args: &'a mut Box<dyn PropertyArgs>,
/// If the property was *captured*.
///
/// This can only be `true` in [`WidgetBuilding`].
pub captured: &'a mut bool,
}
/// Direct property access in [`WidgetBuilder`] and [`WidgetBuilding`].
pub struct WidgetBuilderProperties {
items: Vec<WidgetItemPositioned>,
}
impl WidgetBuilderProperties {
/// Reference the property, if it is present.
pub fn property(&self, property_id: PropertyId) -> Option<BuilderPropertyRef> {
match self.property_index(property_id) {
Some(i) => match &self.items[i].item {
WidgetItem::Property {
importance,
args,
captured,
} => Some(BuilderPropertyRef {
importance: *importance,
position: self.items[i].position,
args: &**args,
captured: *captured,
}),
WidgetItem::Intrinsic { .. } => unreachable!(),
},
None => None,
}
}
/// Modify the property, if it is present.
pub fn property_mut(&mut self, property_id: PropertyId) -> Option<BuilderPropertyMut> {
match self.property_index(property_id) {
Some(i) => match &mut self.items[i] {
WidgetItemPositioned {
position,
item:
WidgetItem::Property {
importance,
args,
captured,
},
..
} => Some(BuilderPropertyMut {
importance,
position,
args,
captured,
}),
_ => unreachable!(),
},
None => None,
}
}
/// Iterate over the current properties.
///
/// The properties may not be sorted in the correct order if the builder has never built.
pub fn properties(&self) -> impl Iterator<Item = BuilderPropertyRef> {
self.items.iter().filter_map(|it| match &it.item {
WidgetItem::Intrinsic { .. } => None,
WidgetItem::Property {
importance,
args,
captured,
} => Some(BuilderPropertyRef {
importance: *importance,
position: it.position,
args: &**args,
captured: *captured,
}),
})
}
/// iterate over mutable references to the current properties.
pub fn properties_mut(&mut self) -> impl Iterator<Item = BuilderPropertyMut> {
self.items.iter_mut().filter_map(|it| match &mut it.item {
WidgetItem::Intrinsic { .. } => None,
WidgetItem::Property {
importance,
args,
captured,
} => Some(BuilderPropertyMut {
importance,
position: &mut it.position,
args,
captured,
}),
})
}
/// Flags the property as captured and downcast the input value.
///
/// Unlike other property kinds you can capture values in the [`WidgetBuilder`], note that the value may not
/// the final value, unless you are capturing on build.
///
/// Other property kinds can only be captured in [`WidgetBuilding`] as
/// their values strongly depend on the final `when` blocks that are only applied after building starts.
pub fn capture_value<T>(&mut self, property_id: PropertyId) -> Option<T>
where
T: VarValue,
{
let p = self.capture_property_impl(property_id)?;
let value = p.args.downcast_value::<T>(0).clone();
Some(value)
}
/// Flags the property as captured and downcast the input value, or calls `or_else` to generate the value.
pub fn capture_value_or_else<T>(&mut self, property_id: PropertyId, or_else: impl FnOnce() -> T) -> T
where
T: VarValue,
{
match self.capture_value(property_id) {
Some(v) => v,
None => or_else(),
}
}
/// Flags the property as captured and downcast the input value, or returns the default value.
pub fn capture_value_or_default<T>(&mut self, property_id: PropertyId) -> T
where
T: VarValue + Default,
{
self.capture_value_or_else(property_id, T::default)
}
fn capture_property_impl(&mut self, property_id: PropertyId) -> Option<BuilderPropertyRef> {
if let Some(i) = self.property_index(property_id) {
match &mut self.items[i] {
WidgetItemPositioned {
position,
item:
WidgetItem::Property {
importance,
args,
captured,
},
..
} => {
*captured = true;
Some(BuilderPropertyRef {
importance: *importance,
position: *position,
args: &**args,
captured: *captured,
})
}
_ => unreachable!(),
}
} else {
None
}
}
fn property_index(&self, property_id: PropertyId) -> Option<usize> {
self.items.iter().position(|it| match &it.item {
WidgetItem::Property { args, .. } => args.id() == property_id,
WidgetItem::Intrinsic { .. } => false,
})
}
}
/// Represents any [`PropertyBuildAction<I>`].
pub trait AnyPropertyBuildAction: crate::private::Sealed + Any + Send + Sync {
/// As any.
fn as_any(&self) -> &dyn Any;
/// Clone the action into a new box.
fn clone_boxed(&self) -> Box<dyn AnyPropertyBuildAction>;
}
/// Arguments for [`PropertyBuildAction<I>`].
pub struct PropertyBuildActionArgs<'a, I: Any + Send> {
/// The property input value.
pub input: I,
/// The [`WhenBuildAction::data`] for each when assign that affects `input` in the order that `input` was generated.
///
/// Items are `None` for when assigns that do not have associated build action data.
pub when_conditions_data: &'a [Option<WhenBuildActionData>],
}
/// Represents a custom build action targeting a property input that is applied after `when` is build.
///
/// The type `I` depends on the input kind:
///
/// The expected types for each [`InputKind`] are:
///
/// | Kind | Expected Type
/// |---------------------|-------------------------------------------------
/// | [`Var`] | `BoxedVar<T>`
/// | [`Value`] | `T`
/// | [`UiNode`] | `ArcNode<BoxedUiNode>`
/// | [`UiNodeList`] | `ArcNodeList<BoxedUiNodeList>`
/// | [`WidgetHandler`] | `ArcWidgetHandler<A>`
///
/// [`Var`]: InputKind::Var
/// [`Value`]: InputKind::Value
/// [`UiNode`]: InputKind::UiNode
/// [`UiNodeList`]: InputKind::UiNodeList
/// [`WidgetHandler`]: InputKind::WidgetHandler
pub struct PropertyBuildAction<I: Any + Send>(Arc<Mutex<dyn FnMut(PropertyBuildActionArgs<I>) -> I + Send>>);
impl<I: Any + Send> crate::private::Sealed for PropertyBuildAction<I> {}
impl<I: Any + Send> Clone for PropertyBuildAction<I> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<I: Any + Send> AnyPropertyBuildAction for PropertyBuildAction<I> {
fn clone_boxed(&self) -> Box<dyn AnyPropertyBuildAction> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl<I: Any + Send> PropertyBuildAction<I> {
/// New build action.
pub fn new(build: impl FnMut(PropertyBuildActionArgs<I>) -> I + Send + 'static) -> Self {
Self(Arc::new(Mutex::new(build)))
}
/// New build action that just pass the input.
pub fn no_op() -> Self {
Self::new(|i| i.input)
}
/// Run the build action on a input.
pub fn build(&self, args: PropertyBuildActionArgs<I>) -> I {
(self.0.lock())(args)
}
}
impl Clone for Box<dyn AnyPropertyBuildAction> {
fn clone(&self) -> Self {
self.clone_boxed()
}
}
/// Represents the strong types of each input of a property.
///
/// # Examples
///
/// The example uses [`property_input_types!`] to collect the types and compares it to a manually generated types. Note
/// that the type is a tuple even if there is only one input.
///
/// ```
/// # use zng_app::{*, widget::{node::*, builder::*, property}};
/// # use zng_var::*;
/// # use std::any::Any;
/// #[property(CONTEXT)]
/// pub fn foo(child: impl UiNode, bar: impl IntoVar<bool>) -> impl UiNode {
/// # child
/// }
///
/// # fn main() {
/// assert_eq!(
/// property_input_types!(foo).type_id(),
/// PropertyInputTypes::<(BoxedVar<bool>,)>::unit().type_id(),
/// );
/// # }
/// ```
///
/// You can use the collected types in advanced code generation, such as attribute proc-macros targeting property assigns in widgets.
/// The next example demonstrates a trait that uses auto-deref to convert a trait bound to a `bool`:
///
/// ```
/// # use zng_app::{*, widget::{node::*, builder::*, property}};
/// # use zng_var::*;
/// #[property(CONTEXT)]
/// pub fn foo(child: impl UiNode, bar: impl IntoVar<bool>) -> impl UiNode {
/// # child
/// }
///
/// trait SingleBoolVar {
/// fn is_single_bool_var(self) -> bool;
/// }
///
/// // match
/// impl<'a, V: Var<bool>> SingleBoolVar for &'a PropertyInputTypes<(V,)> {
/// fn is_single_bool_var(self) -> bool {
/// true
/// }
/// }
///
/// // fallback impl
/// impl<T: Send + 'static> SingleBoolVar for PropertyInputTypes<T> {
/// fn is_single_bool_var(self) -> bool {
/// false
/// }
/// }
///
/// # fn main() {
/// assert!((&property_input_types!(foo)).is_single_bool_var());
/// # }
/// ```
///
/// Learn more about how this trick works and limitations
/// [here](https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md).
pub struct PropertyInputTypes<Tuple>(std::marker::PhantomData<Tuple>);
impl<Tuple> PropertyInputTypes<Tuple> {
/// Unit value.
pub const fn unit() -> Self {
Self(std::marker::PhantomData)
}
}
impl<Tuple> Clone for PropertyInputTypes<Tuple> {
fn clone(&self) -> Self {
*self
}
}
impl<Tuple> Copy for PropertyInputTypes<Tuple> {}
// SAFETY: PhantomData
unsafe impl<Tuple> Send for PropertyInputTypes<Tuple> {}
unsafe impl<Tuple> Sync for PropertyInputTypes<Tuple> {}