1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2017-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "ShaderViewer.h"
#include <QComboBox>
#include <QFontDatabase>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QListWidget>
#include <QMenu>
#include <QMouseEvent>
#include <QShortcut>
#include <QToolTip>
#include "3rdparty/scintilla/include/SciLexer.h"
#include "3rdparty/scintilla/include/qt/ScintillaEdit.h"
#include "3rdparty/toolwindowmanager/ToolWindowManager.h"
#include "3rdparty/toolwindowmanager/ToolWindowManagerArea.h"
#include "Code/ScintillaSyntax.h"
#include "Widgets/FindReplace.h"
#include "ui_ShaderViewer.h"
namespace
{
struct VariableTag
{
VariableTag() {}
VariableTag(VariableCategory c, int i, int a = 0) : cat(c), idx(i), arrayIdx(a) {}
VariableCategory cat = VariableCategory::Unknown;
int idx = 0;
int arrayIdx = 0;
bool operator==(const VariableTag &o)
{
return cat == o.cat && idx == o.idx && arrayIdx == o.arrayIdx;
}
};
};
Q_DECLARE_METATYPE(VariableTag);
ShaderViewer::ShaderViewer(ICaptureContext &ctx, QWidget *parent)
: QFrame(parent), ui(new Ui::ShaderViewer), m_Ctx(ctx)
{
ui->setupUi(this);
ui->constants->setFont(Formatter::PreferredFont());
ui->registers->setFont(Formatter::PreferredFont());
ui->locals->setFont(Formatter::PreferredFont());
ui->watch->setFont(Formatter::PreferredFont());
ui->inputSig->setFont(Formatter::PreferredFont());
ui->outputSig->setFont(Formatter::PreferredFont());
ui->callstack->setFont(Formatter::PreferredFont());
// we create this up front so its state stays persistent as much as possible.
m_FindReplace = new FindReplace(this);
m_FindResults = MakeEditor(lit("findresults"), QString(), SCLEX_NULL);
m_FindResults->setReadOnly(true);
m_FindResults->setWindowTitle(lit("Find Results"));
// remove margins
m_FindResults->setMarginWidthN(0, 0);
m_FindResults->setMarginWidthN(1, 0);
m_FindResults->setMarginWidthN(2, 0);
QObject::connect(m_FindReplace, &FindReplace::performFind, this, &ShaderViewer::performFind);
QObject::connect(m_FindReplace, &FindReplace::performFindAll, this, &ShaderViewer::performFindAll);
QObject::connect(m_FindReplace, &FindReplace::performReplace, this, &ShaderViewer::performReplace);
QObject::connect(m_FindReplace, &FindReplace::performReplaceAll, this,
&ShaderViewer::performReplaceAll);
ui->docking->addToolWindow(m_FindReplace, ToolWindowManager::NoArea);
ui->docking->setToolWindowProperties(m_FindReplace, ToolWindowManager::HideOnClose);
ui->docking->addToolWindow(m_FindResults, ToolWindowManager::NoArea);
ui->docking->setToolWindowProperties(m_FindResults, ToolWindowManager::HideOnClose);
{
m_DisassemblyView =
MakeEditor(lit("scintillaDisassem"), QString(),
m_Ctx.APIProps().pipelineType == GraphicsAPI::Vulkan ? SCLEX_GLSL : SCLEX_HLSL);
m_DisassemblyView->setReadOnly(true);
QObject::connect(m_DisassemblyView, &ScintillaEdit::keyPressed, this,
&ShaderViewer::readonly_keyPressed);
m_Scintillas.push_back(m_DisassemblyView);
m_DisassemblyFrame = new QWidget(this);
m_DisassemblyFrame->setWindowTitle(tr("Disassembly"));
m_DisassemblyToolbar = new QFrame(this);
m_DisassemblyToolbar->setFrameShape(QFrame::Panel);
m_DisassemblyToolbar->setFrameShadow(QFrame::Raised);
QHBoxLayout *toolbarlayout = new QHBoxLayout(m_DisassemblyToolbar);
toolbarlayout->setSpacing(2);
toolbarlayout->setContentsMargins(3, 3, 3, 3);
m_DisassemblyType = new QComboBox(m_DisassemblyToolbar);
m_DisassemblyType->setMaxVisibleItems(12);
m_DisassemblyType->setSizeAdjustPolicy(QComboBox::AdjustToContents);
toolbarlayout->addWidget(new QLabel(tr("Disassembly type:"), m_DisassemblyToolbar));
toolbarlayout->addWidget(m_DisassemblyType);
toolbarlayout->addItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));
QVBoxLayout *framelayout = new QVBoxLayout(m_DisassemblyFrame);
framelayout->setSpacing(0);
framelayout->setMargin(0);
framelayout->addWidget(m_DisassemblyToolbar);
framelayout->addWidget(m_DisassemblyView);
ui->docking->addToolWindow(m_DisassemblyFrame, ToolWindowManager::EmptySpace);
ui->docking->setToolWindowProperties(m_DisassemblyFrame,
ToolWindowManager::HideCloseButton |
ToolWindowManager::DisallowFloatWindow |
ToolWindowManager::AlwaysDisplayFullTabs);
}
ui->docking->setAllowFloatingWindow(false);
{
QMenu *snippetsMenu = new QMenu(this);
QAction *dim = new QAction(tr("Texture Dimensions Global"), this);
QAction *mip = new QAction(tr("Selected Mip Global"), this);
QAction *slice = new QAction(tr("Seleted Array Slice / Cubemap Face Global"), this);
QAction *sample = new QAction(tr("Selected Sample Global"), this);
QAction *type = new QAction(tr("Texture Type Global"), this);
QAction *samplers = new QAction(tr("Point && Linear Samplers"), this);
QAction *resources = new QAction(tr("Texture Resources"), this);
snippetsMenu->addAction(dim);
snippetsMenu->addAction(mip);
snippetsMenu->addAction(slice);
snippetsMenu->addAction(sample);
snippetsMenu->addAction(type);
snippetsMenu->addSeparator();
snippetsMenu->addAction(samplers);
snippetsMenu->addAction(resources);
QObject::connect(dim, &QAction::triggered, this, &ShaderViewer::snippet_textureDimensions);
QObject::connect(mip, &QAction::triggered, this, &ShaderViewer::snippet_selectedMip);
QObject::connect(slice, &QAction::triggered, this, &ShaderViewer::snippet_selectedSlice);
QObject::connect(sample, &QAction::triggered, this, &ShaderViewer::snippet_selectedSample);
QObject::connect(type, &QAction::triggered, this, &ShaderViewer::snippet_selectedType);
QObject::connect(samplers, &QAction::triggered, this, &ShaderViewer::snippet_samplers);
QObject::connect(resources, &QAction::triggered, this, &ShaderViewer::snippet_resources);
ui->snippets->setMenu(snippetsMenu);
}
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setSpacing(3);
layout->setContentsMargins(3, 3, 3, 3);
layout->addWidget(ui->toolbar);
layout->addWidget(ui->docking);
m_Ctx.AddCaptureViewer(this);
}
void ShaderViewer::editShader(bool customShader, ShaderStage stage, const QString &entryPoint,
const rdcstrpairs &files, ShaderEncoding shaderEncoding,
ShaderCompileFlags flags)
{
m_Scintillas.removeOne(m_DisassemblyView);
ui->docking->removeToolWindow(m_DisassemblyFrame);
m_DisassemblyView = NULL;
m_Stage = stage;
m_Flags = flags;
// set up compilation parameters
QStringList strs;
strs.clear();
for(ShaderEncoding i : values<ShaderEncoding>())
strs << ToQStr(i);
ui->encoding->addItems(strs);
ui->encoding->setCurrentIndex((int)shaderEncoding);
ui->entryFunc->setText(entryPoint);
PopulateCompileTools();
QObject::connect(ui->encoding, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged),
[this](int) { PopulateCompileTools(); });
QObject::connect(ui->compileTool, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged),
[this](int) { PopulateCompileToolParameters(); });
// if it's a custom shader, hide the group entirely (don't allow customisation of compile
// parameters). We can still use it to store the parameters passed in. When visible we collapse it
// by default.
if(customShader)
ui->compilationGroup->hide();
// hide debugging windows
ui->watch->hide();
ui->registers->hide();
ui->constants->hide();
ui->callstack->hide();
ui->locals->hide();
ui->snippets->setVisible(customShader);
// hide debugging toolbar buttons
ui->debugSep->hide();
ui->runBack->hide();
ui->run->hide();
ui->stepBack->hide();
ui->stepNext->hide();
ui->runToCursor->hide();
ui->runToSample->hide();
ui->runToNaNOrInf->hide();
ui->regFormatSep->hide();
ui->intView->hide();
ui->floatView->hide();
ui->debugToggleSep->hide();
ui->debugToggle->hide();
// hide signatures
ui->inputSig->hide();
ui->outputSig->hide();
QString title;
QWidget *sel = NULL;
for(const rdcstrpair &kv : files)
{
QString name = QFileInfo(kv.first).fileName();
QString text = kv.second;
ScintillaEdit *scintilla = AddFileScintilla(name, text);
scintilla->setReadOnly(false);
QObject::connect(scintilla, &ScintillaEdit::keyPressed, this, &ShaderViewer::editable_keyPressed);
QObject::connect(scintilla, &ScintillaEdit::modified, [this](int type, int, int, int,
const QByteArray &, int, int, int) {
if(type & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT | SC_MOD_BEFOREINSERT | SC_MOD_BEFOREDELETE))
m_FindState = FindState();
});
m_Ctx.GetMainWindow()->RegisterShortcut(QKeySequence(QKeySequence::Refresh).toString(), this,
[this](QWidget *) { on_refresh_clicked(); });
ui->refresh->setToolTip(ui->refresh->toolTip() +
lit(" (%1)").arg(QKeySequence(QKeySequence::Refresh).toString()));
QWidget *w = (QWidget *)scintilla;
w->setProperty("filename", kv.first);
if(text.contains(entryPoint))
sel = scintilla;
if(sel == scintilla || title.isEmpty())
title = tr("%1 - Edit (%2)").arg(entryPoint).arg(name);
}
if(sel != NULL)
ToolWindowManager::raiseToolWindow(sel);
setWindowTitle(title);
if(files.count() > 2)
addFileList();
m_Errors = MakeEditor(lit("errors"), QString(), SCLEX_NULL);
m_Errors->setReadOnly(true);
m_Errors->setWindowTitle(lit("Errors"));
// remove margins
m_Errors->setMarginWidthN(0, 0);
m_Errors->setMarginWidthN(1, 0);
m_Errors->setMarginWidthN(2, 0);
QObject::connect(m_Errors, &ScintillaEdit::keyPressed, this, &ShaderViewer::readonly_keyPressed);
ui->docking->addToolWindow(
m_Errors, ToolWindowManager::AreaReference(ToolWindowManager::BottomOf,
ui->docking->areaOf(m_Scintillas.front()), 0.2f));
ui->docking->setToolWindowProperties(
m_Errors, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
if(!customShader)
{
ui->compilationGroup->setWindowTitle(tr("Compilation Settings"));
ui->docking->addToolWindow(ui->compilationGroup,
ToolWindowManager::AreaReference(
ToolWindowManager::LeftOf, ui->docking->areaOf(m_Errors), 0.5f));
ui->docking->setToolWindowProperties(
ui->compilationGroup,
ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
}
}
void ShaderViewer::debugShader(const ShaderBindpointMapping *bind, const ShaderReflection *shader,
ResourceId pipeline, ShaderDebugTrace *trace,
const QString &debugContext)
{
m_Mapping = bind;
m_ShaderDetails = shader;
m_Pipeline = pipeline;
m_Trace = trace;
m_Stage = ShaderStage::Vertex;
m_DebugContext = debugContext;
// no recompilation happening, hide that group
ui->compilationGroup->hide();
// no replacing allowed, stay in find mode
m_FindReplace->allowUserModeChange(false);
if(!m_ShaderDetails || !m_Mapping)
m_Trace = NULL;
if(m_ShaderDetails)
{
m_Stage = m_ShaderDetails->stage;
m_Ctx.Replay().AsyncInvoke([this](IReplayController *r) {
rdcarray<rdcstr> targets = r->GetDisassemblyTargets();
rdcstr disasm = r->DisassembleShader(m_Pipeline, m_ShaderDetails, "");
GUIInvoke::call(this, [this, targets, disasm]() {
QStringList targetNames;
for(int i = 0; i < targets.count(); i++)
{
QString target = targets[i];
targetNames << QString(targets[i]);
if(i == 0)
{
// add any custom decompiling tools we have after the first one
for(const ShaderProcessingTool &d : m_Ctx.Config().ShaderProcessors)
{
if(d.input == m_ShaderDetails->encoding)
targetNames << targetName(d);
}
}
}
m_DisassemblyType->clear();
m_DisassemblyType->addItems(targetNames);
m_DisassemblyType->setCurrentIndex(0);
QObject::connect(m_DisassemblyType, OverloadedSlot<int>::of(&QComboBox::currentIndexChanged),
this, &ShaderViewer::disassemble_typeChanged);
// read-only applies to us too!
m_DisassemblyView->setReadOnly(false);
m_DisassemblyView->setText(disasm.c_str());
m_DisassemblyView->setReadOnly(true);
bool preferSourceDebug = false;
for(const ShaderCompileFlag &flag : m_ShaderDetails->debugInfo.compileFlags.flags)
{
if(flag.name == "preferSourceDebug")
{
preferSourceDebug = true;
break;
}
}
updateDebugging();
// we do updateDebugging() again because the first call finds the scintilla for the current
// source file, the second time jumps to it.
if(preferSourceDebug)
{
gotoSourceDebugging();
updateDebugging();
}
});
});
}
updateWindowTitle();
// we always want to highlight words/registers
QObject::connect(m_DisassemblyView, &ScintillaEdit::buttonReleased, this,
&ShaderViewer::disassembly_buttonReleased);
if(m_Trace)
{
if(m_Stage == ShaderStage::Vertex)
{
ANALYTIC_SET(ShaderDebug.Vertex, true);
}
else if(m_Stage == ShaderStage::Pixel)
{
ANALYTIC_SET(ShaderDebug.Pixel, true);
}
else if(m_Stage == ShaderStage::Compute)
{
ANALYTIC_SET(ShaderDebug.Compute, true);
}
m_DisassemblyFrame->layout()->removeWidget(m_DisassemblyToolbar);
}
if(m_ShaderDetails && !m_ShaderDetails->debugInfo.files.isEmpty())
{
if(m_Trace)
setWindowTitle(QFormatStr("Debug %1() - %2").arg(m_ShaderDetails->entryPoint).arg(debugContext));
else
setWindowTitle(m_ShaderDetails->entryPoint);
// add all the files, skipping any that have empty contents. We push a NULL in that case so the
// indices still match up with what the debug info expects. Debug info *shouldn't* point us at
// an empty file, but if it does we'll just bail out when we see NULL
m_FileScintillas.reserve(m_ShaderDetails->debugInfo.files.count());
QWidget *sel = NULL;
for(const ShaderSourceFile &f : m_ShaderDetails->debugInfo.files)
{
if(f.contents.isEmpty())
{
m_FileScintillas.push_back(NULL);
continue;
}
QString name = QFileInfo(f.filename).fileName();
QString text = f.contents;
ScintillaEdit *scintilla = AddFileScintilla(name, text);
if(sel == NULL)
sel = scintilla;
m_FileScintillas.push_back(scintilla);
}
if(m_Trace || sel == NULL)
sel = m_DisassemblyFrame;
if(m_ShaderDetails->debugInfo.files.size() > 2)
addFileList();
ToolWindowManager::raiseToolWindow(sel);
}
// hide edit buttons
ui->editSep->hide();
ui->refresh->hide();
ui->snippets->hide();
if(m_Trace)
{
// hide signatures
ui->inputSig->hide();
ui->outputSig->hide();
if(m_ShaderDetails->debugInfo.files.isEmpty())
{
ui->debugToggle->setEnabled(false);
ui->debugToggle->setText(tr("HLSL Unavailable"));
}
ui->registers->setColumns({tr("Name"), tr("Type"), tr("Value")});
ui->registers->header()->setSectionResizeMode(0, QHeaderView::Interactive);
ui->registers->header()->setSectionResizeMode(1, QHeaderView::Interactive);
ui->registers->header()->setSectionResizeMode(2, QHeaderView::Stretch);
ui->locals->setColumns({tr("Name"), tr("Register(s)"), tr("Type"), tr("Value")});
ui->locals->header()->setSectionResizeMode(0, QHeaderView::Interactive);
ui->locals->header()->setSectionResizeMode(1, QHeaderView::Interactive);
ui->locals->header()->setSectionResizeMode(2, QHeaderView::Interactive);
ui->locals->header()->setSectionResizeMode(3, QHeaderView::Stretch);
ui->constants->setColumns({tr("Name"), tr("Type"), tr("Value")});
ui->constants->header()->setSectionResizeMode(0, QHeaderView::Interactive);
ui->constants->header()->setSectionResizeMode(1, QHeaderView::Interactive);
ui->constants->header()->setSectionResizeMode(2, QHeaderView::Stretch);
ui->registers->setTooltipElidedItems(false);
ui->constants->setTooltipElidedItems(false);
ui->watch->setWindowTitle(tr("Watch"));
ui->docking->addToolWindow(
ui->watch, ToolWindowManager::AreaReference(ToolWindowManager::BottomOf,
ui->docking->areaOf(m_DisassemblyFrame), 0.25f));
ui->docking->setToolWindowProperties(
ui->watch, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
ui->registers->setWindowTitle(tr("Registers"));
ui->docking->addToolWindow(
ui->registers,
ToolWindowManager::AreaReference(ToolWindowManager::AddTo, ui->docking->areaOf(ui->watch)));
ui->docking->setToolWindowProperties(
ui->registers, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
ui->constants->setWindowTitle(tr("Constants && Resources"));
ui->docking->addToolWindow(
ui->constants, ToolWindowManager::AreaReference(ToolWindowManager::LeftOf,
ui->docking->areaOf(ui->registers), 0.5f));
ui->docking->setToolWindowProperties(
ui->constants, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
ui->callstack->setWindowTitle(tr("Callstack"));
ui->docking->addToolWindow(
ui->callstack, ToolWindowManager::AreaReference(ToolWindowManager::RightOf,
ui->docking->areaOf(ui->registers), 0.2f));
ui->docking->setToolWindowProperties(
ui->callstack, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
if(m_Trace->hasLocals)
{
ui->locals->setWindowTitle(tr("Local Variables"));
ui->docking->addToolWindow(
ui->locals, ToolWindowManager::AreaReference(ToolWindowManager::AddTo,
ui->docking->areaOf(ui->registers)));
ui->docking->setToolWindowProperties(
ui->locals, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
}
else
{
ui->locals->hide();
}
m_Line2Inst.resize(m_ShaderDetails->debugInfo.files.count());
for(size_t inst = 0; inst < m_Trace->lineInfo.size(); inst++)
{
const LineColumnInfo &line = m_Trace->lineInfo[inst];
if(line.fileIndex < 0 || line.fileIndex >= m_Line2Inst.count())
continue;
for(uint32_t lineNum = line.lineStart; lineNum <= line.lineEnd; lineNum++)
m_Line2Inst[line.fileIndex][lineNum] = inst;
}
QObject::connect(ui->stepBack, &QToolButton::clicked, this, &ShaderViewer::stepBack);
QObject::connect(ui->stepNext, &QToolButton::clicked, this, &ShaderViewer::stepNext);
QObject::connect(ui->runBack, &QToolButton::clicked, this, &ShaderViewer::runBack);
QObject::connect(ui->run, &QToolButton::clicked, this, &ShaderViewer::run);
QObject::connect(ui->runToCursor, &QToolButton::clicked, this, &ShaderViewer::runToCursor);
QObject::connect(ui->runToSample, &QToolButton::clicked, this, &ShaderViewer::runToSample);
QObject::connect(ui->runToNaNOrInf, &QToolButton::clicked, this, &ShaderViewer::runToNanOrInf);
for(ScintillaEdit *edit : m_Scintillas)
{
edit->setMarginWidthN(1, 20.0 * devicePixelRatioF());
// display current line in margin 2, distinct from breakpoint in margin 1
sptr_t markMask = (1 << CURRENT_MARKER) | (1 << FINISHED_MARKER);
edit->setMarginMaskN(1, edit->marginMaskN(1) & ~markMask);
edit->setMarginMaskN(2, edit->marginMaskN(2) | markMask);
// suppress the built-in context menu and hook up our own
edit->usePopUp(SC_POPUP_NEVER);
edit->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(edit, &ScintillaEdit::customContextMenuRequested, this,
&ShaderViewer::debug_contextMenu);
edit->setMouseDwellTime(500);
QObject::connect(edit, &ScintillaEdit::dwellStart, this, &ShaderViewer::disasm_tooltipShow);
QObject::connect(edit, &ScintillaEdit::dwellEnd, this, &ShaderViewer::disasm_tooltipHide);
}
// register the shortcuts globally for this shader viewer so it works regardless of the active
// scintilla
QObject::connect(new QShortcut(QKeySequence(Qt::Key_F10), this), &QShortcut::activated, this,
&ShaderViewer::stepNext);
QObject::connect(new QShortcut(QKeySequence(Qt::Key_F10 | Qt::ShiftModifier), this),
&QShortcut::activated, this, &ShaderViewer::stepBack);
QObject::connect(new QShortcut(QKeySequence(Qt::Key_F10 | Qt::ControlModifier), this),
&QShortcut::activated, this, &ShaderViewer::runToCursor);
QObject::connect(new QShortcut(QKeySequence(Qt::Key_F5), this), &QShortcut::activated, this,
&ShaderViewer::run);
QObject::connect(new QShortcut(QKeySequence(Qt::Key_F5 | Qt::ShiftModifier), this),
&QShortcut::activated, this, &ShaderViewer::runBack);
QObject::connect(new QShortcut(QKeySequence(Qt::Key_F9), this), &QShortcut::activated,
[this]() { ToggleBreakpoint(); });
// event filter to pick up tooltip events
ui->constants->installEventFilter(this);
ui->registers->installEventFilter(this);
ui->watch->installEventFilter(this);
SetCurrentStep(0);
QObject::connect(ui->watch, &RDTableWidget::keyPress, this, &ShaderViewer::watch_keyPress);
ui->watch->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->watch, &RDTableWidget::customContextMenuRequested, this,
&ShaderViewer::variables_contextMenu);
ui->registers->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->registers, &RDTreeWidget::customContextMenuRequested, this,
&ShaderViewer::variables_contextMenu);
ui->locals->setContextMenuPolicy(Qt::CustomContextMenu);
QObject::connect(ui->locals, &RDTreeWidget::customContextMenuRequested, this,
&ShaderViewer::variables_contextMenu);
ui->watch->insertRow(0);
for(int i = 0; i < ui->watch->columnCount(); i++)
{
QTableWidgetItem *item = new QTableWidgetItem();
if(i > 0)
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(0, i, item);
}
ui->watch->resizeRowsToContents();
ToolWindowManager::raiseToolWindow(m_DisassemblyFrame);
}
else
{
// hide watch, constants, variables
ui->watch->hide();
ui->registers->hide();
ui->constants->hide();
ui->locals->hide();
ui->callstack->hide();
// hide debugging toolbar buttons
ui->debugSep->hide();
ui->runBack->hide();
ui->run->hide();
ui->stepBack->hide();
ui->stepNext->hide();
ui->runToCursor->hide();
ui->runToSample->hide();
ui->runToNaNOrInf->hide();
ui->regFormatSep->hide();
ui->intView->hide();
ui->floatView->hide();
ui->debugToggleSep->hide();
ui->debugToggle->hide();
// show input and output signatures
ui->inputSig->setColumns(
{tr("Name"), tr("Index"), tr("Reg"), tr("Type"), tr("SysValue"), tr("Mask"), tr("Used")});
for(int i = 0; i < ui->inputSig->header()->count(); i++)
ui->inputSig->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents);
ui->outputSig->setColumns(
{tr("Name"), tr("Index"), tr("Reg"), tr("Type"), tr("SysValue"), tr("Mask"), tr("Used")});
for(int i = 0; i < ui->outputSig->header()->count(); i++)
ui->outputSig->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents);
if(m_ShaderDetails)
{
for(const SigParameter &s : m_ShaderDetails->inputSignature)
{
QString name = s.varName.isEmpty()
? QString(s.semanticName)
: QFormatStr("%1 (%2)").arg(s.varName).arg(s.semanticName);
if(s.semanticName.isEmpty())
name = s.varName;
QString semIdx = s.needSemanticIndex ? QString::number(s.semanticIndex) : QString();
QString regIdx =
s.systemValue == ShaderBuiltin::Undefined ? QString::number(s.regIndex) : lit("-");
ui->inputSig->addTopLevelItem(new RDTreeWidgetItem(
{name, semIdx, regIdx, TypeString(s), ToQStr(s.systemValue),
GetComponentString(s.regChannelMask), GetComponentString(s.channelUsedMask)}));
}
bool multipleStreams = false;
for(const SigParameter &s : m_ShaderDetails->outputSignature)
{
if(s.stream > 0)
{
multipleStreams = true;
break;
}
}
for(const SigParameter &s : m_ShaderDetails->outputSignature)
{
QString name = s.varName.isEmpty()
? QString(s.semanticName)
: QFormatStr("%1 (%2)").arg(s.varName).arg(s.semanticName);
if(s.semanticName.isEmpty())
name = s.varName;
if(multipleStreams)
name = QFormatStr("Stream %1 : %2").arg(s.stream).arg(name);
QString semIdx = s.needSemanticIndex ? QString::number(s.semanticIndex) : QString();
QString regIdx =
s.systemValue == ShaderBuiltin::Undefined ? QString::number(s.regIndex) : lit("-");
ui->outputSig->addTopLevelItem(new RDTreeWidgetItem(
{name, semIdx, regIdx, TypeString(s), ToQStr(s.systemValue),
GetComponentString(s.regChannelMask), GetComponentString(s.channelUsedMask)}));
}
}
ui->inputSig->setWindowTitle(tr("Input Signature"));
ui->docking->addToolWindow(ui->inputSig, ToolWindowManager::AreaReference(
ToolWindowManager::BottomOf,
ui->docking->areaOf(m_DisassemblyFrame), 0.2f));
ui->docking->setToolWindowProperties(
ui->inputSig, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
ui->outputSig->setWindowTitle(tr("Output Signature"));
ui->docking->addToolWindow(
ui->outputSig, ToolWindowManager::AreaReference(ToolWindowManager::RightOf,
ui->docking->areaOf(ui->inputSig), 0.5f));
ui->docking->setToolWindowProperties(
ui->outputSig, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
}
for(ScintillaEdit *edit : m_Scintillas)
{
// C# LightCoral
edit->markerSetBack(CURRENT_MARKER, SCINTILLA_COLOUR(240, 128, 128));
edit->markerSetBack(CURRENT_MARKER + 1, SCINTILLA_COLOUR(240, 128, 128));
edit->markerDefine(CURRENT_MARKER, SC_MARK_SHORTARROW);
edit->markerDefine(CURRENT_MARKER + 1, SC_MARK_BACKGROUND);
edit->indicSetFore(CURRENT_INDICATOR, SCINTILLA_COLOUR(240, 128, 128));
edit->indicSetAlpha(CURRENT_INDICATOR, 220);
edit->indicSetOutlineAlpha(CURRENT_INDICATOR, 255);
edit->indicSetUnder(CURRENT_INDICATOR, true);
edit->indicSetStyle(CURRENT_INDICATOR, INDIC_STRAIGHTBOX);
edit->indicSetHoverFore(CURRENT_INDICATOR, SCINTILLA_COLOUR(240, 128, 128));
edit->indicSetHoverStyle(CURRENT_INDICATOR, INDIC_STRAIGHTBOX);
// C# LightSlateGray
edit->markerSetBack(FINISHED_MARKER, SCINTILLA_COLOUR(119, 136, 153));
edit->markerSetBack(FINISHED_MARKER + 1, SCINTILLA_COLOUR(119, 136, 153));
edit->markerDefine(FINISHED_MARKER, SC_MARK_ROUNDRECT);
edit->markerDefine(FINISHED_MARKER + 1, SC_MARK_BACKGROUND);
edit->indicSetFore(FINISHED_INDICATOR, SCINTILLA_COLOUR(119, 136, 153));
edit->indicSetAlpha(FINISHED_INDICATOR, 220);
edit->indicSetOutlineAlpha(FINISHED_INDICATOR, 255);
edit->indicSetUnder(FINISHED_INDICATOR, true);
edit->indicSetStyle(FINISHED_INDICATOR, INDIC_STRAIGHTBOX);
edit->indicSetHoverFore(FINISHED_INDICATOR, SCINTILLA_COLOUR(119, 136, 153));
edit->indicSetHoverStyle(FINISHED_INDICATOR, INDIC_STRAIGHTBOX);
// C# Red
edit->markerSetBack(BREAKPOINT_MARKER, SCINTILLA_COLOUR(255, 0, 0));
edit->markerSetBack(BREAKPOINT_MARKER + 1, SCINTILLA_COLOUR(255, 0, 0));
edit->markerDefine(BREAKPOINT_MARKER, SC_MARK_CIRCLE);
edit->markerDefine(BREAKPOINT_MARKER + 1, SC_MARK_BACKGROUND);
}
}
void ShaderViewer::updateWindowTitle()
{
if(m_ShaderDetails)
{
QString shaderName = m_Ctx.GetResourceName(m_ShaderDetails->resourceId);
// On D3D12, get the shader name from the pipeline rather than the shader itself
// for the benefit of D3D12 which doesn't have separate shader objects
if(m_Ctx.CurPipelineState().IsCaptureD3D12())
shaderName = QFormatStr("%1 %2")
.arg(m_Ctx.GetResourceName(m_Pipeline))
.arg(m_Ctx.CurPipelineState().Abbrev(m_ShaderDetails->stage));
if(m_Trace)
setWindowTitle(QFormatStr("Debugging %1 - %2").arg(shaderName).arg(m_DebugContext));
else
setWindowTitle(shaderName);
}
}
void ShaderViewer::gotoSourceDebugging()
{
if(m_CurInstructionScintilla)
{
ToolWindowManager::raiseToolWindow(m_CurInstructionScintilla);
m_CurInstructionScintilla->setFocus(Qt::MouseFocusReason);
}
}
void ShaderViewer::gotoDisassemblyDebugging()
{
ToolWindowManager::raiseToolWindow(m_DisassemblyFrame);
m_DisassemblyFrame->setFocus(Qt::MouseFocusReason);
}
ShaderViewer::~ShaderViewer()
{
// don't want to async invoke while using 'this', so save the trace separately
ShaderDebugTrace *trace = m_Trace;
// unregister any shortcuts on this window
m_Ctx.GetMainWindow()->UnregisterShortcut(QString(), this);
m_Ctx.Replay().AsyncInvoke([trace](IReplayController *r) { r->FreeTrace(trace); });
if(m_CloseCallback)
m_CloseCallback(&m_Ctx);
m_Ctx.RemoveCaptureViewer(this);
delete ui;
}
void ShaderViewer::OnCaptureLoaded()
{
}
void ShaderViewer::OnCaptureClosed()
{
ToolWindowManager::closeToolWindow(this);
}
void ShaderViewer::OnEventChanged(uint32_t eventId)
{
updateDebugging();
updateWindowTitle();
}
ScintillaEdit *ShaderViewer::AddFileScintilla(const QString &name, const QString &text)
{
ScintillaEdit *scintilla = MakeEditor(
lit("scintilla") + name, text, IsD3D(m_Ctx.APIProps().localRenderer) ? SCLEX_HLSL : SCLEX_GLSL);
scintilla->setReadOnly(true);
scintilla->setWindowTitle(name);
((QWidget *)scintilla)->setProperty("name", name);
QObject::connect(scintilla, &ScintillaEdit::keyPressed, this, &ShaderViewer::readonly_keyPressed);
ToolWindowManager::AreaReference ref(ToolWindowManager::EmptySpace);
if(!m_Scintillas.empty())
ref = ToolWindowManager::AreaReference(ToolWindowManager::AddTo,
ui->docking->areaOf(m_Scintillas[0]));
ui->docking->addToolWindow(scintilla, ref);
ui->docking->setToolWindowProperties(scintilla, ToolWindowManager::HideCloseButton |
ToolWindowManager::DisallowFloatWindow |
ToolWindowManager::AlwaysDisplayFullTabs);
m_Scintillas.push_back(scintilla);
return scintilla;
}
ScintillaEdit *ShaderViewer::MakeEditor(const QString &name, const QString &text, int lang)
{
ScintillaEdit *ret = new ScintillaEdit(this);
ret->setText(text.toUtf8().data());
sptr_t numlines = ret->lineCount();
int margin0width = 30;
if(numlines > 1000)
margin0width += 6;
if(numlines > 10000)
margin0width += 6;
margin0width = int(margin0width * devicePixelRatioF());
ret->setMarginLeft(4.0 * devicePixelRatioF());
ret->setMarginWidthN(0, margin0width);
ret->setMarginWidthN(1, 0);
ret->setMarginWidthN(2, 16.0 * devicePixelRatioF());
ret->setObjectName(name);
ret->styleSetFont(STYLE_DEFAULT,
QFontDatabase::systemFont(QFontDatabase::FixedFont).family().toUtf8().data());
// C# DarkGreen
ret->indicSetFore(INDICATOR_REGHIGHLIGHT, SCINTILLA_COLOUR(0, 100, 0));
ret->indicSetStyle(INDICATOR_REGHIGHLIGHT, INDIC_ROUNDBOX);
// set up find result highlight style
ret->indicSetFore(INDICATOR_FINDRESULT, SCINTILLA_COLOUR(200, 200, 127));
ret->indicSetStyle(INDICATOR_FINDRESULT, INDIC_FULLBOX);
ret->indicSetAlpha(INDICATOR_FINDRESULT, 50);
ret->indicSetOutlineAlpha(INDICATOR_FINDRESULT, 80);
ConfigureSyntax(ret, lang);
ret->setTabWidth(4);
ret->setScrollWidth(1);
ret->setScrollWidthTracking(true);
ret->colourise(0, -1);
ret->emptyUndoBuffer();
return ret;
}
void ShaderViewer::readonly_keyPressed(QKeyEvent *event)
{
if(event->key() == Qt::Key_F && (event->modifiers() & Qt::ControlModifier))
{
m_FindReplace->setReplaceMode(false);
on_findReplace_clicked();
}
if(event->key() == Qt::Key_F3)
{
find((event->modifiers() & Qt::ShiftModifier) == 0);
}
}
void ShaderViewer::editable_keyPressed(QKeyEvent *event)
{
if(event->key() == Qt::Key_H && (event->modifiers() & Qt::ControlModifier))
{
m_FindReplace->setReplaceMode(true);
on_findReplace_clicked();
}
}
void ShaderViewer::debug_contextMenu(const QPoint &pos)
{
ScintillaEdit *edit = qobject_cast<ScintillaEdit *>(QObject::sender());
bool isDisasm = (edit == m_DisassemblyView);
int scintillaPos = edit->positionFromPoint(pos.x(), pos.y());
QMenu contextMenu(this);
QAction gotoOther(isDisasm ? tr("Go to Source") : tr("Go to Disassembly"), this);
QObject::connect(&gotoOther, &QAction::triggered, [this, isDisasm]() {
if(isDisasm)
gotoSourceDebugging();
else
gotoDisassemblyDebugging();
updateDebugging();
});
QAction intDisplay(tr("Integer register display"), this);
QAction floatDisplay(tr("Float register display"), this);
intDisplay.setCheckable(true);
floatDisplay.setCheckable(true);
intDisplay.setChecked(ui->intView->isChecked());
floatDisplay.setChecked(ui->floatView->isChecked());
QObject::connect(&intDisplay, &QAction::triggered, this, &ShaderViewer::on_intView_clicked);
QObject::connect(&floatDisplay, &QAction::triggered, this, &ShaderViewer::on_floatView_clicked);
if(isDisasm && m_CurInstructionScintilla == NULL)
gotoOther.setEnabled(false);
contextMenu.addAction(&gotoOther);
contextMenu.addSeparator();
contextMenu.addAction(&intDisplay);
contextMenu.addAction(&floatDisplay);
contextMenu.addSeparator();
QAction addBreakpoint(tr("Toggle breakpoint here"), this);
QAction runCursor(tr("Run to Cursor"), this);
QObject::connect(&addBreakpoint, &QAction::triggered, [this, scintillaPos] {
m_DisassemblyView->setSelection(scintillaPos, scintillaPos);
ToggleBreakpoint();
});
QObject::connect(&runCursor, &QAction::triggered, [this, scintillaPos] {
m_DisassemblyView->setSelection(scintillaPos, scintillaPos);
runToCursor();
});
contextMenu.addAction(&addBreakpoint);
contextMenu.addAction(&runCursor);
contextMenu.addSeparator();
QAction copyText(tr("Copy"), this);
QAction selectAll(tr("Select All"), this);
copyText.setEnabled(!edit->selectionEmpty());
QObject::connect(©Text, &QAction::triggered,
[edit] { edit->copyRange(edit->selectionStart(), edit->selectionEnd()); });
QObject::connect(&selectAll, &QAction::triggered, [edit] { edit->selectAll(); });
contextMenu.addAction(©Text);
contextMenu.addAction(&selectAll);
contextMenu.addSeparator();
RDDialog::show(&contextMenu, edit->viewport()->mapToGlobal(pos));
}
void ShaderViewer::variables_contextMenu(const QPoint &pos)
{
QAbstractItemView *w = qobject_cast<QAbstractItemView *>(QObject::sender());
QMenu contextMenu(this);
QAction copyValue(tr("Copy"), this);
QAction addWatch(tr("Add Watch"), this);
QAction deleteWatch(tr("Delete Watch"), this);
QAction clearAll(tr("Clear All"), this);
contextMenu.addAction(©Value);
contextMenu.addSeparator();
contextMenu.addAction(&addWatch);
if(QObject::sender() == ui->watch)
{
QObject::connect(©Value, &QAction::triggered, [this] { ui->watch->copySelection(); });
contextMenu.addAction(&deleteWatch);
contextMenu.addSeparator();
contextMenu.addAction(&clearAll);
// start with no row selected
int selRow = -1;
QList<QTableWidgetItem *> items = ui->watch->selectedItems();
for(QTableWidgetItem *item : items)
{
// if no row is selected, or the same as this item, set selected row to this item's
if(selRow == -1 || selRow == item->row())
{
selRow = item->row();
}
else
{
// we only get here if we see an item on a different row selected - that means too many rows
// so bail out
selRow = -1;
break;
}
}
// if we have a selected row that isn't the last one, we can add/delete this item
deleteWatch.setEnabled(selRow >= 0 && selRow < ui->watch->rowCount() - 1);
addWatch.setEnabled(selRow >= 0 && selRow < ui->watch->rowCount() - 1);
QObject::connect(&addWatch, &QAction::triggered, [this, selRow] {
QTableWidgetItem *item = ui->watch->item(selRow, 0);
if(item)
AddWatch(item->text());
});
QObject::connect(&deleteWatch, &QAction::triggered,
[this, selRow] { ui->watch->removeRow(selRow); });
QObject::connect(&clearAll, &QAction::triggered, [this] {
while(ui->watch->rowCount() > 1)
ui->watch->removeRow(0);
});
}
else
{
RDTreeWidget *tree = qobject_cast<RDTreeWidget *>(w);
QObject::connect(©Value, &QAction::triggered, [tree] { tree->copySelection(); });
addWatch.setEnabled(tree->selectedItem() != NULL);
QObject::connect(&addWatch, &QAction::triggered, [this, tree] {
if(tree == ui->locals)
AddWatch(tree->selectedItem()->tag().toString());
else
AddWatch(tree->selectedItem()->text(0));
});
}
RDDialog::show(&contextMenu, w->viewport()->mapToGlobal(pos));
}
void ShaderViewer::disassembly_buttonReleased(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
sptr_t scintillaPos = m_DisassemblyView->positionFromPoint(event->x(), event->y());
sptr_t start = m_DisassemblyView->wordStartPosition(scintillaPos, true);
sptr_t end = m_DisassemblyView->wordEndPosition(scintillaPos, true);
QString text = QString::fromUtf8(m_DisassemblyView->textRange(start, end));
QRegularExpression regexp(lit("^[xyzwrgba]+$"));
// if we match a swizzle look before that for the register
if(regexp.match(text).hasMatch())
{
start--;
while(isspace(m_DisassemblyView->charAt(start)))
start--;
if(m_DisassemblyView->charAt(start) == '.')
{
end = m_DisassemblyView->wordEndPosition(start - 1, true);
start = m_DisassemblyView->wordStartPosition(start - 1, true);
text = QString::fromUtf8(m_DisassemblyView->textRange(start, end));
}
}
if(!text.isEmpty())
{
VariableTag tag;
getRegisterFromWord(text, tag.cat, tag.idx, tag.arrayIdx);
// for now since we don't have friendly naming, only highlight registers
if(tag.cat != VariableCategory::Unknown)
{
start = 0;
end = m_DisassemblyView->length();
for(int i = 0; i < ui->registers->topLevelItemCount(); i++)
{
RDTreeWidgetItem *item = ui->registers->topLevelItem(i);
if(item->tag().value<VariableTag>() == tag)
item->setBackgroundColor(QColor::fromHslF(
0.333f, 1.0f, qBound(0.25, palette().color(QPalette::Base).lightnessF(), 0.85)));
else
item->setBackground(QBrush());
}
for(int i = 0; i < ui->constants->topLevelItemCount(); i++)
{
RDTreeWidgetItem *item = ui->constants->topLevelItem(i);
if(item->tag().value<VariableTag>() == tag)
item->setBackgroundColor(QColor::fromHslF(
0.333f, 1.0f, qBound(0.25, palette().color(QPalette::Base).lightnessF(), 0.85)));
else
item->setBackground(QBrush());
}
m_DisassemblyView->setIndicatorCurrent(INDICATOR_REGHIGHLIGHT);
m_DisassemblyView->indicatorClearRange(start, end);
sptr_t flags = SCFIND_MATCHCASE | SCFIND_WHOLEWORD;
if(tag.cat != VariableCategory::Unknown)
{
flags |= SCFIND_REGEXP | SCFIND_POSIX;
text += lit("\\.[xyzwrgba]+");
}
QByteArray findUtf8 = text.toUtf8();
QPair<int, int> result;
do
{
result = m_DisassemblyView->findText(flags, findUtf8.data(), start, end);
if(result.first >= 0)
m_DisassemblyView->indicatorFillRange(result.first, result.second - result.first);
start = result.second;
} while(result.first >= 0);
}
}
}
}
void ShaderViewer::disassemble_typeChanged(int index)
{
if(m_ShaderDetails == NULL)
return;
QString targetStr = m_DisassemblyType->currentText();
QByteArray target = targetStr.toUtf8();
for(const ShaderProcessingTool &disasm : m_Ctx.Config().ShaderProcessors)
{
if(targetStr == targetName(disasm))
{
ShaderToolOutput out = disasm.DisassembleShader(this, m_ShaderDetails, "");
rdcstr text;
if(out.result.isEmpty())
text = out.log;
else
text.assign((const char *)out.result.data(), out.result.size());
m_DisassemblyView->setReadOnly(false);
m_DisassemblyView->setText(text.c_str());
m_DisassemblyView->setReadOnly(true);
m_DisassemblyView->emptyUndoBuffer();
return;
}
}
m_Ctx.Replay().AsyncInvoke([this, target](IReplayController *r) {
rdcstr disasm = r->DisassembleShader(m_Pipeline, m_ShaderDetails, target.data());
GUIInvoke::call(this, [this, disasm]() {
m_DisassemblyView->setReadOnly(false);
m_DisassemblyView->setText(disasm.c_str());
m_DisassemblyView->setReadOnly(true);
m_DisassemblyView->emptyUndoBuffer();
});
});
}
void ShaderViewer::watch_keyPress(QKeyEvent *event)
{
if(event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)
{
QList<QTableWidgetItem *> items = ui->watch->selectedItems();
if(!items.isEmpty() && items.back()->row() < ui->watch->rowCount() - 1)
ui->watch->removeRow(items.back()->row());
}
}
void ShaderViewer::on_watch_itemChanged(QTableWidgetItem *item)
{
// ignore changes to the type/value columns. Only look at name changes, which must be by the user
if(item->column() != 0)
return;
static bool recurse = false;
if(recurse)
return;
recurse = true;
// if the item is now empty, remove it
if(item->text().isEmpty())
ui->watch->removeRow(item->row());
// ensure we have a trailing row for adding new watch items.
if(ui->watch->rowCount() == 0 || ui->watch->item(ui->watch->rowCount() - 1, 0) == NULL ||
!ui->watch->item(ui->watch->rowCount() - 1, 0)->text().isEmpty())
{
// add a new row if needed
if(ui->watch->rowCount() == 0 || ui->watch->item(ui->watch->rowCount() - 1, 0) != NULL)
ui->watch->insertRow(ui->watch->rowCount());
for(int i = 0; i < ui->watch->columnCount(); i++)
{
QTableWidgetItem *newItem = new QTableWidgetItem();
if(i > 0)
newItem->setFlags(newItem->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(ui->watch->rowCount() - 1, i, newItem);
}
}
ui->watch->resizeRowsToContents();
recurse = false;
updateDebugging();
}
bool ShaderViewer::stepBack()
{
if(!m_Trace)
return false;
if(CurrentStep() == 0)
return false;
if(isSourceDebugging())
{
const ShaderDebugState &oldstate = m_Trace->states[CurrentStep()];
LineColumnInfo oldLine =
m_Trace->lineInfo[qMin(m_Trace->lineInfo.size() - 1, (size_t)oldstate.nextInstruction)];
while(CurrentStep() < m_Trace->states.count())
{
m_CurrentStep--;
const ShaderDebugState &state = m_Trace->states[m_CurrentStep];
if(m_Breakpoints.contains((int)state.nextInstruction))
break;
if(m_CurrentStep == 0)
break;
if(m_Trace->lineInfo[state.nextInstruction] == oldLine)
continue;
break;
}
SetCurrentStep(CurrentStep());
}
else
{
SetCurrentStep(CurrentStep() - 1);
}
return true;
}
bool ShaderViewer::stepNext()
{
if(!m_Trace)
return false;
if(CurrentStep() + 1 >= m_Trace->states.count())
return false;
if(isSourceDebugging())
{
const ShaderDebugState &oldstate = m_Trace->states[CurrentStep()];
LineColumnInfo oldLine = m_Trace->lineInfo[oldstate.nextInstruction];
while(CurrentStep() < m_Trace->states.count())
{
m_CurrentStep++;
const ShaderDebugState &state = m_Trace->states[m_CurrentStep];
if(m_Breakpoints.contains((int)state.nextInstruction))
break;
if(m_CurrentStep + 1 >= m_Trace->states.count())
break;
if(m_Trace->lineInfo[state.nextInstruction] == oldLine)
continue;
break;
}
SetCurrentStep(CurrentStep());
}
else
{
SetCurrentStep(CurrentStep() + 1);
}
return true;
}
void ShaderViewer::runToCursor()
{
if(!m_Trace)
return;
ScintillaEdit *cur = currentScintilla();
if(cur != m_DisassemblyView)
{
int scintillaIndex = m_FileScintillas.indexOf(cur);
if(scintillaIndex < 0)
return;
sptr_t i = cur->lineFromPosition(cur->currentPos()) + 1;
QMap<int32_t, size_t> &fileMap = m_Line2Inst[scintillaIndex];
// find the next line that maps to an instruction
for(; i < cur->lineCount(); i++)
{
if(fileMap.contains(i))
{
runTo((int)fileMap[i], true);
return;
}
}
// if we didn't find one, just run
run();
}
else
{
sptr_t i = m_DisassemblyView->lineFromPosition(m_DisassemblyView->currentPos());
for(; i < m_DisassemblyView->lineCount(); i++)
{
int line = instructionForLine(i);
if(line >= 0)
{
runTo(line, true);
break;
}
}
}
}
int ShaderViewer::instructionForLine(sptr_t line)
{
QString trimmed = QString::fromUtf8(m_DisassemblyView->getLine(line).trimmed());
int colon = trimmed.indexOf(QLatin1Char(':'));
if(colon > 0)
{
trimmed.truncate(colon);
bool ok = false;
int instruction = trimmed.toInt(&ok);
if(ok && instruction >= 0)
return instruction;
}
return -1;
}
void ShaderViewer::runToSample()
{
runTo(-1, true, ShaderEvents::SampleLoadGather);
}
void ShaderViewer::runToNanOrInf()
{
runTo(-1, true, ShaderEvents::GeneratedNanOrInf);
}
void ShaderViewer::runBack()
{
runTo(-1, false);
}
void ShaderViewer::run()
{
runTo(-1, true);
}
void ShaderViewer::runTo(int runToInstruction, bool forward, ShaderEvents condition)
{
if(!m_Trace)
return;
int step = CurrentStep();
int inc = forward ? 1 : -1;
bool firstStep = true;
while(step < m_Trace->states.count())
{
if(runToInstruction >= 0 && m_Trace->states[step].nextInstruction == (uint32_t)runToInstruction)
break;
if(!firstStep && (m_Trace->states[step + inc].flags & condition))
break;
if(!firstStep && m_Breakpoints.contains((int)m_Trace->states[step].nextInstruction))
break;
firstStep = false;
if(step + inc < 0 || step + inc >= m_Trace->states.count())
break;
step += inc;
}
SetCurrentStep(step);
}
QString ShaderViewer::stringRep(const ShaderVariable &var, bool useType)
{
if(ui->intView->isChecked() || (useType && var.type == VarType::Int))
return RowString(var, 0, VarType::Int);
if(useType && var.type == VarType::UInt)
return RowString(var, 0, VarType::UInt);
return RowString(var, 0, VarType::Float);
}
RDTreeWidgetItem *ShaderViewer::makeResourceRegister(const Bindpoint &bind, uint32_t idx,
const BoundResource &bound,
const ShaderResource &res)
{
QString name = QFormatStr(" (%1)").arg(res.name);
const TextureDescription *tex = m_Ctx.GetTexture(bound.resourceId);
const BufferDescription *buf = m_Ctx.GetBuffer(bound.resourceId);
QChar regChar(QLatin1Char('u'));
if(res.isReadOnly)
regChar = QLatin1Char('t');
QString regname;
if(m_Ctx.APIProps().pipelineType == GraphicsAPI::D3D12)
{
if(bind.arraySize == 1)
regname = QFormatStr("%1%2:%3").arg(regChar).arg(bind.bindset).arg(bind.bind);
else
regname = QFormatStr("%1%2:%3[%4]").arg(regChar).arg(bind.bindset).arg(bind.bind).arg(idx);
}
else
{
regname = QFormatStr("%1%2").arg(regChar).arg(bind.bind);
}
if(tex)
{
QString type = QFormatStr("%1x%2x%3[%4] @ %5 - %6")
.arg(tex->width)
.arg(tex->height)
.arg(tex->depth > 1 ? tex->depth : tex->arraysize)
.arg(tex->mips)
.arg(tex->format.Name())
.arg(m_Ctx.GetResourceName(bound.resourceId));
return new RDTreeWidgetItem({regname + name, lit("Texture"), type});
}
else if(buf)
{
QString type =
QFormatStr("%1 - %2").arg(buf->length).arg(m_Ctx.GetResourceName(bound.resourceId));
return new RDTreeWidgetItem({regname + name, lit("Buffer"), type});
}
else
{
return new RDTreeWidgetItem(
{regname + name, lit("Resource"), m_Ctx.GetResourceName(bound.resourceId)});
}
}
QString ShaderViewer::targetName(const ShaderProcessingTool &disasm)
{
return lit("%1 (%2)").arg(ToQStr(disasm.output)).arg(disasm.name);
}
void ShaderViewer::addFileList()
{
QListWidget *list = new QListWidget(this);
list->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
list->setSelectionMode(QAbstractItemView::SingleSelection);
QObject::connect(list, &QListWidget::currentRowChanged, [this](int idx) {
QWidget *raiseWidget = m_Scintillas[idx];
if(m_Scintillas[idx] == m_DisassemblyView)
raiseWidget = m_DisassemblyFrame;
ToolWindowManager::raiseToolWindow(raiseWidget);
});
list->setWindowTitle(tr("File List"));
for(ScintillaEdit *s : m_Scintillas)
{
if(s == m_DisassemblyView)
list->addItem(m_DisassemblyFrame->windowTitle());
else
list->addItem(s->windowTitle());
}
ui->docking->addToolWindow(
list, ToolWindowManager::AreaReference(ToolWindowManager::LeftOf,
ui->docking->areaOf(m_Scintillas.front()), 0.2f));
ui->docking->setToolWindowProperties(
list, ToolWindowManager::HideCloseButton | ToolWindowManager::DisallowFloatWindow);
}
void ShaderViewer::combineStructures(RDTreeWidgetItem *root)
{
RDTreeWidgetItem temp;
// we perform a filter moving from root to temp. At each point we check the node:
// * if the node has no struct or array prefix, it gets moved
// * if the node does have a prefix, we sweep finding all matching elements with the same prefix,
// strip the prefix off them and make a combined node, then recurse to combine anything
// underneath. We aren't greedy in picking prefixes so this should generate a struct/array tree.
// * in the event that a node has no matching elements we move it across as if it had no prefix.
// * we iterate from last to first, because when combining elements that may be spread out in the
// list of children, we want to combine up to the position of the last item, not the position of
// the first.
for(int c = root->childCount() - 1; c >= 0;)
{
RDTreeWidgetItem *child = root->takeChild(c);
c--;
QString name = child->text(0);
int dotIndex = name.indexOf(QLatin1Char('.'));
int arrIndex = name.indexOf(QLatin1Char('['));
// if this node doesn't have any segments, just move it across.
if(dotIndex < 0 && arrIndex < 0)
{
temp.insertChild(0, child);
continue;
}
// store the index of the first separator
int sepIndex = dotIndex;
bool isArray = false;
if(sepIndex == -1 || (arrIndex > 0 && arrIndex < sepIndex))
{
sepIndex = arrIndex;
isArray = true;
}
// we have a valid node to match against, record the prefix (including separator character)
QString prefix = name.mid(0, sepIndex + 1);
QVector<RDTreeWidgetItem *> matches = {child};
// iterate down from the next item
for(int n = c; n >= 0; n--)
{
RDTreeWidgetItem *testNode = root->child(n);
QString testName = testNode->text(0);
QString testprefix = testName.mid(0, sepIndex + 1);
// no match - continue
if(testprefix != prefix)
continue;
// match, take this child
matches.push_back(root->takeChild(n));
// also decrement c since we're taking a child ahead of where that loop will go.
c--;
}
// no other matches with the same prefix, just move across
if(matches.count() == 1)
{
temp.insertChild(0, child);
continue;
}
// sort the children by name
std::sort(matches.begin(), matches.end(),
[](const RDTreeWidgetItem *a, const RDTreeWidgetItem *b) {
return a->text(0) < b->text(0);
});
// create a new parent with just the prefix
QVariantList values = {name.mid(0, sepIndex)};
for(int i = 1; i < child->dataCount(); i++)
values.push_back(QVariant());
RDTreeWidgetItem *parent = new RDTreeWidgetItem(values);
// add all the children (stripping the prefix from their name)
for(RDTreeWidgetItem *item : matches)
{
if(!isArray)
item->setText(0, item->text(0).mid(sepIndex + 1));
parent->addChild(item);
if(item->background().color().isValid())
parent->setBackground(item->background());
if(item->foreground().color().isValid())
parent->setForeground(item->foreground());
}
// recurse and combine members of this object if a struct
if(!isArray)
combineStructures(parent);
// now add to the list
temp.insertChild(0, parent);
}
if(root->childCount() > 0)
qCritical() << "Some objects left on root!";
// move all the children back from the temp object into the parameter
while(temp.childCount() > 0)
root->addChild(temp.takeChild(0));
}
RDTreeWidgetItem *ShaderViewer::findLocal(RDTreeWidgetItem *root, QString name)
{
if(root->tag().toString() == name)
return root;
for(int i = 0; i < root->childCount(); i++)
{
RDTreeWidgetItem *ret = findLocal(root->child(i), name);
if(ret)
return ret;
}
return NULL;
}
void ShaderViewer::updateDebugging()
{
if(!m_Trace || m_CurrentStep < 0 || m_CurrentStep >= m_Trace->states.count())
return;
if(ui->debugToggle->isEnabled())
{
if(isSourceDebugging())
ui->debugToggle->setText(tr("Debug in Assembly"));
else
ui->debugToggle->setText(tr("Debug in HLSL"));
}
const ShaderDebugState &state = m_Trace->states[m_CurrentStep];
uint32_t nextInst = state.nextInstruction;
bool done = false;
if(m_CurrentStep == m_Trace->states.count() - 1)
{
nextInst--;
done = true;
}
// add current instruction marker
m_DisassemblyView->markerDeleteAll(CURRENT_MARKER);
m_DisassemblyView->markerDeleteAll(CURRENT_MARKER + 1);
m_DisassemblyView->markerDeleteAll(FINISHED_MARKER);
m_DisassemblyView->markerDeleteAll(FINISHED_MARKER + 1);
if(m_CurInstructionScintilla)
{
m_CurInstructionScintilla->markerDeleteAll(CURRENT_MARKER);
m_CurInstructionScintilla->markerDeleteAll(CURRENT_MARKER + 1);
m_CurInstructionScintilla->markerDeleteAll(FINISHED_MARKER);
m_CurInstructionScintilla->markerDeleteAll(FINISHED_MARKER + 1);
m_CurInstructionScintilla->indicatorClearRange(0, m_CurInstructionScintilla->length());
m_CurInstructionScintilla = NULL;
}
for(sptr_t i = 0; i < m_DisassemblyView->lineCount(); i++)
{
if(QString::fromUtf8(m_DisassemblyView->getLine(i).trimmed())
.startsWith(QFormatStr("%1:").arg(nextInst)))
{
m_DisassemblyView->markerAdd(i, done ? FINISHED_MARKER : CURRENT_MARKER);
m_DisassemblyView->markerAdd(i, done ? FINISHED_MARKER + 1 : CURRENT_MARKER + 1);
int pos = m_DisassemblyView->positionFromLine(i);
m_DisassemblyView->setSelection(pos, pos);
ensureLineScrolled(m_DisassemblyView, i);
break;
}
}
ui->callstack->clear();
if(state.nextInstruction < m_Trace->lineInfo.size())
{
LineColumnInfo &lineInfo = m_Trace->lineInfo[state.nextInstruction];
for(const rdcstr &s : lineInfo.callstack)
ui->callstack->insertItem(0, s);
if(lineInfo.fileIndex >= 0 && lineInfo.fileIndex < m_FileScintillas.count())
{
m_CurInstructionScintilla = m_FileScintillas[lineInfo.fileIndex];
if(m_CurInstructionScintilla)
{
for(sptr_t line = lineInfo.lineStart; line <= (sptr_t)lineInfo.lineEnd; line++)
{
if(line == (sptr_t)lineInfo.lineEnd)
m_CurInstructionScintilla->markerAdd(line - 1, done ? FINISHED_MARKER : CURRENT_MARKER);
if(lineInfo.colStart == 0)
{
// with no column info, add a marker on the whole line
m_CurInstructionScintilla->markerAdd(line - 1,
done ? FINISHED_MARKER + 1 : CURRENT_MARKER + 1);
}
else
{
// otherwise add an indicator on the column range.
// Start from the full position/length for this line
sptr_t pos = m_CurInstructionScintilla->positionFromLine(line - 1);
sptr_t len = m_CurInstructionScintilla->lineEndPosition(line - 1) - pos;
// if we're on the last line of the range, restrict the length to end on the last column
if(line == (sptr_t)lineInfo.lineEnd && lineInfo.colEnd != 0)
len = lineInfo.colEnd;
// if we're on the start of the range (which may also be the last line above too), shift
// inwards towards the first column
if(line == (sptr_t)lineInfo.lineStart)
{
pos += lineInfo.colStart - 1;
len -= lineInfo.colStart - 1;
}
m_CurInstructionScintilla->setIndicatorCurrent(done ? FINISHED_INDICATOR
: CURRENT_INDICATOR);
m_CurInstructionScintilla->indicatorFillRange(pos, len);
}
}
if(isSourceDebugging() ||
ui->docking->areaOf(m_CurInstructionScintilla) != ui->docking->areaOf(m_DisassemblyFrame))
ToolWindowManager::raiseToolWindow(m_CurInstructionScintilla);
int pos = m_CurInstructionScintilla->positionFromLine(lineInfo.lineStart - 1);
m_CurInstructionScintilla->setSelection(pos, pos);
ensureLineScrolled(m_CurInstructionScintilla, lineInfo.lineStart - 1);
}
}
}
if(ui->constants->topLevelItemCount() == 0)
{
for(int i = 0; i < m_Trace->constantBlocks.count(); i++)
{
for(int j = 0; j < m_Trace->constantBlocks[i].members.count(); j++)
{
if(m_Trace->constantBlocks[i].members[j].rows > 0 ||
m_Trace->constantBlocks[i].members[j].columns > 0)
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_Trace->constantBlocks[i].members[j].name, lit("cbuffer"),
stringRep(m_Trace->constantBlocks[i].members[j], false)});
node->setTag(QVariant::fromValue(VariableTag(VariableCategory::Constants, j, i)));
ui->constants->addTopLevelItem(node);
}
}
}
for(int i = 0; i < m_Trace->inputs.count(); i++)
{
const ShaderVariable &input = m_Trace->inputs[i];
if(input.rows > 0 || input.columns > 0)
{
RDTreeWidgetItem *node = new RDTreeWidgetItem(
{input.name, ToQStr(input.type) + lit(" input"), stringRep(input, true)});
node->setTag(QVariant::fromValue(VariableTag(VariableCategory::Inputs, i)));
ui->constants->addTopLevelItem(node);
}
}
rdcarray<BoundResourceArray> rw = m_Ctx.CurPipelineState().GetReadWriteResources(m_Stage);
rdcarray<BoundResourceArray> ro = m_Ctx.CurPipelineState().GetReadOnlyResources(m_Stage);
bool tree = false;
for(int i = 0;
i < m_Mapping->readWriteResources.count() && i < m_ShaderDetails->readWriteResources.count();
i++)
{
Bindpoint bind = m_Mapping->readWriteResources[i];
if(!bind.used)
continue;
int idx = rw.indexOf(bind);
if(idx < 0 || rw[idx].resources.isEmpty())
continue;
if(bind.arraySize == 1)
{
RDTreeWidgetItem *node = makeResourceRegister(bind, 0, rw[idx].resources[0],
m_ShaderDetails->readWriteResources[i]);
if(node)
ui->constants->addTopLevelItem(node);
}
else
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->readWriteResources[i].name,
QFormatStr("[%1]").arg(bind.arraySize), QString()});
for(uint32_t a = 0; a < bind.arraySize; a++)
node->addChild(makeResourceRegister(bind, a, rw[idx].resources[a],
m_ShaderDetails->readWriteResources[i]));
tree = true;
ui->constants->addTopLevelItem(node);
}
}
for(int i = 0;
i < m_Mapping->readOnlyResources.count() && i < m_ShaderDetails->readOnlyResources.count();
i++)
{
Bindpoint bind = m_Mapping->readOnlyResources[i];
if(!bind.used)
continue;
int idx = ro.indexOf(bind);
if(idx < 0 || ro[idx].resources.isEmpty())
continue;
if(bind.arraySize == 1)
{
RDTreeWidgetItem *node = makeResourceRegister(bind, 0, ro[idx].resources[0],
m_ShaderDetails->readOnlyResources[i]);
if(node)
ui->constants->addTopLevelItem(node);
}
else
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({m_ShaderDetails->readOnlyResources[i].name,
QFormatStr("[%1]").arg(bind.arraySize), QString()});
for(uint32_t a = 0; a < bind.arraySize; a++)
node->addChild(makeResourceRegister(bind, a, ro[idx].resources[a],
m_ShaderDetails->readOnlyResources[i]));
tree = true;
ui->constants->addTopLevelItem(node);
}
}
if(tree)
{
ui->constants->setIndentation(20);
ui->constants->setRootIsDecorated(true);
}
}
if(m_Trace->hasLocals)
{
const QString stateprefix = lit("!!@");
RDTreeViewExpansionState expansion;
ui->locals->saveExpansionExternal(expansion, stateprefix, 0);
ui->locals->clear();
const QString xyzw = lit("xyzw");
RDTreeWidgetItem fakeroot;
for(size_t lidx = 0; lidx < state.locals.size(); lidx++)
{
// iterate in reverse order, so newest locals tend to end up on top
const LocalVariableMapping &l = state.locals[state.locals.size() - 1 - lidx];
QString localName = l.localName;
QString regNames, typeName;
QString value;
bool modified = false;
if(l.type == VarType::UInt)
typeName = lit("uint");
else if(l.type == VarType::Int)
typeName = lit("int");
else if(l.type == VarType::Float)
typeName = lit("float");
else if(l.type == VarType::Double)
typeName = lit("double");
if(l.registers[0].type == RegisterType::IndexedTemporary)
{
typeName += lit("[]");
regNames = QFormatStr("x%1").arg(l.registers[0].index);
for(const RegisterRange &mr : state.modified)
{
if(mr.type == RegisterType::IndexedTemporary && mr.index == l.registers[0].index)
{
modified = true;
break;
}
}
}
else
{
if(l.rows > 1)
typeName += QFormatStr("%1x%2").arg(l.rows).arg(l.columns);
else
typeName += QString::number(l.columns);
for(uint32_t i = 0; i < l.regCount; i++)
{
const RegisterRange &r = l.registers[i];
for(const RegisterRange &mr : state.modified)
{
if(mr.type == r.type && mr.index == r.index && mr.component == r.component)
{
modified = true;
break;
}
}
if(!value.isEmpty())
value += lit(", ");
if(!regNames.isEmpty())
regNames += lit(", ");
if(r.type == RegisterType::Undefined)
{
regNames += lit("-");
value += lit("?");
continue;
}
const ShaderVariable *var = GetRegisterVariable(r);
if(var)
{
// if the previous register was the same, just append our component
if(i > 0 && r.type == l.registers[i - 1].type && r.index == l.registers[i - 1].index)
{
// remove the auto-appended ", " - there must be one because this isn't the first
// register
regNames.chop(2);
regNames += xyzw[r.component];
}
else
{
regNames += QFormatStr("%1.%2").arg(var->name).arg(xyzw[r.component]);
}
if(l.type == VarType::UInt)
value += Formatter::Format(var->value.uv[r.component]);
else if(l.type == VarType::Int)
value += Formatter::Format(var->value.iv[r.component]);
else if(l.type == VarType::Float)
value += Formatter::Format(var->value.fv[r.component]);
else if(l.type == VarType::Double)
value += Formatter::Format(var->value.dv[r.component]);
}
else
{
regNames += lit("<error>");
value += lit("<error>");
}
}
}
RDTreeWidgetItem *node = new RDTreeWidgetItem({localName, regNames, typeName, value});
node->setTag(localName);
if(modified)
node->setForegroundColor(QColor(Qt::red));
if(l.registers[0].type == RegisterType::IndexedTemporary)
{
const ShaderVariable *var = NULL;
if(l.registers[0].index < state.indexableTemps.size())
var = &state.indexableTemps[l.registers[0].index];
for(int t = 0; var && t < var->members.count(); t++)
{
node->addChild(new RDTreeWidgetItem({
QFormatStr("%1[%2]").arg(localName).arg(t), QFormatStr("%1[%2]").arg(regNames).arg(t),
typeName, RowString(var->members[t], 0, l.type),
}));
}
}
fakeroot.addChild(node);
}
// recursively combine nodes with the same prefix together
combineStructures(&fakeroot);
while(fakeroot.childCount() > 0)
ui->locals->addTopLevelItem(fakeroot.takeChild(0));
ui->locals->applyExternalExpansion(expansion, stateprefix, 0);
}
if(ui->registers->topLevelItemCount() == 0)
{
for(int i = 0; i < state.registers.count(); i++)
ui->registers->addTopLevelItem(
new RDTreeWidgetItem({state.registers[i].name, lit("temporary"), QString()}));
for(int i = 0; i < state.indexableTemps.count(); i++)
{
RDTreeWidgetItem *node =
new RDTreeWidgetItem({QFormatStr("x%1").arg(i), lit("indexable"), QString()});
for(int t = 0; t < state.indexableTemps[i].members.count(); t++)
node->addChild(new RDTreeWidgetItem(
{state.indexableTemps[i].members[t].name, lit("indexable"), QString()}));
ui->registers->addTopLevelItem(node);
}
for(int i = 0; i < state.outputs.count(); i++)
ui->registers->addTopLevelItem(
new RDTreeWidgetItem({state.outputs[i].name, lit("output"), QString()}));
}
ui->registers->beginUpdate();
int v = 0;
for(int i = 0; i < state.registers.count(); i++)
{
RDTreeWidgetItem *node = ui->registers->topLevelItem(v++);
node->setText(2, stringRep(state.registers[i], false));
node->setTag(QVariant::fromValue(VariableTag(VariableCategory::Temporaries, i)));
bool modified = false;
for(const RegisterRange &mr : state.modified)
{
if(mr.type == RegisterType::Temporary && mr.index == i)
{
modified = true;
break;
}
}
if(modified)
node->setForegroundColor(QColor(Qt::red));
else
node->setForeground(QBrush());
}
for(int i = 0; i < state.indexableTemps.count(); i++)
{
RDTreeWidgetItem *node = ui->registers->topLevelItem(v++);
bool modified = false;
for(const RegisterRange &mr : state.modified)
{
if(mr.type == RegisterType::IndexedTemporary && mr.index == i)
{
modified = true;
break;
}
}
if(modified)
node->setForegroundColor(QColor(Qt::red));
else
node->setForeground(QBrush());
for(int t = 0; t < state.indexableTemps[i].members.count(); t++)
{
RDTreeWidgetItem *child = node->child(t);
if(modified)
child->setForegroundColor(QColor(Qt::red));
else
child->setForeground(QBrush());
child->setText(2, stringRep(state.indexableTemps[i].members[t], false));
child->setTag(QVariant::fromValue(VariableTag(VariableCategory::IndexTemporaries, t, i)));
}
}
for(int i = 0; i < state.outputs.count(); i++)
{
RDTreeWidgetItem *node = ui->registers->topLevelItem(v++);
node->setText(2, stringRep(state.outputs[i], false));
node->setTag(QVariant::fromValue(VariableTag(VariableCategory::Outputs, i)));
bool modified = false;
for(const RegisterRange &mr : state.modified)
{
if(mr.type == RegisterType::Output && mr.index == i)
{
modified = true;
break;
}
}
if(modified)
node->setForegroundColor(QColor(Qt::red));
else
node->setForeground(QBrush());
}
ui->registers->endUpdate();
ui->watch->setUpdatesEnabled(false);
for(int i = 0; i < ui->watch->rowCount() - 1; i++)
{
QTableWidgetItem *item = ui->watch->item(i, 0);
QString reg = item->text().trimmed();
QRegularExpression regexp(lit("^([rvo])([0-9]+)(\\.[xyzwrgba]+)?(,[xfiudb])?$"));
QRegularExpressionMatch match = regexp.match(reg);
// try indexable temps
if(!match.hasMatch())
{
regexp = QRegularExpression(lit("^(x[0-9]+)\\[([0-9]+)\\](\\.[xyzwrgba]+)?(,[xfiudb])?$"));
match = regexp.match(reg);
}
if(match.hasMatch())
{
item = new QTableWidgetItem(tr("register", "watch type"));
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 2, item);
QString regtype = match.captured(1);
QString regidx = match.captured(2);
QString swizzle = match.captured(3).replace(QLatin1Char('.'), QString());
QString regcast = match.captured(4).replace(QLatin1Char(','), QString());
if(regcast.isEmpty())
{
if(ui->intView->isChecked())
regcast = lit("i");
else
regcast = lit("f");
}
VariableCategory varCat = VariableCategory::Unknown;
int arrIndex = -1;
bool ok = false;
if(regtype == lit("r"))
{
varCat = VariableCategory::Temporaries;
}
else if(regtype == lit("v"))
{
varCat = VariableCategory::Inputs;
}
else if(regtype == lit("o"))
{
varCat = VariableCategory::Outputs;
}
else if(regtype[0] == QLatin1Char('x'))
{
varCat = VariableCategory::IndexTemporaries;
QString tempArrayIndexStr = regtype.mid(1);
arrIndex = tempArrayIndexStr.toInt(&ok);
if(!ok)
arrIndex = -1;
}
const rdcarray<ShaderVariable> *vars = GetVariableList(varCat, arrIndex);
ok = false;
int regindex = regidx.toInt(&ok);
if(vars && ok && regindex >= 0 && regindex < vars->count())
{
const ShaderVariable &vr = (*vars)[regindex];
if(swizzle.isEmpty())
{
swizzle = lit("xyzw").left((int)vr.columns);
if(regcast == lit("d") && swizzle.count() > 2)
swizzle = lit("xy");
}
QString val;
for(int s = 0; s < swizzle.count(); s++)
{
QChar swiz = swizzle[s];
int elindex = 0;
if(swiz == QLatin1Char('x') || swiz == QLatin1Char('r'))
elindex = 0;
if(swiz == QLatin1Char('y') || swiz == QLatin1Char('g'))
elindex = 1;
if(swiz == QLatin1Char('z') || swiz == QLatin1Char('b'))
elindex = 2;
if(swiz == QLatin1Char('w') || swiz == QLatin1Char('a'))
elindex = 3;
if(regcast == lit("i"))
{
val += Formatter::Format(vr.value.iv[elindex]);
}
else if(regcast == lit("f"))
{
val += Formatter::Format(vr.value.fv[elindex]);
}
else if(regcast == lit("u"))
{
val += Formatter::Format(vr.value.uv[elindex]);
}
else if(regcast == lit("x"))
{
val += Formatter::Format(vr.value.uv[elindex], true);
}
else if(regcast == lit("b"))
{
val += QFormatStr("%1").arg(vr.value.uv[elindex], 32, 2, QLatin1Char('0'));
}
else if(regcast == lit("d"))
{
if(elindex < 2)
val += Formatter::Format(vr.value.dv[elindex]);
else
val += lit("-");
}
if(s < swizzle.count() - 1)
val += lit(", ");
}
item = new QTableWidgetItem(vr.name);
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 1, item);
item = new QTableWidgetItem(val);
item->setData(Qt::UserRole, QVariant::fromValue(VariableTag(varCat, regindex, arrIndex)));
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 3, item);
continue;
}
}
else
{
regexp = QRegularExpression(lit("^(.+)(\\.[xyzwrgba]+)?(,[xfiudb])?$"));
match = regexp.match(reg);
if(match.hasMatch())
{
QString variablename = match.captured(1);
RDTreeWidgetItem *local = findLocal(ui->locals->invisibleRootItem(), match.captured(1));
if(local)
{
// TODO apply swizzle/typecast ?
item = new QTableWidgetItem(local->text(1));
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 1, item);
item = new QTableWidgetItem(local->text(2));
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 2, item);
if(local->childCount() > 0)
{
// can't display structs
item = new QTableWidgetItem(lit("{...}"));
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 3, item);
}
else
{
item = new QTableWidgetItem(local->text(3));
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 3, item);
}
continue;
}
}
}
item = new QTableWidgetItem();
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 2, item);
item = new QTableWidgetItem(tr("Error evaluating expression"));
item->setFlags(item->flags() & ~Qt::ItemIsEditable);
ui->watch->setItem(i, 3, item);
}
ui->watch->setUpdatesEnabled(true);
ui->constants->resizeColumnToContents(0);
ui->registers->resizeColumnToContents(0);
ui->constants->resizeColumnToContents(1);
ui->registers->resizeColumnToContents(1);
updateVariableTooltip();
}
const ShaderVariable *ShaderViewer::GetRegisterVariable(const RegisterRange &r)
{
const ShaderDebugState &state = m_Trace->states[m_CurrentStep];
const ShaderVariable *var = NULL;
switch(r.type)
{
case RegisterType::Undefined: break;
case RegisterType::Input:
if(r.index < m_Trace->inputs.size())
var = &m_Trace->inputs[r.index];
break;
case RegisterType::Temporary:
if(r.index < state.registers.size())
var = &state.registers[r.index];
break;
case RegisterType::IndexedTemporary:
if(r.index < state.indexableTemps.size())
var = &state.indexableTemps[r.index];
break;
case RegisterType::Output:
if(r.index < state.outputs.size())
var = &state.outputs[r.index];
break;
}
return var;
}
void ShaderViewer::ensureLineScrolled(ScintillaEdit *s, int line)
{
int firstLine = s->firstVisibleLine();
int linesVisible = s->linesOnScreen();
if(s->isVisible() && (line < firstLine || line > (firstLine + linesVisible)))
s->setFirstVisibleLine(qMax(0, line - linesVisible / 2));
}
int ShaderViewer::CurrentStep()
{
return m_CurrentStep;
}
void ShaderViewer::SetCurrentStep(int step)
{
if(m_Trace && !m_Trace->states.empty())
m_CurrentStep = qBound(0, step, m_Trace->states.count() - 1);
else
m_CurrentStep = 0;
updateDebugging();
}
void ShaderViewer::ToggleBreakpoint(int instruction)
{
sptr_t instLine = -1;
if(instruction == -1)
{
ScintillaEdit *cur = currentScintilla();
// search forward for an instruction
if(cur != m_DisassemblyView)
{
int scintillaIndex = m_FileScintillas.indexOf(cur);
if(scintillaIndex < 0)
return;
// add one to go from scintilla line numbers (0-based) to ours (1-based)
sptr_t i = cur->lineFromPosition(cur->currentPos()) + 1;
QMap<int32_t, size_t> &fileMap = m_Line2Inst[scintillaIndex];
// find the next line that maps to an instruction
for(; i < cur->lineCount(); i++)
{
if(fileMap.contains(i))
{
instruction = (int)fileMap[i];
break;
}
}
}
else
{
instLine = m_DisassemblyView->lineFromPosition(m_DisassemblyView->currentPos());
for(; instLine < m_DisassemblyView->lineCount(); instLine++)
{
instruction = instructionForLine(instLine);
if(instruction >= 0)
break;
}
}
}
if(instruction < 0 || instruction >= m_DisassemblyView->lineCount())
return;
if(instLine == -1)
{
// find line for this instruction
for(instLine = 0; instLine < m_DisassemblyView->lineCount(); instLine++)
{
int inst = instructionForLine(instLine);
if(instruction == inst)
break;
}
if(instLine >= m_DisassemblyView->lineCount())
instLine = -1;
}
if(m_Breakpoints.contains(instruction))
{
if(instLine >= 0)
{
m_DisassemblyView->markerDelete(instLine, BREAKPOINT_MARKER);
m_DisassemblyView->markerDelete(instLine, BREAKPOINT_MARKER + 1);
const LineColumnInfo &lineInfo = m_Trace->lineInfo[instruction];
if(lineInfo.fileIndex >= 0 && lineInfo.fileIndex < m_FileScintillas.count())
{
for(sptr_t line = lineInfo.lineStart; line <= (sptr_t)lineInfo.lineEnd; line++)
{
ScintillaEdit *s = m_FileScintillas[lineInfo.fileIndex];
if(s)
{
m_FileScintillas[lineInfo.fileIndex]->markerDelete(line - 1, BREAKPOINT_MARKER);
m_FileScintillas[lineInfo.fileIndex]->markerDelete(line - 1, BREAKPOINT_MARKER + 1);
}
}
}
}
m_Breakpoints.removeOne(instruction);
}
else
{
if(instLine >= 0)
{
m_DisassemblyView->markerAdd(instLine, BREAKPOINT_MARKER);
m_DisassemblyView->markerAdd(instLine, BREAKPOINT_MARKER + 1);
const LineColumnInfo &lineInfo = m_Trace->lineInfo[instruction];
if(lineInfo.fileIndex >= 0 && lineInfo.fileIndex < m_FileScintillas.count())
{
for(sptr_t line = lineInfo.lineStart; line <= (sptr_t)lineInfo.lineEnd; line++)
{
ScintillaEdit *s = m_FileScintillas[lineInfo.fileIndex];
if(s)
{
m_FileScintillas[lineInfo.fileIndex]->markerAdd(line - 1, BREAKPOINT_MARKER);
m_FileScintillas[lineInfo.fileIndex]->markerAdd(line - 1, BREAKPOINT_MARKER + 1);
}
}
}
}
m_Breakpoints.push_back(instruction);
}
}
void ShaderViewer::ShowErrors(const rdcstr &errors)
{
if(m_Errors)
{
m_Errors->setReadOnly(false);
m_Errors->setText(errors.c_str());
m_Errors->setReadOnly(true);
if(!errors.isEmpty())
ToolWindowManager::raiseToolWindow(m_Errors);
}
}
void ShaderViewer::AddWatch(const rdcstr &variable)
{
int newRow = ui->watch->rowCount() - 1;
ui->watch->insertRow(ui->watch->rowCount() - 1);
ui->watch->setItem(newRow, 0, new QTableWidgetItem(variable));
ToolWindowManager::raiseToolWindow(ui->watch);
ui->watch->activateWindow();
ui->watch->QWidget::setFocus();
}
int ShaderViewer::snippetPos()
{
if(IsD3D(m_Ctx.APIProps().pipelineType))
return 0;
if(m_Scintillas.isEmpty())
return 0;
QPair<int, int> ver =
m_Scintillas[0]->findText(SCFIND_REGEXP, "#version.*", 0, m_Scintillas[0]->length());
if(ver.first < 0)
return 0;
return ver.second + 1;
}
void ShaderViewer::insertVulkanUBO()
{
if(m_Scintillas.isEmpty())
return;
m_Scintillas[0]->insertText(snippetPos(),
"layout(binding = 0, std140) uniform RENDERDOC_Uniforms\n"
"{\n"
" uvec4 TexDim;\n"
" uint SelectedMip;\n"
" int TextureType;\n"
" uint SelectedSliceFace;\n"
" int SelectedSample;\n"
"} RENDERDOC;\n\n");
}
void ShaderViewer::snippet_textureDimensions()
{
if(m_Scintillas.isEmpty())
return;
GraphicsAPI api = m_Ctx.APIProps().pipelineType;
if(IsD3D(api))
{
m_Scintillas[0]->insertText(snippetPos(),
"// xyz == width, height, depth. w == # mips\n"
"uint4 RENDERDOC_TexDim; \n\n");
}
else if(api == GraphicsAPI::OpenGL)
{
m_Scintillas[0]->insertText(snippetPos(),
"// xyz == width, height, depth. w == # mips\n"
"uniform uvec4 RENDERDOC_TexDim;\n\n");
}
else if(api == GraphicsAPI::Vulkan)
{
insertVulkanUBO();
}
m_Scintillas[0]->setSelection(0, 0);
}
void ShaderViewer::snippet_selectedMip()
{
if(m_Scintillas.isEmpty())
return;
GraphicsAPI api = m_Ctx.APIProps().pipelineType;
if(IsD3D(api))
{
m_Scintillas[0]->insertText(snippetPos(),
"// selected mip in UI\n"
"uint RENDERDOC_SelectedMip;\n\n");
}
else if(api == GraphicsAPI::OpenGL)
{
m_Scintillas[0]->insertText(snippetPos(),
"// selected mip in UI\n"
"uniform uint RENDERDOC_SelectedMip;\n\n");
}
else if(api == GraphicsAPI::Vulkan)
{
insertVulkanUBO();
}
m_Scintillas[0]->setSelection(0, 0);
}
void ShaderViewer::snippet_selectedSlice()
{
if(m_Scintillas.isEmpty())
return;
GraphicsAPI api = m_Ctx.APIProps().pipelineType;
if(IsD3D(api))
{
m_Scintillas[0]->insertText(snippetPos(),
"// selected array slice or cubemap face in UI\n"
"uint RENDERDOC_SelectedSliceFace;\n\n");
}
else if(api == GraphicsAPI::OpenGL)
{
m_Scintillas[0]->insertText(snippetPos(),
"// selected array slice or cubemap face in UI\n"
"uniform uint RENDERDOC_SelectedSliceFace;\n\n");
}
else if(api == GraphicsAPI::Vulkan)
{
insertVulkanUBO();
}
m_Scintillas[0]->setSelection(0, 0);
}
void ShaderViewer::snippet_selectedSample()
{
if(m_Scintillas.isEmpty())
return;
GraphicsAPI api = m_Ctx.APIProps().pipelineType;
if(IsD3D(api))
{
m_Scintillas[0]->insertText(snippetPos(),
"// selected MSAA sample or -numSamples for resolve. See docs\n"
"int RENDERDOC_SelectedSample;\n\n");
}
else if(api == GraphicsAPI::OpenGL)
{
m_Scintillas[0]->insertText(snippetPos(),
"// selected MSAA sample or -numSamples for resolve. See docs\n"
"uniform int RENDERDOC_SelectedSample;\n\n");
}
else if(api == GraphicsAPI::Vulkan)
{
insertVulkanUBO();
}
m_Scintillas[0]->setSelection(0, 0);
}
void ShaderViewer::snippet_selectedType()
{
if(m_Scintillas.isEmpty())
return;
GraphicsAPI api = m_Ctx.APIProps().pipelineType;
if(IsD3D(api))
{
m_Scintillas[0]->insertText(snippetPos(),
"// 1 = 1D, 2 = 2D, 3 = 3D, 4 = Depth, 5 = Depth + Stencil\n"
"// 6 = Depth (MS), 7 = Depth + Stencil (MS)\n"
"uint RENDERDOC_TextureType;\n\n");
}
else if(api == GraphicsAPI::OpenGL)
{
m_Scintillas[0]->insertText(snippetPos(),
"// 1 = 1D, 2 = 2D, 3 = 3D, 4 = Cube\n"
"// 5 = 1DArray, 6 = 2DArray, 7 = CubeArray\n"
"// 8 = Rect, 9 = Buffer, 10 = 2DMS\n"
"uniform uint RENDERDOC_TextureType;\n\n");
}
else if(api == GraphicsAPI::Vulkan)
{
insertVulkanUBO();
}
m_Scintillas[0]->setSelection(0, 0);
}
void ShaderViewer::snippet_samplers()
{
if(m_Scintillas.isEmpty())
return;
GraphicsAPI api = m_Ctx.APIProps().pipelineType;
if(IsD3D(api))
{
m_Scintillas[0]->insertText(snippetPos(),
"// Samplers\n"
"SamplerState pointSampler : register(s0);\n"
"SamplerState linearSampler : register(s1);\n"
"// End Samplers\n\n");
m_Scintillas[0]->setSelection(0, 0);
}
}
void ShaderViewer::snippet_resources()
{
if(m_Scintillas.isEmpty())
return;
GraphicsAPI api = m_Ctx.APIProps().pipelineType;
if(IsD3D(api))
{
m_Scintillas[0]->insertText(
snippetPos(),
"// Textures\n"
"Texture1DArray<float4> texDisplayTex1DArray : register(t1);\n"
"Texture2DArray<float4> texDisplayTex2DArray : register(t2);\n"
"Texture3D<float4> texDisplayTex3D : register(t3);\n"
"Texture2DArray<float2> texDisplayTexDepthArray : register(t4);\n"
"Texture2DArray<uint2> texDisplayTexStencilArray : register(t5);\n"
"Texture2DMSArray<float2> texDisplayTexDepthMSArray : register(t6);\n"
"Texture2DMSArray<uint2> texDisplayTexStencilMSArray : register(t7);\n"
"Texture2DMSArray<float4> texDisplayTex2DMSArray : register(t9);\n"
"\n"
"Texture1DArray<uint4> texDisplayUIntTex1DArray : register(t11);\n"
"Texture2DArray<uint4> texDisplayUIntTex2DArray : register(t12);\n"
"Texture3D<uint4> texDisplayUIntTex3D : register(t13);\n"
"Texture2DMSArray<uint4> texDisplayUIntTex2DMSArray : register(t19);\n"
"\n"
"Texture1DArray<int4> texDisplayIntTex1DArray : register(t21);\n"
"Texture2DArray<int4> texDisplayIntTex2DArray : register(t22);\n"
"Texture3D<int4> texDisplayIntTex3D : register(t23);\n"
"Texture2DMSArray<int4> texDisplayIntTex2DMSArray : register(t29);\n"
"// End Textures\n\n\n");
}
else if(api == GraphicsAPI::OpenGL)
{
m_Scintillas[0]->insertText(snippetPos(),
"// Textures\n"
"// Unsigned int samplers\n"
"layout (binding = 1) uniform usampler1D texUInt1D;\n"
"layout (binding = 2) uniform usampler2D texUInt2D;\n"
"layout (binding = 3) uniform usampler3D texUInt3D;\n"
"// cube = 4\n"
"layout (binding = 5) uniform usampler1DArray texUInt1DArray;\n"
"layout (binding = 6) uniform usampler2DArray texUInt2DArray;\n"
"// cube array = 7\n"
"layout (binding = 8) uniform usampler2DRect texUInt2DRect;\n"
"layout (binding = 9) uniform usamplerBuffer texUIntBuffer;\n"
"layout (binding = 10) uniform usampler2DMS texUInt2DMS;\n"
"\n"
"// Int samplers\n"
"layout (binding = 1) uniform isampler1D texSInt1D;\n"
"layout (binding = 2) uniform isampler2D texSInt2D;\n"
"layout (binding = 3) uniform isampler3D texSInt3D;\n"
"// cube = 4\n"
"layout (binding = 5) uniform isampler1DArray texSInt1DArray;\n"
"layout (binding = 6) uniform isampler2DArray texSInt2DArray;\n"
"// cube array = 7\n"
"layout (binding = 8) uniform isampler2DRect texSInt2DRect;\n"
"layout (binding = 9) uniform isamplerBuffer texSIntBuffer;\n"
"layout (binding = 10) uniform isampler2DMS texSInt2DMS;\n"
"\n"
"// Floating point samplers\n"
"layout (binding = 1) uniform sampler1D tex1D;\n"
"layout (binding = 2) uniform sampler2D tex2D;\n"
"layout (binding = 3) uniform sampler3D tex3D;\n"
"layout (binding = 4) uniform samplerCube texCube;\n"
"layout (binding = 5) uniform sampler1DArray tex1DArray;\n"
"layout (binding = 6) uniform sampler2DArray tex2DArray;\n"
"layout (binding = 7) uniform samplerCubeArray texCubeArray;\n"
"layout (binding = 8) uniform sampler2DRect tex2DRect;\n"
"layout (binding = 9) uniform samplerBuffer texBuffer;\n"
"layout (binding = 10) uniform sampler2DMS tex2DMS;\n"
"// End Textures\n\n\n");
}
else if(api == GraphicsAPI::Vulkan)
{
m_Scintillas[0]->insertText(snippetPos(),
"// Textures\n"
"// Floating point samplers\n"
"layout(binding = 6) uniform sampler1DArray tex1DArray;\n"
"layout(binding = 7) uniform sampler2DArray tex2DArray;\n"
"layout(binding = 8) uniform sampler3D tex3D;\n"
"layout(binding = 9) uniform sampler2DMS tex2DMS;\n"
"\n"
"// Unsigned int samplers\n"
"layout(binding = 11) uniform usampler1DArray texUInt1DArray;\n"
"layout(binding = 12) uniform usampler2DArray texUInt2DArray;\n"
"layout(binding = 13) uniform usampler3D texUInt3D;\n"
"layout(binding = 14) uniform usampler2DMS texUInt2DMS;\n"
"\n"
"// Int samplers\n"
"layout(binding = 16) uniform isampler1DArray texSInt1DArray;\n"
"layout(binding = 17) uniform isampler2DArray texSInt2DArray;\n"
"layout(binding = 18) uniform isampler3D texSInt3D;\n"
"layout(binding = 19) uniform isampler2DMS texSInt2DMS;\n"
"// End Textures\n\n\n");
}
m_Scintillas[0]->setSelection(0, 0);
}
bool ShaderViewer::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::ToolTip)
{
QHelpEvent *he = (QHelpEvent *)event;
RDTreeWidget *tree = qobject_cast<RDTreeWidget *>(watched);
if(tree)
{
RDTreeWidgetItem *item = tree->itemAt(tree->viewport()->mapFromGlobal(QCursor::pos()));
if(item)
{
VariableTag tag = item->tag().value<VariableTag>();
showVariableTooltip(tag.cat, tag.idx, tag.arrayIdx);
}
}
RDTableWidget *table = qobject_cast<RDTableWidget *>(watched);
if(table)
{
QTableWidgetItem *item = table->itemAt(table->viewport()->mapFromGlobal(QCursor::pos()));
if(item)
{
item = table->item(item->row(), 2);
VariableTag tag = item->data(Qt::UserRole).value<VariableTag>();
showVariableTooltip(tag.cat, tag.idx, tag.arrayIdx);
}
}
}
if(event->type() == QEvent::MouseMove || event->type() == QEvent::Leave)
{
hideVariableTooltip();
}
return QFrame::eventFilter(watched, event);
}
void ShaderViewer::disasm_tooltipShow(int x, int y)
{
// do nothing if there's no trace
if(!m_Trace || m_CurrentStep < 0 || m_CurrentStep >= m_Trace->states.count())
return;
ScintillaEdit *sc = qobject_cast<ScintillaEdit *>(QObject::sender());
if(!sc)
return;
// ignore any messages if we're already outside the viewport
if(!sc->rect().contains(sc->mapFromGlobal(QCursor::pos())))
return;
if(sc->isVisible())
{
sptr_t scintillaPos = sc->positionFromPoint(x, y);
sptr_t start = sc->wordStartPosition(scintillaPos, true);
sptr_t end = sc->wordEndPosition(scintillaPos, true);
do
{
// expand leftwards through simple struct . access
// TODO handle arrays
while(isspace(sc->charAt(start - 1)))
start--;
if(sc->charAt(start - 1) == '.')
start = sc->wordStartPosition(start - 2, true);
else
break;
} while(true);
QString text = QString::fromUtf8(sc->textRange(start, end)).trimmed();
if(!text.isEmpty())
showVariableTooltip(text);
}
}
void ShaderViewer::disasm_tooltipHide(int x, int y)
{
hideVariableTooltip();
}
void ShaderViewer::showVariableTooltip(VariableCategory varCat, int varIdx, int arrayIdx)
{
const rdcarray<ShaderVariable> *vars = GetVariableList(varCat, arrayIdx);
if(!vars || varIdx < 0 || varIdx >= vars->count())
{
m_TooltipVarIdx = -1;
return;
}
m_TooltipVarCat = varCat;
m_TooltipName = QString();
m_TooltipVarIdx = varIdx;
m_TooltipArrayIdx = arrayIdx;
m_TooltipPos = QCursor::pos();
updateVariableTooltip();
}
void ShaderViewer::showVariableTooltip(QString name)
{
VariableCategory varCat;
int varIdx;
int arrayIdx;
getRegisterFromWord(name, varCat, varIdx, arrayIdx);
if(varCat != VariableCategory::Unknown)
showVariableTooltip(varCat, varIdx, arrayIdx);
m_TooltipVarCat = VariableCategory::ByString;
m_TooltipName = name;
m_TooltipPos = QCursor::pos();
updateVariableTooltip();
}
const rdcarray<ShaderVariable> *ShaderViewer::GetVariableList(VariableCategory varCat, int arrayIdx)
{
const rdcarray<ShaderVariable> *vars = NULL;
if(!m_Trace || m_CurrentStep < 0 || m_CurrentStep >= m_Trace->states.count())
return vars;
const ShaderDebugState &state = m_Trace->states[m_CurrentStep];
arrayIdx = qMax(0, arrayIdx);
switch(varCat)
{
case VariableCategory::ByString:
case VariableCategory::Unknown: vars = NULL; break;
case VariableCategory::Temporaries: vars = &state.registers; break;
case VariableCategory::IndexTemporaries:
vars = arrayIdx < state.indexableTemps.count() ? &state.indexableTemps[arrayIdx].members : NULL;
break;
case VariableCategory::Inputs: vars = &m_Trace->inputs; break;
case VariableCategory::Constants:
vars = arrayIdx < m_Trace->constantBlocks.count() ? &m_Trace->constantBlocks[arrayIdx].members
: NULL;
break;
case VariableCategory::Outputs: vars = &state.outputs; break;
}
return vars;
}
void ShaderViewer::getRegisterFromWord(const QString &text, VariableCategory &varCat, int &varIdx,
int &arrayIdx)
{
QChar regtype = text[0];
QString regidx = text.mid(1);
varCat = VariableCategory::Unknown;
varIdx = -1;
arrayIdx = 0;
if(regtype == QLatin1Char('r'))
varCat = VariableCategory::Temporaries;
else if(regtype == QLatin1Char('v'))
varCat = VariableCategory::Inputs;
else if(regtype == QLatin1Char('o'))
varCat = VariableCategory::Outputs;
else
return;
bool ok = false;
varIdx = regidx.toInt(&ok);
// if we have a list of registers and the index is in range, and we matched the whole word
// (i.e. v0foo is not the same as v0), then show the tooltip
if(QFormatStr("%1%2").arg(regtype).arg(varIdx) != text)
{
varCat = VariableCategory::Unknown;
varIdx = -1;
}
}
void ShaderViewer::updateVariableTooltip()
{
if(!m_Trace || m_CurrentStep < 0 || m_CurrentStep >= m_Trace->states.count())
return;
const ShaderDebugState &state = m_Trace->states[m_CurrentStep];
if(m_TooltipVarCat == VariableCategory::ByString)
{
if(m_TooltipName.isEmpty())
return;
// first check the constants
QString bracketedName = lit("(") + m_TooltipName;
QString commaName = lit(", ") + m_TooltipName;
QList<ShaderVariable> constants;
for(ShaderVariable &block : m_Trace->constantBlocks)
{
for(ShaderVariable &c : block.members)
{
QString cname = c.name;
// this is a hack for now :(.
if(cname.startsWith(m_TooltipName) || cname.contains(bracketedName) ||
cname.contains(commaName))
constants.push_back(c);
}
}
if(constants.count() == 1)
{
QToolTip::showText(
m_TooltipPos,
QFormatStr("<pre>%1: %2</pre>").arg(constants[0].name).arg(RowString(constants[0], 0)));
return;
}
else if(constants.count() > 1)
{
QString tooltip =
QFormatStr("<pre>%1: %2\n").arg(m_TooltipName).arg(RowString(constants[0], 0));
QString spacing = QString(m_TooltipName.length(), QLatin1Char(' '));
for(int i = 1; i < constants.count(); i++)
tooltip += QFormatStr("%1 %2\n").arg(spacing).arg(RowString(constants[i], 0));
tooltip += lit("</pre>");
QToolTip::showText(m_TooltipPos, tooltip);
return;
}
// now check locals (if there are any)
for(const LocalVariableMapping &l : state.locals)
{
if(QString(l.localName) == m_TooltipName)
{
QString tooltip = QFormatStr("<pre>%1: ").arg(m_TooltipName);
for(uint32_t i = 0; i < l.regCount; i++)
{
const RegisterRange &r = l.registers[i];
if(i > 0)
tooltip += lit(", ");
if(r.type == RegisterType::Undefined)
{
tooltip += lit("?");
continue;
}
const ShaderVariable *var = GetRegisterVariable(r);
if(var)
{
if(l.type == VarType::UInt)
tooltip += Formatter::Format(var->value.uv[r.component]);
else if(l.type == VarType::Int)
tooltip += Formatter::Format(var->value.iv[r.component]);
else if(l.type == VarType::Float)
tooltip += Formatter::Format(var->value.fv[r.component]);
else if(l.type == VarType::Double)
tooltip += Formatter::Format(var->value.dv[r.component]);
}
else
{
tooltip += lit("<error>");
}
}
tooltip += lit("</pre>");
QToolTip::showText(m_TooltipPos, tooltip);
return;
}
}
return;
}
if(m_TooltipVarIdx < 0)
return;
const rdcarray<ShaderVariable> *vars = GetVariableList(m_TooltipVarCat, m_TooltipArrayIdx);
const ShaderVariable &var = (*vars)[m_TooltipVarIdx];
QString text = QFormatStr("<pre>%1\n").arg(var.name);
text +=
lit(" X Y Z W \n"
"--------------------------------------------------------\n");
text += QFormatStr("float | %1 %2 %3 %4\n")
.arg(Formatter::Format(var.value.fv[0]), 11)
.arg(Formatter::Format(var.value.fv[1]), 11)
.arg(Formatter::Format(var.value.fv[2]), 11)
.arg(Formatter::Format(var.value.fv[3]), 11);
text += QFormatStr("uint | %1 %2 %3 %4\n")
.arg(var.value.uv[0], 11, 10, QLatin1Char(' '))
.arg(var.value.uv[1], 11, 10, QLatin1Char(' '))
.arg(var.value.uv[2], 11, 10, QLatin1Char(' '))
.arg(var.value.uv[3], 11, 10, QLatin1Char(' '));
text += QFormatStr("int | %1 %2 %3 %4\n")
.arg(var.value.iv[0], 11, 10, QLatin1Char(' '))
.arg(var.value.iv[1], 11, 10, QLatin1Char(' '))
.arg(var.value.iv[2], 11, 10, QLatin1Char(' '))
.arg(var.value.iv[3], 11, 10, QLatin1Char(' '));
text += QFormatStr("hex | %1 %2 %3 %4")
.arg(Formatter::HexFormat(var.value.uv[0], 4))
.arg(Formatter::HexFormat(var.value.uv[1], 4))
.arg(Formatter::HexFormat(var.value.uv[2], 4))
.arg(Formatter::HexFormat(var.value.uv[3], 4));
text += lit("</pre>");
QToolTip::showText(m_TooltipPos, text);
}
void ShaderViewer::hideVariableTooltip()
{
QToolTip::hideText();
m_TooltipVarIdx = -1;
m_TooltipName = QString();
}
bool ShaderViewer::isSourceDebugging()
{
return !m_DisassemblyFrame->isVisible();
}
void ShaderViewer::on_findReplace_clicked()
{
if(m_FindReplace->isVisible())
{
ToolWindowManager::raiseToolWindow(m_FindReplace);
}
else
{
ui->docking->moveToolWindow(
m_FindReplace, ToolWindowManager::AreaReference(ToolWindowManager::NewFloatingArea));
ui->docking->setToolWindowProperties(m_FindReplace, ToolWindowManager::HideOnClose);
}
ui->docking->areaOf(m_FindReplace)->parentWidget()->activateWindow();
m_FindReplace->takeFocus();
}
void ShaderViewer::PopulateCompileTools()
{
ShaderEncoding encoding = ShaderEncoding(ui->encoding->currentIndex());
rdcarray<ShaderEncoding> accepted = m_Ctx.TargetShaderEncodings();
QStringList strs;
strs.clear();
for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors)
{
// skip tools that can't accept our inputs, or doesn't produce a supported output
if(tool.input != encoding || accepted.indexOf(tool.output) < 0)
continue;
strs << tool.name;
}
// if we can pass in the shader source as-is, add a built-in option
if(accepted.indexOf(encoding) >= 0)
strs << tr("Builtin");
ui->compileTool->clear();
ui->compileTool->addItems(strs);
// pick the first option as highest priority
ui->compileTool->setCurrentIndex(0);
// fill out parameters
PopulateCompileToolParameters();
if(strs.isEmpty())
{
ShowErrors(tr("No compilation tool found that takes %1 as input and produces compatible output")
.arg(ToQStr(encoding)));
}
}
void ShaderViewer::PopulateCompileToolParameters()
{
ShaderEncoding encoding = ShaderEncoding(ui->encoding->currentIndex());
rdcarray<ShaderEncoding> accepted = m_Ctx.TargetShaderEncodings();
ui->toolCommandLine->clear();
if(accepted.indexOf(encoding) >= 0 &&
ui->compileTool->currentIndex() == ui->compileTool->count() - 1)
{
// if we're using the last Builtin tool, there are no default parameters
}
else
{
for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors)
{
if(QString(tool.name) == ui->compileTool->currentText())
{
ui->toolCommandLine->setPlainText(tool.DefaultArguments());
ui->toolCommandLine->setEnabled(true);
break;
}
}
}
for(int i = 0; i < m_Flags.flags.count(); i++)
{
ShaderCompileFlag &flag = m_Flags.flags[i];
if(flag.name == "@cmdline")
{
// append command line from saved flags
ui->toolCommandLine->setPlainText(ui->toolCommandLine->toPlainText() +
lit(" %1").arg(flag.value));
break;
}
}
}
bool ShaderViewer::ProcessIncludeDirectives(QString &source, const rdcstrpairs &files)
{
// try and match up #includes against the files that we have. This isn't always
// possible as fxc only seems to include the source for files if something in
// that file was included in the compiled output. So you might end up with
// dangling #includes - we just have to ignore them
int offs = source.indexOf(lit("#include"));
while(offs >= 0)
{
// search back to ensure this is a valid #include (ie. not in a comment).
// Must only see whitespace before, then a newline.
int ws = qMax(0, offs - 1);
while(ws >= 0 && (source[ws] == QLatin1Char(' ') || source[ws] == QLatin1Char('\t')))
ws--;
// not valid? jump to next.
if(ws > 0 && source[ws] != QLatin1Char('\n'))
{
offs = source.indexOf(lit("#include"), offs + 1);
continue;
}
int start = ws + 1;
bool tail = true;
int lineEnd = source.indexOf(QLatin1Char('\n'), start + 1);
if(lineEnd == -1)
{
lineEnd = source.length();
tail = false;
}
ws = offs + sizeof("#include") - 1;
while(source[ws] == QLatin1Char(' ') || source[ws] == QLatin1Char('\t'))
ws++;
QString line = source.mid(offs, lineEnd - offs + 1);
if(source[ws] != QLatin1Char('<') && source[ws] != QLatin1Char('"'))
{
ShowErrors(tr("Invalid #include directive found:\r\n") + line);
return false;
}
// find matching char, either <> or "";
int end =
source.indexOf(source[ws] == QLatin1Char('"') ? QLatin1Char('"') : QLatin1Char('>'), ws + 1);
if(end == -1)
{
ShowErrors(tr("Invalid #include directive found:\r\n") + line);
return false;
}
QString fname = source.mid(ws + 1, end - ws - 1);
QString fileText;
// look for exact match first
for(int i = 0; i < files.count(); i++)
{
if(QString(files[i].first) == fname)
{
fileText = files[i].second;
break;
}
}
if(fileText.isEmpty())
{
QString search = QFileInfo(fname).fileName();
// if not, try and find the same filename (this is not proper include handling!)
for(const rdcstrpair &kv : files)
{
if(QFileInfo(kv.first).fileName().compare(search, Qt::CaseInsensitive) == 0)
{
fileText = kv.second;
break;
}
}
if(fileText.isEmpty())
fileText = QFormatStr("// Can't find file %1\n").arg(fname);
}
source = source.left(offs) + lit("\n\n") + fileText + lit("\n\n") +
(tail ? source.mid(lineEnd + 1) : QString());
// need to start searching from the beginning - wasteful but allows nested includes to
// work
offs = source.indexOf(lit("#include"));
}
for(const rdcstrpair &kv : files)
{
if(kv.first == "@cmdline")
source = QString(kv.second) + lit("\n\n") + source;
}
return true;
}
void ShaderViewer::on_refresh_clicked()
{
if(m_Trace)
{
m_Ctx.GetPipelineViewer()->SaveShaderFile(m_ShaderDetails);
return;
}
// if we don't have any compile tools - even the 'builtin' one, this compilation is not going to
// succeed.
if(ui->compileTool->count() == 0)
{
ShaderEncoding encoding = ShaderEncoding(ui->encoding->currentIndex());
ShowErrors(tr("No compilation tool found that takes %1 as input and produces compatible output")
.arg(ToQStr(encoding)));
}
else if(m_SaveCallback)
{
ShaderEncoding encoding = ShaderEncoding(ui->encoding->currentIndex());
rdcstrpairs files;
for(ScintillaEdit *s : m_Scintillas)
{
QWidget *w = (QWidget *)s;
files.push_back(make_rdcpair<rdcstr, rdcstr>(
w->property("filename").toString(), QString::fromUtf8(s->getText(s->textLength() + 1))));
}
if(files.isEmpty())
return;
QString source = files[0].second;
if(encoding == ShaderEncoding::HLSL || encoding == ShaderEncoding::GLSL)
{
bool success = ProcessIncludeDirectives(source, files);
if(!success)
return;
}
bytebuf shaderBytes(source.toUtf8());
rdcarray<ShaderEncoding> accepted = m_Ctx.TargetShaderEncodings();
if(accepted.indexOf(encoding) >= 0 &&
ui->compileTool->currentIndex() == ui->compileTool->count() - 1)
{
// if using the builtin compiler, just pass through
}
else
{
for(const ShaderProcessingTool &tool : m_Ctx.Config().ShaderProcessors)
{
if(QString(tool.name) == ui->compileTool->currentText())
{
ShaderToolOutput out = tool.CompileShader(this, source, ui->entryFunc->text(), m_Stage,
ui->toolCommandLine->toPlainText());
ShowErrors(out.log);
if(out.result.isEmpty())
return;
encoding = tool.output;
shaderBytes = out.result;
break;
}
}
}
ShaderCompileFlags flags = m_Flags;
bool found = false;
for(ShaderCompileFlag &f : flags.flags)
{
if(f.name == "@cmdline")
{
f.value = ui->toolCommandLine->toPlainText();
found = true;
break;
}
}
if(!found)
flags.flags.push_back({"@cmdline", ui->toolCommandLine->toPlainText()});
m_SaveCallback(&m_Ctx, this, encoding, flags, ui->entryFunc->text(), shaderBytes);
}
}
void ShaderViewer::on_intView_clicked()
{
ui->intView->setChecked(true);
ui->floatView->setChecked(false);
updateDebugging();
}
void ShaderViewer::on_floatView_clicked()
{
ui->floatView->setChecked(true);
ui->intView->setChecked(false);
updateDebugging();
}
void ShaderViewer::on_debugToggle_clicked()
{
if(isSourceDebugging())
gotoDisassemblyDebugging();
else
gotoSourceDebugging();
updateDebugging();
}
ScintillaEdit *ShaderViewer::currentScintilla()
{
ScintillaEdit *cur = qobject_cast<ScintillaEdit *>(QApplication::focusWidget());
if(cur == NULL)
{
for(ScintillaEdit *s : m_Scintillas)
{
if(s->isVisible())
{
cur = s;
break;
}
}
}
return cur;
}
ScintillaEdit *ShaderViewer::nextScintilla(ScintillaEdit *cur)
{
for(int i = 0; i < m_Scintillas.count(); i++)
{
if(m_Scintillas[i] == cur)
{
if(i + 1 < m_Scintillas.count())
return m_Scintillas[i + 1];
return m_Scintillas[0];
}
}
if(!m_Scintillas.isEmpty())
return m_Scintillas[0];
return NULL;
}
void ShaderViewer::find(bool down)
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
sptr_t flags = 0;
if(m_FindReplace->matchCase())
flags |= SCFIND_MATCHCASE;
if(m_FindReplace->matchWord())
flags |= SCFIND_WHOLEWORD;
if(m_FindReplace->regexp())
flags |= SCFIND_REGEXP | SCFIND_POSIX;
FindReplace::SearchContext context = m_FindReplace->context();
QString findHash = QFormatStr("%1%2%3").arg(find).arg(flags).arg((int)context);
if(findHash != m_FindState.hash)
{
m_FindState.hash = findHash;
m_FindState.start = 0;
m_FindState.end = cur->length();
m_FindState.offset = cur->currentPos();
}
int start = m_FindState.start + m_FindState.offset;
int end = m_FindState.end;
if(!down)
end = m_FindState.start;
QPair<int, int> result = cur->findText(flags, find.toUtf8().data(), start, end);
m_FindState.prevResult = result;
if(result.first == -1)
{
sptr_t maxOffset = down ? 0 : m_FindState.end;
// if we're at offset 0 searching down, there are no results. Same for offset max and searching
// up
if(m_FindState.offset == maxOffset)
return;
// otherwise, we can wrap the search around
if(context == FindReplace::AllFiles)
{
cur = nextScintilla(cur);
ToolWindowManager::raiseToolWindow(cur);
cur->activateWindow();
cur->QWidget::setFocus();
}
m_FindState.offset = maxOffset;
start = m_FindState.start + m_FindState.offset;
end = m_FindState.end;
if(!down)
end = m_FindState.start;
result = cur->findText(flags, find.toUtf8().data(), start, end);
m_FindState.prevResult = result;
if(result.first == -1)
return;
}
cur->setSelection(result.first, result.second);
ensureLineScrolled(cur, cur->lineFromPosition(result.first));
if(down)
m_FindState.offset = result.second - m_FindState.start;
else
m_FindState.offset = result.first - m_FindState.start;
}
void ShaderViewer::performFind()
{
find(m_FindReplace->direction() == FindReplace::Down);
}
void ShaderViewer::performFindAll()
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
sptr_t flags = 0;
QString results = tr("Find all \"%1\"").arg(find);
if(m_FindReplace->matchCase())
{
flags |= SCFIND_MATCHCASE;
results += tr(", Match case");
}
if(m_FindReplace->matchWord())
{
flags |= SCFIND_WHOLEWORD;
results += tr(", Match whole word");
}
if(m_FindReplace->regexp())
{
flags |= SCFIND_REGEXP | SCFIND_POSIX;
results += tr(", with Regular Expressions");
}
FindReplace::SearchContext context = m_FindReplace->context();
if(context == FindReplace::File)
results += tr(", in current file\n");
else
results += tr(", in all files\n");
// trash the find state for any incremental finds
m_FindState = FindState();
QList<ScintillaEdit *> scintillas = m_Scintillas;
if(context == FindReplace::File)
scintillas = {cur};
QList<QPair<int, int>> resultList;
QByteArray findUtf8 = find.toUtf8();
for(ScintillaEdit *s : scintillas)
{
sptr_t start = 0;
sptr_t end = s->length();
s->setIndicatorCurrent(INDICATOR_FINDRESULT);
s->indicatorClearRange(start, end);
if(findUtf8.isEmpty())
continue;
QPair<int, int> result;
do
{
result = s->findText(flags, findUtf8.data(), start, end);
if(result.first >= 0)
{
int line = s->lineFromPosition(result.first);
sptr_t lineStart = s->positionFromLine(line);
sptr_t lineEnd = s->lineEndPosition(line);
s->indicatorFillRange(result.first, result.second - result.first);
QString lineText = QString::fromUtf8(s->textRange(lineStart, lineEnd));
results += QFormatStr(" %1(%2): ").arg(s->windowTitle()).arg(line, 4);
int startPos = results.length();
results += lineText;
results += lit("\n");
resultList.push_back(
qMakePair(result.first - lineStart + startPos, result.second - lineStart + startPos));
}
start = result.second;
} while(result.first >= 0);
}
if(findUtf8.isEmpty())
return;
results += tr("Matching lines: %1").arg(resultList.count());
m_FindResults->setReadOnly(false);
m_FindResults->setText(results.toUtf8().data());
m_FindResults->setIndicatorCurrent(INDICATOR_FINDRESULT);
for(QPair<int, int> r : resultList)
m_FindResults->indicatorFillRange(r.first, r.second - r.first);
m_FindResults->setReadOnly(true);
if(m_FindResults->isVisible())
{
ToolWindowManager::raiseToolWindow(m_FindResults);
}
else
{
ui->docking->moveToolWindow(m_FindResults,
ToolWindowManager::AreaReference(ToolWindowManager::BottomOf,
ui->docking->areaOf(cur), 0.2f));
ui->docking->setToolWindowProperties(m_FindResults, ToolWindowManager::HideOnClose);
}
}
void ShaderViewer::performReplace()
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
if(find.isEmpty())
return;
sptr_t flags = 0;
if(m_FindReplace->matchCase())
flags |= SCFIND_MATCHCASE;
if(m_FindReplace->matchWord())
flags |= SCFIND_WHOLEWORD;
if(m_FindReplace->regexp())
flags |= SCFIND_REGEXP | SCFIND_POSIX;
FindReplace::SearchContext context = m_FindReplace->context();
QString findHash = QFormatStr("%1%2%3").arg(find).arg(flags).arg((int)context);
// if we didn't have a valid previous find, just do a find and bail
if(findHash != m_FindState.hash)
{
performFind();
return;
}
if(m_FindState.prevResult.first == -1)
return;
cur->setTargetRange(m_FindState.prevResult.first, m_FindState.prevResult.second);
FindState save = m_FindState;
QString replaceText = m_FindReplace->replaceText();
// otherwise we have a valid previous find. Do the replace now
// note this will invalidate the find state (as most user operations would), so we save/restore
// the state
if(m_FindReplace->regexp())
cur->replaceTargetRE(-1, replaceText.toUtf8().data());
else
cur->replaceTarget(-1, replaceText.toUtf8().data());
m_FindState = save;
// adjust the offset if we replaced text and it went up or down in size
m_FindState.offset += (replaceText.count() - find.count());
// move to the next result
performFind();
}
void ShaderViewer::performReplaceAll()
{
ScintillaEdit *cur = currentScintilla();
if(!cur)
return;
QString find = m_FindReplace->findText();
QString replace = m_FindReplace->replaceText();
if(find.isEmpty())
return;
sptr_t flags = 0;
if(m_FindReplace->matchCase())
flags |= SCFIND_MATCHCASE;
if(m_FindReplace->matchWord())
flags |= SCFIND_WHOLEWORD;
if(m_FindReplace->regexp())
flags |= SCFIND_REGEXP | SCFIND_POSIX;
FindReplace::SearchContext context = m_FindReplace->context();
(void)context;
// trash the find state for any incremental finds
m_FindState = FindState();
QList<ScintillaEdit *> scintillas = m_Scintillas;
if(context == FindReplace::File)
scintillas = {cur};
int numReplacements = 1;
for(ScintillaEdit *s : scintillas)
{
sptr_t start = 0;
sptr_t end = s->length();
QPair<int, int> result;
QByteArray findUtf8 = find.toUtf8();
QByteArray replaceUtf8 = replace.toUtf8();
do
{
result = s->findText(flags, findUtf8.data(), start, end);
if(result.first >= 0)
{
s->setTargetRange(result.first, result.second);
if(m_FindReplace->regexp())
s->replaceTargetRE(-1, replaceUtf8.data());
else
s->replaceTarget(-1, replaceUtf8.data());
numReplacements++;
}
start = result.second + (replaceUtf8.count() - findUtf8.count());
} while(result.first >= 0);
}
RDDialog::information(
this, tr("Replace all"),
tr("%1 replacements made in %2 files").arg(numReplacements).arg(scintillas.count()));
}
|