summaryrefslogtreecommitdiff
path: root/apps/plugins/lua/lstrlib.c
diff options
context:
space:
mode:
Diffstat (limited to 'apps/plugins/lua/lstrlib.c')
0 files changed, 0 insertions, 0 deletions
id='n74' href='#n74'>74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954
\cfg{text-indent}{0}
\cfg{text-width}{72}
\cfg{text-title-align}{left}
\cfg{text-chapter-align}{left}
\cfg{text-chapter-numeric}{true}
\cfg{text-chapter-suffix}{. }
\cfg{text-chapter-underline}{-}
\cfg{text-section-align}{0}{left}
\cfg{text-section-numeric}{0}{true}
\cfg{text-section-suffix}{0}{. }
\cfg{text-section-underline}{0}{-}
\cfg{text-section-align}{1}{left}
\cfg{text-section-numeric}{1}{true}
\cfg{text-section-suffix}{1}{. }
\cfg{text-section-underline}{1}{-}
\cfg{text-versionid}{0}

\cfg{html-contents-filename}{index.html}
\cfg{html-template-filename}{%k.html}
\cfg{html-index-filename}{docindex.html}
\cfg{html-leaf-level}{1}
\cfg{html-contents-depth-0}{1}
\cfg{html-contents-depth-1}{3}
\cfg{html-leaf-contains-contents}{true}

\define{dash} \u2013{-}

\title Developer documentation for Simon Tatham's puzzle collection

This is a guide to the internal structure of Simon Tatham's Portable
Puzzle Collection (henceforth referred to simply as \q{Puzzles}),
for use by anyone attempting to implement a new puzzle or port to a
new platform.

This guide is believed correct as of \cw{git} commit
\cw{a2212e82aa2f4b9a4ee22783d6fed2761c213432}. Hopefully it will be
updated along with the code in future, but if not, I've at least left
this version number in here so you can figure out what's changed by
tracking commit comments from there onwards.

\C{intro} Introduction

The Puzzles code base is divided into four parts: a set of
interchangeable front ends, a set of interchangeable back ends, a
universal \q{middle end} which acts as a buffer between the two, and
a bunch of miscellaneous utility functions. In the following
sections I give some general discussion of each of these parts.

\H{intro-frontend} Front end

The front end is the non-portable part of the code: it's the bit
that you replace completely when you port to a different platform.
So it's responsible for all system calls, all GUI interaction, and
anything else platform-specific.

The front end contains \cw{main()} or the local platform's
equivalent. Top-level control over the application's execution flow
belongs to the front end (it isn't, for example, a set of functions
called by a universal \cw{main()} somewhere else).

The front end has complete freedom to design the GUI for any given
port of Puzzles. There is no centralised mechanism for maintaining the
menu layout, for example. This has a cost in consistency (when I
\e{do} want the same menu layout on more than one platform, I have to
edit N pieces of code in parallel every time I make a change), but the
advantage is that local GUI conventions can be conformed to and local
constraints adapted to. For example, MacOS has strict human interface
guidelines which specify a different menu layout from the one I've
used on Windows and GTK; there's nothing stopping the MacOS front end
from providing a menu layout consistent with those guidelines.

Although the front end is mostly caller rather than the callee in
its interactions with other parts of the code, it is required to
implement a small API for other modules to call, mostly of drawing
functions for games to use when drawing their graphics. The drawing
API is documented in \k{drawing}; the other miscellaneous front end
API functions are documented in \k{frontend-api}.

\H{intro-backend} Back end

A \q{back end}, in this collection, is synonymous with a \q{puzzle}.
Each back end implements a different game.

At the top level, a back end is simply a data structure, containing
a few constants (flag words, preferred pixel size) and a large
number of function pointers. Back ends are almost invariably callee
rather than caller, which means there's a limitation on what a back
end can do on its own initiative.

The persistent state in a back end is divided into a number of data
structures, which are used for different purposes and therefore
likely to be switched around, changed without notice, and otherwise
updated by the rest of the code. It is important when designing a
back end to put the right pieces of data into the right structures,
or standard midend-provided features (such as Undo) may fail to
work.

The functions and variables provided in the back end data structure
are documented in \k{backend}.

\H{intro-midend} Middle end

Puzzles has a single and universal \q{middle end}. This code is
common to all platforms and all games; it sits in between the front
end and the back end and provides standard functionality everywhere.

People adding new back ends or new front ends should generally not
need to edit the middle end. On rare occasions there might be a
change that can be made to the middle end to permit a new game to do
something not currently anticipated by the middle end's present
design; however, this is terribly easy to get wrong and should
probably not be undertaken without consulting the primary maintainer
(me). Patch submissions containing unannounced mid-end changes will
be treated on their merits like any other patch; this is just a
friendly warning that mid-end changes will need quite a lot of
merits to make them acceptable.

Functionality provided by the mid-end includes:

\b Maintaining a list of game state structures and moving back and
forth along that list to provide Undo and Redo.

\b Handling timers (for move animations, flashes on completion, and
in some cases actually timing the game).

\b Handling the container format of game IDs: receiving them,
picking them apart into parameters, description and/or random seed,
and so on. The game back end need only handle the individual parts
of a game ID (encoded parameters and encoded game description);
everything else is handled centrally by the mid-end.

\b Handling standard keystrokes and menu commands, such as \q{New
Game}, \q{Restart Game} and \q{Quit}.

\b Pre-processing mouse events so that the game back ends can rely
on them arriving in a sensible order (no missing button-release
events, no sudden changes of which button is currently pressed,
etc).

\b Handling the dialog boxes which ask the user for a game ID.

\b Handling serialisation of entire games (for loading and saving a
half-finished game to a disk file; for handling application shutdown
and restart on platforms such as PalmOS where state is expected to be
saved; for storing the previous game in order to undo and redo across
a New Game event).

Thus, there's a lot of work done once by the mid-end so that
individual back ends don't have to worry about it. All the back end
has to do is cooperate in ensuring the mid-end can do its work
properly.

The API of functions provided by the mid-end to be called by the
front end is documented in \k{midend}.

\H{intro-utils} Miscellaneous utilities

In addition to these three major structural components, the Puzzles
code also contains a variety of utility modules usable by all of the
above components. There is a set of functions to provide
platform-independent random number generation; functions to make
memory allocation easier; functions which implement a balanced tree
structure to be used as necessary in complex algorithms; and a few
other miscellaneous functions. All of these are documented in
\k{utils}.

\H{intro-structure} Structure of this guide

There are a number of function call interfaces within Puzzles, and
this guide will discuss each one in a chapter of its own. After
that, \k{writing} discusses how to design new games, with some
general design thoughts and tips.

\C{backend} Interface to the back end

This chapter gives a detailed discussion of the interface that each
back end must implement.

At the top level, each back end source file exports a single global
symbol, which is a \c{const struct game} containing a large number
of function pointers and a small amount of constant data. This
structure is called by different names depending on what kind of
platform the puzzle set is being compiled on:

\b On platforms such as Windows and GTK, which build a separate
binary for each puzzle, the game structure in every back end has the
same name, \cq{thegame}; the front end refers directly to this name,
so that compiling the same front end module against a different back
end module builds a different puzzle.

\b On platforms such as MacOS X and PalmOS, which build all the
puzzles into a single monolithic binary, the game structure in each
back end must have a different name, and there's a helper module
\c{list.c} which constructs a complete list of those game structures
from a header file generated by CMake.

On the latter type of platform, source files may assume that the
preprocessor symbol \c{COMBINED} has been defined. Thus, the usual
code to declare the game structure looks something like this:

\c #ifdef COMBINED
\c #define thegame net    /* or whatever this game is called */
\e                 iii    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
\c #endif
\c 
\c const struct game thegame = {
\c     /* lots of structure initialisation in here */
\e     iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
\c };

Game back ends must also internally define a number of data
structures, for storing their various persistent state. This chapter
will first discuss the nature and use of those structures, and then
go on to give details of every element of the game structure.

\H{backend-structs} Data structures

Each game is required to define four separate data structures. This
section discusses each one and suggests what sorts of things need to
be put in it.

\S{backend-game-params} \c{game_params}

The \c{game_params} structure contains anything which affects the
automatic generation of new puzzles. So if puzzle generation is
parametrised in any way, those parameters need to be stored in
\c{game_params}.

Most puzzles currently in this collection are played on a grid of
squares, meaning that the most obvious parameter is the grid size.
Many puzzles have additional parameters; for example, Mines allows
you to control the number of mines in the grid independently of its
size, Net can be wrapping or non-wrapping, Solo has difficulty
levels and symmetry settings, and so on.

A simple rule for deciding whether a data item needs to go in
\c{game_params} is: would the user expect to be able to control this
data item from either the preset-game-types menu or the \q{Custom}
game type configuration? If so, it's part of \c{game_params}.

\c{game_params} structures are permitted to contain pointers to
subsidiary data if they need to. The back end is required to provide
functions to create and destroy \c{game_params}, and those functions
can allocate and free additional memory if necessary. (It has not
yet been necessary to do this in any puzzle so far, but the
capability is there just in case.)

\c{game_params} is also the only structure which the game's
\cw{compute_size()} function may refer to; this means that any aspect
of the game which affects the size of the window it needs to be drawn
in (other than the magnification level) must be stored in
\c{game_params}. In particular, this imposes the fundamental
limitation that random game generation may not have a random effect on
the window size: game generation algorithms are constrained to work by
starting from the grid size rather than generating it as an emergent
phenomenon. (Although this is a restriction in theory, it has not yet
seemed to be a problem.)

\S{backend-game-state} \c{game_state}

While the user is actually playing a puzzle, the \c{game_state}
structure stores all the data corresponding to the current state of
play.

The mid-end keeps \c{game_state}s in a list, and adds to the list
every time the player makes a move; the Undo and Redo functions step
back and forth through that list.

Therefore, a good means of deciding whether a data item needs to go in
\c{game_state} is: would a player expect that data item to be restored
on undo? If so, put it in \c{game_state}, and this will automatically
happen without you having to lift a finger. If not, then you might
have found a data item that needs to go in \c{game_ui} instead.

Two quite different examples of this:

\b if the game provides an interface for making moves by moving a
cursor around the grid with the keyboard and pressing some other key
when you get to a square you want to change, then the location of that
cursor belongs in \c{game_ui}, because the player will want to undo
one \e{square change} at a time, not one \e{cursor movement} at a
time.

\b Mines tracks the number of times you opened a mine square and died.
Every time you do that, you can only continue the game by pressing
Undo. So the deaths counter belongs in \c{game_ui}, because otherwise,
it would revert to 0 every time you undid your mistaken move.

During play, \c{game_state}s are often passed around without an
accompanying \c{game_params} structure. Therefore, any information
in \c{game_params} which is important during play (such as the grid
size) must be duplicated within the \c{game_state}. One simple
method of doing this is to have the \c{game_state} structure
\e{contain} a \c{game_params} structure as one of its members,
although this isn't obligatory if you prefer to do it another way.

\S{backend-game-drawstate} \c{game_drawstate}

\c{game_drawstate} carries persistent state relating to the current
graphical contents of the puzzle window. The same \c{game_drawstate}
is passed to every call to the game redraw function, so that it can
remember what it has already drawn and what needs redrawing.

A typical use for a \c{game_drawstate} is to have an array mirroring
the array of grid squares in the \c{game_state}, but describing what
was drawn in the window on the most recent redraw. This is used to
identify the squares that need redrawing next time, by deciding what
the new value in that array should be, and comparing it to what was
drawn last time. See \k{writing-howto-redraw} for more on this
subject.

\c{game_drawstate} is occasionally completely torn down and
reconstructed by the mid-end, if the user somehow forces a full
redraw. Therefore, no data should be stored in \c{game_drawstate}
which is \e{not} related to the state of the puzzle window, because
it might be unexpectedly destroyed.

The back end provides functions to create and destroy
\c{game_drawstate}, which means it can contain pointers to
subsidiary allocated data if it needs to. A common thing to want to
allocate in a \c{game_drawstate} is a \c{blitter}; see
\k{drawing-blitter} for more on this subject.

\S{backend-game-ui} \c{game_ui}

\c{game_ui} contains whatever doesn't fit into the above three
structures!

A new \c{game_ui} is created when the user begins playing a new
instance of a puzzle (i.e. during \q{New Game} or after entering a
game ID etc). It persists until the user finishes playing that game
and begins another one (or closes the window); in particular,
\q{Restart Game} does \e{not} destroy the \c{game_ui}.

\c{game_ui} is useful for implementing user-interface state which is
not part of \c{game_state}. Common examples are keyboard control
(you wouldn't want to have to separately Undo through every cursor
motion) and mouse dragging. See \k{writing-keyboard-cursor} and
\k{writing-howto-dragging}, respectively, for more details.

Another use for \c{game_ui} is to store highly persistent data such
as the Mines death counter. This is conceptually rather different:
where the Net cursor position was \e{not important enough} to
preserve for the player to restore by Undo, the Mines death counter
is \e{too important} to permit the player to revert by Undo!

A final use for \c{game_ui} is to pass information to the redraw
function about recent changes to the game state. This is used in
Mines, for example, to indicate whether a requested \q{flash} should
be a white flash for victory or a red flash for defeat; see
\k{writing-flash-types}.

\H{backend-simple} Simple data in the back end

In this section I begin to discuss each individual element in the
back end structure. To begin with, here are some simple
self-contained data elements.

\S{backend-name} \c{name}

\c const char *name;

This is a simple ASCII string giving the name of the puzzle. This
name will be used in window titles, in game selection menus on
monolithic platforms, and anywhere else that the front end needs to
know the name of a game.

\S{backend-winhelp} \c{winhelp_topic} and \c{htmlhelp_topic}

\c const char *winhelp_topic, *htmlhelp_topic;

These members are used on Windows only, to provide online help.
Although the Windows front end provides a separate binary for each
puzzle, it has a single monolithic help file; so when a user selects
\q{Help} from the menu, the program needs to open the help file and
jump to the chapter describing that particular puzzle.

This code base still supports the legacy \cw{.HLP} Windows Help format
as well as the less old \cw{.CHM} HTML Help format. The two use
different methods of identifying topics, so you have to specify both.

Each chapter about a puzzle in \c{puzzles.but} is labelled with a
\e{help topic} name for Windows Help, which typically appears just
after the \cw{\\C} chapter title paragraph, similar to this:

\c \C{net} \i{Net}
\c
\c \cfg{winhelp-topic}{games.net}

But HTML Help is able to use the Halibut identifier for the chapter
itself, i.e. the keyword that appears in braces immediatey after the
\cw{\\C}.

So the corresponding game back end encodes the \c{winhelp-topic}
string (here \cq{games.net}) in the \c{winhelp_topic} element of the
game structure, and puts the chapter identifier (here \cq{net}) in the
\c{htmlhelp_topic} element. For example:

\c const struct game thegame = {
\c    "Net", "games.net", "net",
\c    // ...
\c };

\H{backend-params} Handling game parameter sets

In this section I present the various functions which handle the
\c{game_params} structure.

\S{backend-default-params} \cw{default_params()}

\c game_params *(*default_params)(void);

This function allocates a new \c{game_params} structure, fills it
with the default values, and returns a pointer to it.

\S{backend-fetch-preset} \cw{fetch_preset()}

\c bool (*fetch_preset)(int i, char **name, game_params **params);

This function is one of the two APIs a back end can provide to
populate the \q{Type} menu, which provides a list of conveniently
accessible preset parameters for most games.

The function is called with \c{i} equal to the index of the preset
required (numbering from zero). It returns \cw{false} if that preset
does not exist (if \c{i} is less than zero or greater than the
largest preset index). Otherwise, it sets \c{*params} to point at a
newly allocated \c{game_params} structure containing the preset
information, sets \c{*name} to point at a newly allocated C string
containing the preset title (to go on the \q{Type} menu), and
returns \cw{true}.

If the game does not wish to support any presets at all, this
function is permitted to return \cw{false} always.

If the game wants to return presets in the form of a hierarchical menu
instead of a flat list (and, indeed, even if it doesn't), then it may
set this function pointer to \cw{NULL}, and instead fill in the
alternative function pointer \cw{preset_menu}
(\k{backend-preset-menu}).

\S{backend-preset-menu} \cw{preset_menu()}

\c struct preset_menu *(*preset_menu)(void);

This function is the more flexible of the two APIs by which a back end
can define a collection of preset game parameters.

This function simply returns a complete menu hierarchy, in the form of
a \c{struct preset_menu} (see \k{midend-get-presets}) and further
submenus (if it wishes) dangling off it. There are utility functions
described in \k{utils-presets} to make it easy for the back end to
construct this menu.

If the game has no need to return a hierarchy of menus, it may instead
opt to implement the \cw{fetch_preset()} function (see
\k{backend-fetch-preset}).

The game need not fill in the \c{id} fields in the preset menu
structures. The mid-end will do that after it receives the structure
from the game, and before passing it on to the front end.

\S{backend-encode-params} \cw{encode_params()}

\c char *(*encode_params)(const game_params *params, bool full);

The job of this function is to take a \c{game_params}, and encode it
in a printable ASCII string form for use in game IDs. The return value must
be a newly allocated C string, and \e{must} not contain a colon or a hash
(since those characters are used to mark the end of the parameter
section in a game ID).

Ideally, it should also not contain any other potentially
controversial punctuation; bear in mind when designing a string
parameter format that it will probably be used on both Windows and
Unix command lines under a variety of exciting shell quoting and
metacharacter rules. Sticking entirely to alphanumerics is the
safest thing; if you really need punctuation, you can probably get
away with commas, periods or underscores without causing anybody any
major inconvenience. If you venture far beyond that, you're likely
to irritate \e{somebody}.

(At the time of writing this, most existing games have purely
alphanumeric string parameter formats. Usually these involve a
letter denoting a parameter, followed optionally by a number giving
the value of that parameter, with a few mandatory parts at the
beginning such as numeric width and height separated by \cq{x}.)

If the \c{full} parameter is \cw{true}, this function should encode
absolutely everything in the \c{game_params}, such that a subsequent
call to \cw{decode_params()} (\k{backend-decode-params}) will yield
an identical structure. If \c{full} is \cw{false}, however, you
should leave out anything which is not necessary to describe a
\e{specific puzzle instance}, i.e. anything which only takes effect
when a new puzzle is \e{generated}.

For example, the Solo \c{game_params} includes a difficulty rating
used when constructing new puzzles; but a Solo game ID need not
explicitly include the difficulty, since to describe a puzzle once
generated it's sufficient to give the grid dimensions and the location
and contents of the clue squares. (Indeed, one might very easily type
in a puzzle out of a newspaper without \e{knowing} what its difficulty
level is in Solo's terminology.) Therefore, Solo's
\cw{encode_params()} only encodes the difficulty level if \c{full} is
set.

\S{backend-decode-params} \cw{decode_params()}

\c void (*decode_params)(game_params *params, char const *string);

This function is the inverse of \cw{encode_params()}
(\k{backend-encode-params}). It parses the supplied string and fills
in the supplied \c{game_params} structure. Note that the structure
will \e{already} have been allocated: this function is not expected
to create a \e{new} \c{game_params}, but to modify an existing one.

This function can receive a string which only encodes a subset of
the parameters. The most obvious way in which this can happen is if
the string was constructed by \cw{encode_params()} with its \c{full}
parameter set to \cw{false}; however, it could also happen if the
user typed in a parameter set manually and missed something out. Be
prepared to deal with a wide range of possibilities.

When dealing with a parameter which is not specified in the input
string, what to do requires a judgment call on the part of the
programmer. Sometimes it makes sense to adjust other parameters to
bring them into line with the new ones. In Mines, for example, you
would probably not want to keep the same mine count if the user
dropped the grid size and didn't specify one, since you might easily
end up with more mines than would actually fit in the grid! On the
other hand, sometimes it makes sense to leave the parameter alone: a
Solo player might reasonably expect to be able to configure size and
difficulty independently of one another.

This function currently has no direct means of returning an error if
the string cannot be parsed at all. However, the returned
\c{game_params} is almost always subsequently passed to
\cw{validate_params()} (\k{backend-validate-params}), so if you
really want to signal parse errors, you could always have a \c{char
*} in your parameters structure which stored an error message, and
have \cw{validate_params()} return it if it is non-\cw{NULL}.

\S{backend-free-params} \cw{free_params()}

\c void (*free_params)(game_params *params);

This function frees a \c{game_params} structure, and any subsidiary
allocations contained within it.

\S{backend-dup-params} \cw{dup_params()}

\c game_params *(*dup_params)(const game_params *params);

This function allocates a new \c{game_params} structure and
initialises it with an exact copy of the information in the one
provided as input. It returns a pointer to the new duplicate.

\S{backend-can-configure} \c{can_configure}

\c bool can_configure;

This data element is set to \cw{true} if the back end supports custom
parameter configuration via a dialog box. If it is \cw{true}, then the
functions \cw{configure()} and \cw{custom_params()} are expected to
work. See \k{backend-configure} and \k{backend-custom-params} for more
details.

\S{backend-configure} \cw{configure()}

\c config_item *(*configure)(const game_params *params);

This function is called when the user requests a dialog box for
custom parameter configuration. It returns a newly allocated array
of \cw{config_item} structures, describing the GUI elements required
in the dialog box. The array should have one more element than the
number of controls, since it is terminated with a \cw{C_END} marker
(see below). Each array element describes the control together with
its initial value; the front end will modify the value fields and
return the updated array to \cw{custom_params()} (see
\k{backend-custom-params}).

The \cw{config_item} structure contains the following elements:

\c const char *name;
\c int type;
\c union { /* type-specific fields */ } u;
\e         iiiiiiiiiiiiiiiiiiiiiiiiii

\c{name} is an ASCII string giving the textual label for a GUI
control. It is \e{not} expected to be dynamically allocated.

\c{type} contains one of a small number of \c{enum} values defining
what type of control is being described. The usable member of the
union field \c{u} depends on \c{type}. The valid type values are:

\dt \c{C_STRING}

\dd Describes a text input box. (This is also used for numeric
input. The back end does not bother informing the front end that the
box is numeric rather than textual; some front ends do have the
capacity to take this into account, but I decided it wasn't worth
the extra complexity in the interface.)

\lcont{

For controls of this type, \c{u.string} contains a single field

\c char *sval;

which stores a dynamically allocated string representing the contents
of the input box.

}

\dt \c{C_BOOLEAN}

\dd Describes a simple checkbox.

\lcont{

For controls of this type, \c{u.boolean} contains a single field

\c bool bval;

}

\dt \c{C_CHOICES}

\dd Describes a drop-down list presenting one of a small number of
fixed choices.

\lcont{

For controls of this type, \c{u.choices} contains two fields:

\c const char *choicenames;
\c int selected;

\c{choicenames} contains a list of strings describing the choices. The
very first character of \c{sval} is used as a delimiter when
processing the rest (so that the strings \cq{:zero:one:two},
\cq{!zero!one!two} and \cq{xzeroxonextwo} all define a three-element
list containing \cq{zero}, \cq{one} and \cq{two}).

\c{selected} contains the index of the currently selected element,
numbering from zero (so that in the above example, 0 would mean
\cq{zero} and 2 would mean \cq{two}).

Note that \c{u.choices.choicenames} is \e{not} dynamically allocated,
unlike \c{u.string.sval}.

}

\dt \c{C_END}

\dd Marks the end of the array of \c{config_item}s. There is no
associated member of the union field \c{u} for this type.

The array returned from this function is expected to have filled in
the initial values of all the controls according to the input
\c{game_params} structure.

If the game's \c{can_configure} flag is set to \cw{false}, this
function is never called and can be \cw{NULL}.

\S{backend-custom-params} \cw{custom_params()}

\c game_params *(*custom_params)(const config_item *cfg);

This function is the counterpart to \cw{configure()}
(\k{backend-configure}). It receives as input an array of
\c{config_item}s which was originally created by \cw{configure()},
but in which the control values have since been changed in
accordance with user input. Its function is to read the new values
out of the controls and return a newly allocated \c{game_params}
structure representing the user's chosen parameter set.

(The front end will have modified the controls' \e{values}, but
there will still always be the same set of controls, in the same
order, as provided by \cw{configure()}. It is not necessary to check
the \c{name} and \c{type} fields, although you could use
\cw{assert()} if you were feeling energetic.)

This function is not expected to (and indeed \e{must not}) free the
input \c{config_item} array. (If the parameters fail to validate,
the dialog box will stay open.)

If the game's \c{can_configure} flag is set to \cw{false}, this
function is never called and can be \cw{NULL}.

\S{backend-validate-params} \cw{validate_params()}

\c const char *(*validate_params)(const game_params *params,
\c                                bool full);

This function takes a \c{game_params} structure as input, and checks
that the parameters described in it fall within sensible limits. (At
the very least, grid dimensions should almost certainly be strictly
positive, for example.)

Return value is \cw{NULL} if no problems were found, or
alternatively a (non-dynamically-allocated) ASCII string describing
the error in human-readable form.

If the \c{full} parameter is set, full validation should be
performed: any set of parameters which would not permit generation
of a sensible puzzle should be faulted. If \c{full} is \e{not} set,
the implication is that these parameters are not going to be used
for \e{generating} a puzzle; so parameters which can't even sensibly
\e{describe} a valid puzzle should still be faulted, but parameters
which only affect puzzle generation should not be.

(The \c{full} option makes a difference when parameter combinations
are non-orthogonal. For example, Net has a boolean option
controlling whether it enforces a unique solution; it turns out that
it's impossible to generate a uniquely soluble puzzle with wrapping
walls and width 2, so \cw{validate_params()} will complain if you
ask for one. However, if the user had just been playing a unique
wrapping puzzle of a more sensible width, and then pastes in a game
ID acquired from somebody else which happens to describe a
\e{non}-unique wrapping width-2 puzzle, then \cw{validate_params()}
will be passed a \c{game_params} containing the width and wrapping
settings from the new game ID and the uniqueness setting from the
old one. This would be faulted, if it weren't for the fact that
\c{full} is not set during this call, so Net ignores the
inconsistency. The resulting \c{game_params} is never subsequently
used to generate a puzzle; this is a promise made by the mid-end
when it asks for a non-full validation.)

\H{backend-descs} Handling game descriptions

In this section I present the functions that deal with a textual
description of a puzzle, i.e. the part that comes after the colon in
a descriptive-format game ID.

\S{backend-new-desc} \cw{new_desc()}

\c char *(*new_desc)(const game_params *params, random_state *rs,
\c                   char **aux, bool interactive);

This function is where all the really hard work gets done. This is
the function whose job is to randomly generate a new puzzle,
ensuring solubility and uniqueness as appropriate.

As input it is given a \c{game_params} structure and a random state
(see \k{utils-random} for the random number API). It must invent a
puzzle instance, encode it in printable ASCII string form, and
return a dynamically allocated C string containing that encoding.

Additionally, it may return a second dynamically allocated string in
\c{*aux}. (If it doesn't want to, then it can leave that parameter
completely alone; it isn't required to set it to \cw{NULL}, although
doing so is harmless.) That string, if present, will be passed to
\cw{solve()} (\k{backend-solve}) later on; so if the puzzle is
generated in such a way that a solution is known, then information
about that solution can be saved in \c{*aux} for \cw{solve()} to
use.

The \c{interactive} parameter should be ignored by almost all
puzzles. Its purpose is to distinguish between generating a puzzle
within a GUI context for immediate play, and generating a puzzle in
a command-line context for saving to be played later. The only
puzzle that currently uses this distinction (and, I fervently hope,
the only one which will \e{ever} need to use it) is Mines, which
chooses a random first-click location when generating puzzles
non-interactively, but which waits for the user to place the first
click when interactive. If you think you have come up with another
puzzle which needs to make use of this parameter, please think for
at least ten minutes about whether there is \e{any} alternative!

Note that game description strings are not required to contain an
encoding of parameters such as grid size; a game description is
never separated from the \c{game_params} it was generated with, so
any information contained in that structure need not be encoded
again in the game description.

\S{backend-validate-desc} \cw{validate_desc()}

\c const char *(*validate_desc)(const game_params *params,
\c                              const char *desc);

This function is given a game description, and its job is to
validate that it describes a puzzle which makes sense.

To some extent it's up to the user exactly how far they take the
phrase \q{makes sense}; there are no particularly strict rules about
how hard the user is permitted to shoot themself in the foot when
typing in a bogus game description by hand. (For example, Rectangles
will not verify that the sum of all the numbers in the grid equals
the grid's area. So a user could enter a puzzle which was provably
not soluble, and the program wouldn't complain; there just wouldn't
happen to be any sequence of moves which solved it.)

The one non-negotiable criterion is that any game description which
makes it through \cw{validate_desc()} \e{must not} subsequently
cause a crash or an assertion failure when fed to \cw{new_game()}
and thence to the rest of the back end.

The return value is \cw{NULL} on success, or a
non-dynamically-allocated C string containing an error message.

\S{backend-new-game} \cw{new_game()}

\c game_state *(*new_game)(midend *me, const game_params *params,
\c                         const char *desc);

This function takes a game description as input, together with its
accompanying \c{game_params}, and constructs a \c{game_state}
describing the initial state of the puzzle. It returns a newly
allocated \c{game_state} structure.

Almost all puzzles should ignore the \c{me} parameter. It is
required by Mines, which needs it for later passing to
\cw{midend_supersede_game_desc()} (see \k{backend-supersede}) once
the user has placed the first click. I fervently hope that no other
puzzle will be awkward enough to require it, so everybody else
should ignore it. As with the \c{interactive} parameter in
\cw{new_desc()} (\k{backend-new-desc}), if you think you have a
reason to need this parameter, please try very hard to think of an
alternative approach!

\H{backend-states} Handling game states

This section describes the functions which create and destroy
\c{game_state} structures.

(Well, except \cw{new_game()}, which is in \k{backend-new-game}
instead of under here; but it deals with game descriptions \e{and}
game states and it had to go in one section or the other.)

\S{backend-dup-game} \cw{dup_game()}

\c game_state *(*dup_game)(const game_state *state);

This function allocates a new \c{game_state} structure and
initialises it with an exact copy of the information in the one
provided as input. It returns a pointer to the new duplicate.

\S{backend-free-game} \cw{free_game()}

\c void (*free_game)(game_state *state);

This function frees a \c{game_state} structure, and any subsidiary
allocations contained within it.

\H{backend-ui} Handling \c{game_ui}

\S{backend-new-ui} \cw{new_ui()}

\c game_ui *(*new_ui)(const game_state *state);

This function allocates and returns a new \c{game_ui} structure for
playing a particular puzzle. It is passed a pointer to the initial
\c{game_state}, in case it needs to refer to that when setting up
the initial values for the new game.

\S{backend-free-ui} \cw{free_ui()}

\c void (*free_ui)(game_ui *ui);

This function frees a \c{game_ui} structure, and any subsidiary
allocations contained within it.

\S{backend-encode-ui} \cw{encode_ui()}

\c char *(*encode_ui)(const game_ui *ui);

This function encodes any \e{important} data in a \c{game_ui}
structure in printable ASCII string form. It is only called when
saving a half-finished game to a file.

It should be used sparingly. Almost all data in a \c{game_ui} is not
important enough to save. The location of the keyboard-controlled
cursor, for example, can be reset to a default position on reloading
the game without impacting the user experience. If the user should
somehow manage to save a game while a mouse drag was in progress,
then discarding that mouse drag would be an outright \e{feature}.

A typical thing that \e{would} be worth encoding in this function is
the Mines death counter: it's in the \c{game_ui} rather than the
\c{game_state} because it's too important to allow the user to
revert it by using Undo, and therefore it's also too important to
allow the user to revert it by saving and reloading. (Of course, the
user could edit the save file by hand... But if the user is \e{that}
determined to cheat, they could just as easily modify the game's
source.)

The \cw{encode_ui()} function is optional.  If a back-end doesn't need
this function it can just set the pointer to \cw{NULL}.

\S{backend-decode-ui} \cw{decode_ui()}

\c void (*decode_ui)(game_ui *ui, const char *encoding,
\c                   const game_state *state);

This function parses a string previously output by \cw{encode_ui()},
and writes the decoded data back into the freshly-created \c{game_ui}
structure provided.  If the string is invalid, the function should do
the best it can, which might just mean not changing the \c{game_ui}
structure at all.  This might happen if a save file is corrupted, or
simply from a newer version that encodes more \c{game_ui} data.  The
current \c{game_state} is provided in case the function needs to
refer to it for validation.

Like \cw{encode_ui()}, \cw{decode_ui()} is optional.  If a back-end
doesn't need this function it can just set the pointer to \cw{NULL}.

\S{backend-changed-state} \cw{changed_state()}

\c void (*changed_state)(game_ui *ui, const game_state *oldstate,
\c                       const game_state *newstate);

This function is called by the mid-end whenever the current game
state changes, for any reason. Those reasons include:

\b a fresh move being made by \cw{interpret_move()} and
\cw{execute_move()}

\b a solve operation being performed by \cw{solve()} and
\cw{execute_move()}

\b the user moving back and forth along the undo list by means of
the Undo and Redo operations

\b the user selecting Restart to go back to the initial game state.

The job of \cw{changed_state()} is to update the \c{game_ui} for
consistency with the new game state, if any update is necessary. For
example, Same Game stores data about the currently selected tile
group in its \c{game_ui}, and this data is intrinsically related to
the game state it was derived from. So it's very likely to become
invalid when the game state changes; thus, Same Game's
\cw{changed_state()} function clears the current selection whenever
it is called.

When \cw{anim_length()} or \cw{flash_length()} are called, you can
be sure that there has been a previous call to \cw{changed_state()}.
So \cw{changed_state()} can set up data in the \c{game_ui} which will
be read by \cw{anim_length()} and \cw{flash_length()}, and those
functions will not have to worry about being called without the data
having been initialised.

\H{backend-moves} Making moves

This section describes the functions which actually make moves in
the game: that is, the functions which process user input and end up
producing new \c{game_state}s.

\S{backend-interpret-move} \cw{interpret_move()}

\c char *(*interpret_move)(const game_state *state, game_ui *ui,
\c                         const game_drawstate *ds,
\c                         int x, int y, int button);

This function receives user input and processes it. Its input
parameters are the current \c{game_state}, the current \c{game_ui}
and the current \c{game_drawstate}, plus details of the input event.
\c{button} is either an ASCII value or a special code (listed below)
indicating an arrow or function key or a mouse event; when
\c{button} is a mouse event, \c{x} and \c{y} contain the pixel
coordinates of the mouse pointer relative to the top left of the
puzzle's drawing area.

(The pointer to the \c{game_drawstate} is marked \c{const}, because
\c{interpret_move} should not write to it. The normal use of that
pointer will be to read the game's tile size parameter in order to
divide mouse coordinates by it.)

\cw{interpret_move()} may return in three different ways:

\b Returning \cw{NULL} indicates that no action whatsoever occurred
in response to the input event; the puzzle was not interested in it
at all.

\b Returning the special value \cw{UI_UPDATE} indicates that the input
event has resulted in a change being made to the \c{game_ui} which
will require a redraw of the game window, but that no actual \e{move}
was made (i.e. no new \c{game_state} needs to be created).

\b Returning anything else indicates that a move was made and that a
new \c{game_state} must be created. However, instead of actually
constructing a new \c{game_state} itself, this function is required
to return a printable ASCII string description of the details of the
move. This string will be passed to \cw{execute_move()}
(\k{backend-execute-move}) to actually create the new
\c{game_state}. (Encoding moves as strings in this way means that
the mid-end can keep the strings as well as the game states, and the
strings can be written to disk when saving the game and fed to
\cw{execute_move()} again on reloading.)

The return value from \cw{interpret_move()} is expected to be
dynamically allocated if and only if it is not either \cw{NULL}
\e{or} the special string constant \c{UI_UPDATE}.

After this function is called, the back end is permitted to rely on
some subsequent operations happening in sequence:

\b \cw{execute_move()} will be called to convert this move
description into a new \c{game_state}

\b \cw{changed_state()} will be called with the new \c{game_state}.

This means that if \cw{interpret_move()} needs to do updates to the
\c{game_ui} which are easier to perform by referring to the new
\c{game_state}, it can safely leave them to be done in
\cw{changed_state()} and not worry about them failing to happen.

(Note, however, that \cw{execute_move()} may \e{also} be called in
other circumstances. It is only \cw{interpret_move()} which can rely
on a subsequent call to \cw{changed_state()}.)

The special key codes supported by this function are:

\dt \cw{LEFT_BUTTON}, \cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}

\dd Indicate that one of the mouse buttons was pressed down.

\dt \cw{LEFT_DRAG}, \cw{MIDDLE_DRAG}, \cw{RIGHT_DRAG}

\dd Indicate that the mouse was moved while one of the mouse buttons
was still down. The mid-end guarantees that when one of these events
is received, it will always have been preceded by a button-down
event (and possibly other drag events) for the same mouse button,
and no event involving another mouse button will have appeared in
between.

\dt \cw{LEFT_RELEASE}, \cw{MIDDLE_RELEASE}, \cw{RIGHT_RELEASE}

\dd Indicate that a mouse button was released.  The mid-end
guarantees that when one of these events is received, it will always
have been preceded by a button-down event (and possibly some drag
events) for the same mouse button, and no event involving another
mouse button will have appeared in between.

\dt \cw{CURSOR_UP}, \cw{CURSOR_DOWN}, \cw{CURSOR_LEFT},
\cw{CURSOR_RIGHT}

\dd Indicate that an arrow key was pressed.

\dt \cw{CURSOR_SELECT}, \cw{CURSOR_SELECT2}

\dd On platforms which have one or two prominent \q{select} button
alongside their cursor keys, indicates that one of those buttons was
pressed.  On other platforms, these represent the Enter (or Return)
and Space keys respectively.

In addition, there are some modifiers which can be bitwise-ORed into
the \c{button} parameter:

\dt \cw{MOD_CTRL}, \cw{MOD_SHFT}

\dd These indicate that the Control or Shift key was pressed
alongside the key. They only apply to the cursor keys, not to mouse
buttons or anything else.

\dt \cw{MOD_NUM_KEYPAD}

\dd This applies to some ASCII values, and indicates that the key
code was input via the numeric keypad rather than the main keyboard.
Some puzzles may wish to treat this differently (for example, a
puzzle might want to use the numeric keypad as an eight-way
directional pad), whereas others might not (a game involving numeric
input probably just wants to treat the numeric keypad as numbers).

\dt \cw{MOD_MASK}

\dd This mask is the bitwise OR of all the available modifiers; you
can bitwise-AND with \cw{~MOD_MASK} to strip all the modifiers off
any input value.

\S{backend-execute-move} \cw{execute_move()}

\c game_state *(*execute_move)(const game_state *state, char *move);

This function takes an input \c{game_state} and a move string as
output from \cw{interpret_move()}. It returns a newly allocated
\c{game_state} which contains the result of applying the specified
move to the input game state.

This function may return \cw{NULL} if it cannot parse the move
string (and this is definitely preferable to crashing or failing an
assertion, since one way this can happen is if loading a corrupt
save file). However, it must not return \cw{NULL} for any move
string that really was output from \cw{interpret_move()}: this is
punishable by assertion failure in the mid-end.

\S{backend-can-solve} \c{can_solve}

\c bool can_solve;

This field is set to \cw{true} if the game's \cw{solve()} function
does something. If it's set to \cw{false}, the game will not even
offer the \q{Solve} menu option.

\S{backend-solve} \cw{solve()}

\c char *(*solve)(const game_state *orig, const game_state *curr,
\c                const char *aux, const char **error);

This function is called when the user selects the \q{Solve} option
from the menu.  If \cw{can_solve} is \cw{false} then it will never
be called and can be \cw{NULL}.

It is passed two input game states: \c{orig} is the game state from
the very start of the puzzle, and \c{curr} is the current one.
(Different games find one or other or both of these convenient.) It
is also passed the \c{aux} string saved by \cw{new_desc()}
(\k{backend-new-desc}), in case that encodes important information
needed to provide the solution.

If this function is unable to produce a solution (perhaps, for
example, the game has no in-built solver so it can only solve
puzzles it invented internally and has an \c{aux} string for) then
it may return \cw{NULL}. If it does this, it must also set
\c{*error} to an error message to be presented to the user (such as
\q{Solution not known for this puzzle}); that error message is not
expected to be dynamically allocated.

If this function \e{does} produce a solution, it returns a printable
ASCII move string suitable for feeding to \cw{execute_move()}
(\k{backend-execute-move}). Like a (non-empty) string returned from
\cw{interpret_move()}, the returned string should be dynamically
allocated.

\H{backend-drawing} Drawing the game graphics

This section discusses the back end functions that deal with
drawing.

\S{backend-new-drawstate} \cw{new_drawstate()}

\c game_drawstate *(*new_drawstate)(drawing *dr,
\c                                  const game_state *state);

This function allocates and returns a new \c{game_drawstate}
structure for drawing a particular puzzle. It is passed a pointer to
a \c{game_state}, in case it needs to refer to that when setting up
any initial data.

This function may not rely on the puzzle having been newly started;
a new draw state can be constructed at any time if the front end
requests a forced redraw. For games like Pattern, in which initial
game states are much simpler than general ones, this might be
important to keep in mind.

The parameter \c{dr} is a drawing object (see \k{drawing}) which the
function might need to use to allocate blitters. (However, this
isn't recommended; it's usually more sensible to wait to allocate a
blitter until \cw{set_size()} is called, because that way you can
tailor it to the scale at which the puzzle is being drawn.)

\S{backend-free-drawstate} \cw{free_drawstate()}

\c void (*free_drawstate)(drawing *dr, game_drawstate *ds);

This function frees a \c{game_drawstate} structure, and any
subsidiary allocations contained within it.

The parameter \c{dr} is a drawing object (see \k{drawing}), which
might be required if you are freeing a blitter.

\S{backend-preferred-tilesize} \c{preferred_tilesize}

\c int preferred_tilesize;

Each game is required to define a single integer parameter which
expresses, in some sense, the scale at which it is drawn. This is
described in the APIs as \cq{tilesize}, since most puzzles are on a
square (or possibly triangular or hexagonal) grid and hence a
sensible interpretation of this parameter is to define it as the
size of one grid tile in pixels; however, there's no actual
requirement that the \q{tile size} be proportional to the game
window size. Window size is required to increase monotonically with
\q{tile size}, however.

The data element \c{preferred_tilesize} indicates the tile size which
should be used in the absence of a good reason to do otherwise (such
as the screen being too small to fit the whole puzzle, or the user
explicitly requesting a resize).

\S{backend-compute-size} \cw{compute_size()}

\c void (*compute_size)(const game_params *params, int tilesize,
\c                      int *x, int *y);

This function is passed a \c{game_params} structure and a tile size.
It returns, in \c{*x} and \c{*y}, the size in pixels of the drawing
area that would be required to render a puzzle with those parameters
at that tile size.

\S{backend-set-size} \cw{set_size()}

\c void (*set_size)(drawing *dr, game_drawstate *ds,
\c                  const game_params *params, int tilesize);

This function is responsible for setting up a \c{game_drawstate} to
draw at a given tile size. Typically this will simply involve
copying the supplied \c{tilesize} parameter into a \c{tilesize}
field inside the draw state; for some more complex games it might
also involve setting up other dimension fields, or possibly
allocating a blitter (see \k{drawing-blitter}).

The parameter \c{dr} is a drawing object (see \k{drawing}), which is
required if a blitter needs to be allocated.

Back ends may assume (and may enforce by assertion) that this
function will be called at most once for any \c{game_drawstate}. If
a puzzle needs to be redrawn at a different size, the mid-end will
create a fresh drawstate.

\S{backend-colours} \cw{colours()}

\c float *(*colours)(frontend *fe, int *ncolours);

This function is responsible for telling the front end what colours
the puzzle will need to draw itself.

It returns the number of colours required in \c{*ncolours}, and the
return value from the function itself is a dynamically allocated
array of three times that many \c{float}s, containing the red, green
and blue components of each colour respectively as numbers in the
range [0,1].

The second parameter passed to this function is a front end handle.
The only things it is permitted to do with this handle are to call
the front-end function called \cw{frontend_default_colour()} (see
\k{frontend-default-colour}) or the utility function called
\cw{game_mkhighlight()} (see \k{utils-game-mkhighlight}). (The
latter is a wrapper on the former, so front end implementors only
need to provide \cw{frontend_default_colour()}.) This allows
\cw{colours()} to take local configuration into account when
deciding on its own colour allocations. Most games use the front
end's default colour as their background, apart from a few which
depend on drawing relief highlights so they adjust the background
colour if it's too light for highlights to show up against it.

The first colour in the list is slightly special. The mid-end fills
the drawing area with it before the first call to \cw{redraw()} (see
\k{backend-redraw}).  Some front ends also use it fill the part of the
puzzle window outside the puzzle.  This means that it is usually
sensible to make colour 0 the background colour for the puzzle.

Note that the colours returned from this function are for
\e{drawing}, not for printing. Printing has an entirely different
colour allocation policy.

\S{backend-anim-length} \cw{anim_length()}

\c float (*anim_length)(const game_state *oldstate,
\c                      const game_state *newstate,
\c                      int dir, game_ui *ui);

This function is called when a move is made, undone or redone. It is
given the old and the new \c{game_state}, and its job is to decide
whether the transition between the two needs to be animated or can
be instant.

\c{oldstate} is the state that was current until this call;
\c{newstate} is the state that will be current after it. \c{dir}
specifies the chronological order of those states: if it is
positive, then the transition is the result of a move or a redo (and
so \c{newstate} is the later of the two moves), whereas if it is
negative then the transition is the result of an undo (so that
\c{newstate} is the \e{earlier} move).

If this function decides the transition should be animated, it
returns the desired length of the animation in seconds. If not, it
returns zero.

State changes as a result of a Restart operation are never animated;
the mid-end will handle them internally and never consult this
function at all. State changes as a result of Solve operations are
also not animated by default, although you can change this for a
particular game by setting a flag in \c{flags} (\k{backend-flags}).

The function is also passed a pointer to the local \c{game_ui}. It
may refer to information in here to help with its decision (see
\k{writing-conditional-anim} for an example of this), and/or it may
\e{write} information about the nature of the animation which will
be read later by \cw{redraw()}.

When this function is called, it may rely on \cw{changed_state()}
having been called previously, so if \cw{anim_length()} needs to
refer to information in the \c{game_ui}, then \cw{changed_state()}
is a reliable place to have set that information up.

Move animations do not inhibit further input events. If the user
continues playing before a move animation is complete, the animation
will be abandoned and the display will jump straight to the final
state.

\S{backend-flash-length} \cw{flash_length()}

\c float (*flash_length)(const game_state *oldstate,
\c                       const game_state *newstate,
\c                       int dir, game_ui *ui);

This function is called when a move is completed. (\q{Completed}
means that not only has the move been made, but any animation which
accompanied it has finished.) It decides whether the transition from
\c{oldstate} to \c{newstate} merits a \q{flash}.

A flash is much like a move animation, but it is \e{not} interrupted
by further user interface activity; it runs to completion in
parallel with whatever else might be going on on the display. The
only thing which will rush a flash to completion is another flash.

The purpose of flashes is to indicate that the game has been
completed. They were introduced as a separate concept from move
animations because of Net: the habit of most Net players (and
certainly me) is to rotate a tile into place and immediately lock
it, then move on to another tile. When you make your last move, at
the instant the final tile is rotated into place the screen starts
to flash to indicate victory \dash but if you then press the lock
button out of habit, then the move animation is cancelled, and the
victory flash does not complete. (And if you \e{don't} press the
lock button, the completed grid will look untidy because there will
be one unlocked square.) Therefore, I introduced a specific concept
of a \q{flash} which is separate from a move animation and can
proceed in parallel with move animations and any other display
activity, so that the victory flash in Net is not cancelled by that
final locking move.

The input parameters to \cw{flash_length()} are exactly the same as
the ones to \cw{anim_length()}: see \k{backend-anim-length}.

Just like \cw{anim_length()}, when this function is called, it may
rely on \cw{changed_state()} having been called previously, so if it
needs to refer to information in the \c{game_ui} then
\cw{changed_state()} is a reliable place to have set that
information up.

(Some games use flashes to indicate defeat as well as victory;
Mines, for example, flashes in a different colour when you tread on
a mine from the colour it uses when you complete the game. In order
to achieve this, its \cw{flash_length()} function has to store a
flag in the \c{game_ui} to indicate which flash type is required.)

\S{backend-get-cursor-location} \cw{get_cursor_location()}

\c void (*get_cursor_location)(const game_ui *ui,
\c                             const game_drawstate *ds,
\c                             const game_state *state,
\c                             const game_params *params,
\c                             int *x, int *y,
\c                             int *w, int *h);

This function queries the backend for the rectangular region
containing the cursor (in games that have one), or other region of
interest.

This function is called by only
\cw{midend_get_cursor_location()} (\k{midend-get-cursor-location}). Its
purpose is to allow front ends to query the location of the backend's
cursor. With knowledge of this location, a front end can, for example,
ensure that the region of interest remains visible if the puzzle is
too big to fit on the screen at once.

On returning, \cw{*x}, \cw{*y} should be set to the X and Y
coordinates of the upper-left corner of the rectangular region of
interest, and \cw{*w} and \cw{*h} should be the width and height of
that region, respectively. In the event that a cursor is not visible
on screen, this function should return and leave the return parameters
untouched \dash the midend will notice this. The backend need not
bother checking that \cw{x}, \cw{y}, \cw{w} and \cw{h} are
non-\cw{NULL} \dash the midend guarantees that they will not be.

Defining what constitutes a \q{region of interest} is left up to the
backend. If a game provides a conventional cursor \dash such as Mines,
Solo, or any of the other grid-based games \dash the most logical
choice is of course the location of the cursor itself. However, in
other cases such as Cube or Inertia, there is no \q{cursor} in the
conventional sense \dash the player instead controls an object moving
around the screen. In these cases, it makes sense to define the region
of interest as the bounding box of the player object or another
sensible region \dash such as the grid square the player is sitting on
in Cube.

If a backend does not provide a cursor mechanism at all, the backend
is free to provide an empty implementation of this function, or a
\cw{NULL} pointer in the \cw{game} structure \dash the midend will
notice either of these cases and behave appropriately.

\S{backend-status} \cw{status()}

\c int (*status)(const game_state *state);

This function returns a status value indicating whether the current
game is still in play, or has been won, or has been conclusively lost.
The mid-end uses this to implement \cw{midend_status()}
(\k{midend-status}).

The return value should be +1 if the game has been successfully
solved. If the game has been lost in a situation where further play is
unlikely, the return value should be -1. If neither is true (so play
is still ongoing), return zero.

Front ends may wish to use a non-zero status as a cue to proactively
offer the option of starting a new game. Therefore, back ends should
not return -1 if the game has been \e{technically} lost but undoing
and continuing is still a realistic possibility.

(For instance, games with hidden information such as Guess or Mines
might well return a non-zero status whenever they reveal the solution,
whether or not the player guessed it correctly, on the grounds that a
player would be unlikely to hide the solution and continue playing
after the answer was spoiled. On the other hand, games where you can
merely get into a dead end such as Same Game or Inertia might choose
to return 0 in that situation, on the grounds that the player would
quite likely press Undo and carry on playing.)

\S{backend-redraw} \cw{redraw()}

\c void (*redraw)(drawing *dr, game_drawstate *ds,
\c                const game_state *oldstate,
\c                const game_state *newstate,
\c                int dir, const game_ui *ui,
\c                float anim_time, float flash_time);

This function is responsible for actually drawing the contents of
the game window, and for redrawing every time the game state or the
\c{game_ui} changes.

The parameter \c{dr} is a drawing object which may be passed to the
drawing API functions (see \k{drawing} for documentation of the
drawing API). This function may not save \c{dr} and use it
elsewhere; it must only use it for calling back to the drawing API
functions within its own lifetime.

\c{ds} is the local \c{game_drawstate}, of course, and \c{ui} is the
local \c{game_ui}.

\c{newstate} is the semantically-current game state, and is always
non-\cw{NULL}. If \c{oldstate} is also non-\cw{NULL}, it means that
a move has recently been made and the game is still in the process
of displaying an animation linking the old and new states; in this
situation, \c{anim_time} will give the length of time (in seconds)
that the animation has already been running. If \c{oldstate} is
\cw{NULL}, then \c{anim_time} is unused (and will hopefully be set
to zero to avoid confusion).

\c{dir} specifies the chronological order of those states: if it is
positive, then the transition is the result of a move or a redo (and
so \c{newstate} is the later of the two moves), whereas if it is
negative then the transition is the result of an undo (so that
\c{newstate} is the \e{earlier} move). This allows move animations
that are not time-symmetric (such as Inertia, where gems are consumed
during the animation) to be drawn the right way round.

\c{flash_time}, if it is is non-zero, denotes that the game is in
the middle of a flash, and gives the time since the start of the
flash. See \k{backend-flash-length} for general discussion of
flashes.

The very first time this function is called for a new
\c{game_drawstate}, it is expected to redraw the \e{entire} drawing
area. Since this often involves drawing visual furniture which is
never subsequently altered, it is often simplest to arrange this by
having a special \q{first time} flag in the draw state, and
resetting it after the first redraw.  This function can assume that
the mid-end has filled the drawing area with colour 0 before the first
call.

When this function (or any subfunction) calls the drawing API, it is
expected to pass colour indices which were previously defined by the
\cw{colours()} function.

\H{backend-printing} Printing functions

This section discusses the back end functions that deal with
printing puzzles out on paper.

\S{backend-can-print} \c{can_print}

\c bool can_print;

This flag is set to \cw{true} if the puzzle is capable of printing
itself on paper. (This makes sense for some puzzles, such as Solo,
which can be filled in with a pencil. Other puzzles, such as
Twiddle, inherently involve moving things around and so would not
make sense to print.)

If this flag is \cw{false}, then the functions \cw{print_size()}
and \cw{print()} will never be called and can be \cw{NULL}.

\S{backend-can-print-in-colour} \c{can_print_in_colour}

\c bool can_print_in_colour;

This flag is set to \cw{true} if the puzzle is capable of printing
itself differently when colour is available. For example, Map can
actually print coloured regions in different \e{colours} rather than
resorting to cross-hatching.

If the \c{can_print} flag is \cw{false}, then this flag will be
ignored.

\S{backend-print-size} \cw{print_size()}

\c void (*print_size)(const game_params *params, float *x, float *y);

This function is passed a \c{game_params} structure and a tile size.
It returns, in \c{*x} and \c{*y}, the preferred size in
\e{millimetres} of that puzzle if it were to be printed out on paper.

If the \c{can_print} flag is \cw{false}, this function will never be
called.

\S{backend-print} \cw{print()}

\c void (*print)(drawing *dr, const game_state *state, int tilesize);

This function is called when a puzzle is to be printed out on paper.
It should use the drawing API functions (see \k{drawing}) to print
itself.

This function is separate from \cw{redraw()} because it is often
very different:

\b The printing function may not depend on pixel accuracy, since
printer resolution is variable. Draw as if your canvas had infinite
resolution.

\b The printing function sometimes needs to display things in a
completely different style. Net, for example, is very different as
an on-screen puzzle and as a printed one.

\b The printing function is often much simpler since it has no need
to deal with repeated partial redraws.

However, there's no reason the printing and redraw functions can't
share some code if they want to.

When this function (or any subfunction) calls the drawing API, the
colour indices it passes should be colours which have been allocated
by the \cw{print_*_colour()} functions within this execution of
\cw{print()}. This is very different from the fixed small number of
colours used in \cw{redraw()}, because printers do not have a
limitation on the total number of colours that may be used. Some
puzzles' printing functions might wish to allocate only one \q{ink}
colour and use it for all drawing; others might wish to allocate
\e{more} colours than are used on screen.

One possible colour policy worth mentioning specifically is that a
puzzle's printing function might want to allocate the \e{same}
colour indices as are used by the redraw function, so that code
shared between drawing and printing does not have to keep switching
its colour indices. In order to do this, the simplest thing is to
make use of the fact that colour indices returned from
\cw{print_*_colour()} are guaranteed to be in increasing order from
zero. So if you have declared an \c{enum} defining three colours
\cw{COL_BACKGROUND}, \cw{COL_THIS} and \cw{COL_THAT}, you might then
write

\c int c;
\c c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
\c c = print_mono_colour(dr, 0); assert(c == COL_THIS);
\c c = print_mono_colour(dr, 0); assert(c == COL_THAT);

If the \c{can_print} flag is \cw{false}, this function will never be
called.

\H{backend-misc} Miscellaneous

\S{backend-can-format-as-text-ever} \c{can_format_as_text_ever}

\c bool can_format_as_text_ever;

This field is \cw{true} if the game supports formatting a
game state as ASCII text (typically ASCII art) for copying to the
clipboard and pasting into other applications. If it is \cw{false},
front ends will not offer the \q{Copy} command at all.

If this field is \cw{true}, the game does not necessarily have to
support text formatting for \e{all} games: e.g. a game which can be
played on a square grid or a triangular one might only support copy
and paste for the former, because triangular grids in ASCII art are
just too difficult.

If this field is \cw{false}, the functions
\cw{can_format_as_text_now()} (\k{backend-can-format-as-text-now})
and \cw{text_format()} (\k{backend-text-format}) are never called
and can be \cw{NULL}.

\S{backend-can-format-as-text-now} \c{can_format_as_text_now()}

\c bool (*can_format_as_text_now)(const game_params *params);

This function is passed a \c{game_params}, and returns \cw{true} if
the game can support ASCII text output for this particular game type.
If it returns \cw{false}, front ends will grey out or otherwise
disable the \q{Copy} command.

Games may enable and disable the copy-and-paste function for
different game \e{parameters}, but are currently constrained to
return the same answer from this function for all game \e{states}
sharing the same parameters. In other words, the \q{Copy} function
may enable or disable itself when the player changes game preset,
but will never change during play of a single game or when another
game of exactly the same type is generated.

This function should not take into account aspects of the game
parameters which are not encoded by \cw{encode_params()}
(\k{backend-encode-params}) when the \c{full} parameter is set to
\cw{false}. Such parameters will not necessarily match up between a
call to this function and a subsequent call to \cw{text_format()}
itself. (For instance, game \e{difficulty} should not affect whether
the game can be copied to the clipboard. Only the actual visible
\e{shape} of the game can affect that.)

\S{backend-text-format} \cw{text_format()}

\c char *(*text_format)(const game_state *state);

This function is passed a \c{game_state}, and returns a newly
allocated C string containing an ASCII representation of that game
state. It is used to implement the \q{Copy} operation in many front
ends.

This function will only ever be called if the back end field
\c{can_format_as_text_ever} (\k{backend-can-format-as-text-ever}) is
\cw{true} \e{and} the function \cw{can_format_as_text_now()}
(\k{backend-can-format-as-text-now}) has returned \cw{true} for the
currently selected game parameters.

The returned string may contain line endings (and will probably want
to), using the normal C internal \cq{\\n} convention. For
consistency between puzzles, all multi-line textual puzzle
representations should \e{end} with a newline as well as containing
them internally. (There are currently no puzzles which have a
one-line ASCII representation, so there's no precedent yet for
whether that should come with a newline or not.)

\S{backend-wants-statusbar} \cw{wants_statusbar}

\c bool wants_statusbar;

This field is set to \cw{true} if the puzzle has a use for a textual
status line (to display score, completion status, currently active
tiles, etc). If the \c{redraw()} function ever intends to call
\c{status_bar()} in the drawing API (\k{drawing-status-bar}), then it
should set this flag to \c{true}.

\S{backend-is-timed} \c{is_timed}

\c bool is_timed;

This field is \cw{true} if the puzzle is time-critical. If
so, the mid-end will maintain a game timer while the user plays.

If this field is \cw{false}, then \cw{timing_state()} will never be
called and can be \cw{NULL}.

\S{backend-timing-state} \cw{timing_state()}

\c bool (*timing_state)(const game_state *state, game_ui *ui);

This function is passed the current \c{game_state} and the local
\c{game_ui}; it returns \cw{true} if the game timer should currently
be running.

A typical use for the \c{game_ui} in this function is to note when
the game was first completed (by setting a flag in
\cw{changed_state()} \dash see \k{backend-changed-state}), and
freeze the timer thereafter so that the user can undo back through
their solution process without altering their time.

\S{backend-request-keys} \cw{request_keys()}

\c key_label *(*request_keys)(const game_params *params, int *nkeys);

This function returns a dynamically allocated array of \cw{key_label}
items containing the buttons the back end deems absolutely
\e{necessary} for gameplay, not an exhaustive list of every button the
back end could accept. For example, Keen only returns the digits up to
the game size and the backspace character, \cw{\\b}, even though it
\e{could} accept \cw{M}, as only these buttons are actually needed to
play the game. Each \cw{key_label} item contains the following fields:

\c struct key_label {
\c     char *label; /* label for frontend use */
\c     int button; /* button to pass to midend */
\c } key_label;

The \cw{label} field of this structure can (and often will) be set by
the backend to \cw{NULL}, in which case the midend will instead call
\c{button2label()} (\k{utils-button2label}) and fill in a generic
label. The \cw{button} field is the associated code that can be passed
to the midend when the frontend deems appropriate.

If \cw{label} is not \cw{NULL}, then it's a dynamically allocated
string. Therefore, freeing an array of these structures needs more
than just a single free operatio. The function \c{free_keys()}
(\k{utils-free-keys}) can be used to free a whole array of these
structures conveniently.

The backend should set \cw{*nkeys} to the number of elements in the
returned array.

The field for this function point in the \cw{game} structure might be
set to \cw{NULL} (and indeed it is for the majority of the games) to
indicate that no additional buttons (apart from the cursor keys) are
required to play the game.

This function should not be called directly by frontends. Instead,
frontends should use \cw{midend_request_keys()}
(\k{midend-request-keys}).

\S{backend-current-key-label} \cw{current_key_label()}

\c const char *(*current_key_label)(const game_ui *ui,
\c                                  const game_state *state,
\c                                  int button);

This function is called to ask the back-end how certain keys should be
labelled on platforms (such a feature phones) where this is
conventional.
These labels are expected to reflect what the keys will do right now,
so they can change depending on the game and UI state.

The \c{ui} and \c{state} arguments describe the state of the game for
which key labels are required.
The \c{button} argument is the same as the one passed to
\cw{interpret_move()}.
At present, the only values of \c{button} that can be passed to
\cw{current_key_label()} are \cw{CURSOR_SELECT} and \cw{CURSOR_SELECT2}.
The return value is a short string describing what the requested key
will do if pressed.
Usually the string should be a static string constant.
If it's really necessary to use a dynamically-allocated string, it
should remain valid until the next call to \cw{current_key_label()} or
\cw{free_ui()} with the same \cw{game_ui} (so it can be referenced from
the \cw{game_ui} and freed at the next one of those calls).

There's no fixed upper limit on the length of string that this
function can return, but more than about 12 characters is likely to
cause problems for front-ends.  If two buttons have the same effect,
their labels should be identical so that the front end can detect
this.  Similarly, keys that do different things should have different
labels.  The label should be an empty string (\cw{""}) if the key does
nothing.

Like \cw{request_keys()}, the \cw{current_key_label} pointer in the
\c{game} structure is allowed to be \cw{NULL}, in which case the
mid-end will treat it as though it always returned \cw{""}.

\S{backend-flags} \c{flags}

\c int flags;

This field contains miscellaneous per-backend flags. It consists of
the bitwise OR of some combination of the following:

\dt \cw{BUTTON_BEATS(x,y)}

\dd Given any \cw{x} and \cw{y} from the set \{\cw{LEFT_BUTTON},
\cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}\}, this macro evaluates to a
bit flag which indicates that when buttons \cw{x} and \cw{y} are
both pressed simultaneously, the mid-end should consider \cw{x} to
have priority. (In the absence of any such flags, the mid-end will
always consider the most recently pressed button to have priority.)

\dt \cw{SOLVE_ANIMATES}

\dd This flag indicates that moves generated by \cw{solve()}
(\k{backend-solve}) are candidates for animation just like any other
move. For most games, solve moves should not be animated, so the
mid-end doesn't even bother calling \cw{anim_length()}
(\k{backend-anim-length}), thus saving some special-case code in
each game. On the rare occasion that animated solve moves are
actually required, you can set this flag.

\dt \cw{REQUIRE_RBUTTON}

\dd This flag indicates that the puzzle cannot be usefully played
without the use of mouse buttons other than the left one. On some
PDA platforms, this flag is used by the front end to enable
right-button emulation through an appropriate gesture. Note that a
puzzle is not required to set this just because it \e{uses} the
right button, but only if its use of the right button is critical to
playing the game. (Slant, for example, uses the right button to
cycle through the three square states in the opposite order from the
left button, and hence can manage fine without it.)

\dt \cw{REQUIRE_NUMPAD}

\dd This flag indicates that the puzzle cannot be usefully played
without the use of number-key input. On some PDA platforms it causes
an emulated number pad to appear on the screen. Similarly to
\cw{REQUIRE_RBUTTON}, a puzzle need not specify this simply if its
use of the number keys is not critical.

\H{backend-initiative} Things a back end may do on its own initiative

This section describes a couple of things that a back end may choose
to do by calling functions elsewhere in the program, which would not
otherwise be obvious.

\S{backend-newrs} Create a random state

If a back end needs random numbers at some point during normal play,
it can create a fresh \c{random_state} by first calling
\c{get_random_seed} (\k{frontend-get-random-seed}) and then passing
the returned seed data to \cw{random_new()}.

This is likely not to be what you want. If a puzzle needs randomness
in the middle of play, it's likely to be more sensible to store some
sort of random state within the \c{game_state}, so that the random
numbers are tied to the particular game state and hence the player
can't simply keep undoing their move until they get numbers they
like better.

This facility is currently used only in Net, to implement the
\q{jumble} command, which sets every unlocked tile to a new random
orientation. This randomness \e{is} a reasonable use of the feature,
because it's non-adversarial \dash there's no advantage to the user
in getting different random numbers.

\S{backend-supersede} Supersede its own game description

In response to a move, a back end is (reluctantly) permitted to call
\cw{midend_supersede_game_desc()}:

\c void midend_supersede_game_desc(midend *me,
\c                                 char *desc, char *privdesc);

When the user selects \q{New Game}, the mid-end calls
\cw{new_desc()} (\k{backend-new-desc}) to get a new game
description, and (as well as using that to generate an initial game
state) stores it for the save file and for telling to the user. The
function above overwrites that game description, and also splits it
in two. \c{desc} becomes the new game description which is provided
to the user on request, and is also the one used to construct a new
initial game state if the user selects \q{Restart}. \c{privdesc} is
a \q{private} game description, used to reconstruct the game's
initial state when reloading.

The distinction between the two, as well as the need for this
function at all, comes from Mines. Mines begins with a blank grid
and no idea of where the mines actually are; \cw{new_desc()} does
almost no work in interactive mode, and simply returns a string
encoding the \c{random_state}. When the user first clicks to open a
tile, \e{then} Mines generates the mine positions, in such a way
that the game is soluble from that starting point. Then it uses this
function to supersede the random-state game description with a
proper one. But it needs two: one containing the initial click
location (because that's what you want to happen if you restart the
game, and also what you want to send to a friend so that they play
\e{the same game} as you), and one without the initial click
location (because when you save and reload the game, you expect to
see the same blank initial state as you had before saving).

I should stress again that this function is a horrid hack. Nobody
should use it if they're not Mines; if you think you need to use it,
think again repeatedly in the hope of finding a better way to do
whatever it was you needed to do.

\C{drawing} The drawing API

The back end function \cw{redraw()} (\k{backend-redraw}) is required
to draw the puzzle's graphics on the window's drawing area. The back
end function \cw{print()} similarly draws the puzzle on paper, if the
puzzle is printable. To do this portably, the back end is provided
with a drawing API allowing it to talk directly to the front end. In
this chapter I document that API, both for the benefit of back end
authors trying to use it and for front end authors trying to implement
it.

The drawing API as seen by the back end is a collection of global
functions, each of which takes a pointer to a \c{drawing} structure
(a \q{drawing object}). These objects are supplied as parameters to
the back end's \cw{redraw()} and \cw{print()} functions.

In fact these global functions are not implemented directly by the
front end; instead, they are implemented centrally in \c{drawing.c}
and form a small piece of middleware. The drawing API as supplied by
the front end is a structure containing a set of function pointers,
plus a \cq{void *} handle which is passed to each of those
functions. This enables a single front end to switch between
multiple implementations of the drawing API if necessary. For
example, the Windows API supplies a printing mechanism integrated
into the same GDI which deals with drawing in windows, and therefore
the same API implementation can handle both drawing and printing;
but on Unix, the most common way for applications to print is by
producing PostScript output directly, and although it would be
\e{possible} to write a single (say) \cw{draw_rect()} function which
checked a global flag to decide whether to do GTK drawing operations
or output PostScript to a file, it's much nicer to have two separate
functions and switch between them as appropriate.

When drawing, the puzzle window is indexed by pixel coordinates,
with the top left pixel defined as \cw{(0,0)} and the bottom right
pixel \cw{(w-1,h-1)}, where \c{w} and \c{h} are the width and height
values returned by the back end function \cw{compute_size()}
(\k{backend-compute-size}).

When printing, the puzzle's print area is indexed in exactly the
same way (with an arbitrary tile size provided by the printing
module \c{printing.c}), to facilitate sharing of code between the
drawing and printing routines. However, when printing, puzzles may
no longer assume that the coordinate unit has any relationship to a
pixel; the printer's actual resolution might very well not even be
known at print time, so the coordinate unit might be smaller or
larger than a pixel. Puzzles' print functions should restrict
themselves to drawing geometric shapes rather than fiddly pixel
manipulation.

\e{Puzzles' redraw functions may assume that the surface they draw
on is persistent}. It is the responsibility of every front end to
preserve the puzzle's window contents in the face of GUI window
expose issues and similar. It is not permissible to request that the
back end redraw any part of a window that it has already drawn,
unless something has actually changed as a result of making moves in
the puzzle.

Most front ends accomplish this by having the drawing routines draw
on a stored bitmap rather than directly on the window, and copying
the bitmap to the window every time a part of the window needs to be
redrawn. Therefore, it is vitally important that whenever the back
end does any drawing it informs the front end of which parts of the
window it has accessed, and hence which parts need repainting. This
is done by calling \cw{draw_update()} (\k{drawing-draw-update}).

Persistence of old drawing is convenient. However, a puzzle should
be very careful about how it updates its drawing area. The problem
is that some front ends do anti-aliased drawing: rather than simply
choosing between leaving each pixel untouched or painting it a
specified colour, an antialiased drawing function will \e{blend} the
original and new colours in pixels at a figure's boundary according
to the proportion of the pixel occupied by the figure (probably
modified by some heuristic fudge factors). All of this produces a
smoother appearance for curves and diagonal lines.

An unfortunate effect of drawing an anti-aliased figure repeatedly
is that the pixels around the figure's boundary come steadily more
saturated with \q{ink} and the boundary appears to \q{spread out}.
Worse, redrawing a figure in a different colour won't fully paint
over the old boundary pixels, so the end result is a rather ugly
smudge.

A good strategy to avoid unpleasant anti-aliasing artifacts is to
identify a number of rectangular areas which need to be redrawn,
clear them to the background colour, and then redraw their contents
from scratch, being careful all the while not to stray beyond the
boundaries of the original rectangles. The \cw{clip()} function
(\k{drawing-clip}) comes in very handy here. Games based on a square
grid can often do this fairly easily. Other games may need to be
somewhat more careful. For example, Loopy's redraw function first
identifies portions of the display which need to be updated. Then,
if the changes are fairly well localised, it clears and redraws a
rectangle containing each changed area. Otherwise, it gives up and
redraws the entire grid from scratch.

It is possible to avoid clearing to background and redrawing from
scratch if one is very careful about which drawing functions one
uses: if a function is documented as not anti-aliasing under some
circumstances, you can rely on each pixel in a drawing either being
left entirely alone or being set to the requested colour, with no
blending being performed.

In the following sections I first discuss the drawing API as seen by
the back end, and then the \e{almost} identical function-pointer
form seen by the front end.

\H{drawing-backend} Drawing API as seen by the back end

This section documents the back-end drawing API, in the form of
functions which take a \c{drawing} object as an argument.

\S{drawing-draw-rect} \cw{draw_rect()}

\c void draw_rect(drawing *dr, int x, int y, int w, int h,
\c                int colour);

Draws a filled rectangle in the puzzle window.

\c{x} and \c{y} give the coordinates of the top left pixel of the
rectangle. \c{w} and \c{h} give its width and height. Thus, the
horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
inclusive, and the vertical extent from \c{y} to \c{y+h-1}
inclusive.

\c{colour} is an integer index into the colours array returned by
the back end function \cw{colours()} (\k{backend-colours}).

There is no separate pixel-plotting function. If you want to plot a
single pixel, the approved method is to use \cw{draw_rect()} with
width and height set to 1.

Unlike many of the other drawing functions, this function is
guaranteed to be pixel-perfect: the rectangle will be sharply
defined and not anti-aliased or anything like that.

This function may be used for both drawing and printing.

\S{drawing-draw-rect-outline} \cw{draw_rect_outline()}

\c void draw_rect_outline(drawing *dr, int x, int y, int w, int h,
\c                        int colour);

Draws an outline rectangle in the puzzle window.

\c{x} and \c{y} give the coordinates of the top left pixel of the
rectangle. \c{w} and \c{h} give its width and height. Thus, the
horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
inclusive, and the vertical extent from \c{y} to \c{y+h-1}
inclusive.

\c{colour} is an integer index into the colours array returned by
the back end function \cw{colours()} (\k{backend-colours}).

From a back end perspective, this function may be considered to be
part of the drawing API. However, front ends are not required to
implement it, since it is actually implemented centrally (in
\cw{misc.c}) as a wrapper on \cw{draw_polygon()}.

This function may be used for both drawing and printing.

\S{drawing-draw-rect-corner} \cw{draw_rect_corners()}

\c void draw_rect_corners(drawing *dr, int cx, int cy, int r, int col);

Draws four L-shapes at the corners of a square, in the manner of a
target reticule. This is a convenience function for back ends to use
to display a keyboard cursor (if they want one in that style).

\c{cx} and \c{cy} give the coordinates of the centre of the square.
\c{r} is half the side length of the square, so that the corners are
at \cw{(cx-r,cy-r)}, \cw{(cx+r,cy-r)}, \cw{(cx-r,cy+r)} and
\cw{(cx+r,cy+r)}.

\c{colour} is an integer index into the colours array returned by
the back end function \cw{colours()} (\k{backend-colours}).

\S{drawing-draw-line} \cw{draw_line()}

\c void draw_line(drawing *dr, int x1, int y1, int x2, int y2,
\c                int colour);

Draws a straight line in the puzzle window.

\c{x1} and \c{y1} give the coordinates of one end of the line.
\c{x2} and \c{y2} give the coordinates of the other end. The line
drawn includes both those points.

\c{colour} is an integer index into the colours array returned by
the back end function \cw{colours()} (\k{backend-colours}).

Some platforms may perform anti-aliasing on this function.
Therefore, do not assume that you can erase a line by drawing the
same line over it in the background colour; anti-aliasing might lead
to perceptible ghost artefacts around the vanished line. Horizontal
and vertical lines, however, are pixel-perfect and not anti-aliased.

This function may be used for both drawing and printing.

\S{drawing-draw-polygon} \cw{draw_polygon()}

\c void draw_polygon(drawing *dr, const int *coords, int npoints,
\c                   int fillcolour, int outlinecolour);

Draws an outlined or filled polygon in the puzzle window.

\c{coords} is an array of \cw{(2*npoints)} integers, containing the
\c{x} and \c{y} coordinates of \c{npoints} vertices.

\c{fillcolour} and \c{outlinecolour} are integer indices into the
colours array returned by the back end function \cw{colours()}
(\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
indicate that the polygon should be outlined only.

The polygon defined by the specified list of vertices is first
filled in \c{fillcolour}, if specified, and then outlined in
\c{outlinecolour}.

\c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
(and front ends are permitted to enforce this by assertion). This is
because different platforms disagree on whether a filled polygon
should include its boundary line or not, so drawing \e{only} a
filled polygon would have non-portable effects. If you want your
filled polygon not to have a visible outline, you must set
\c{outlinecolour} to the same as \c{fillcolour}.

Some platforms may perform anti-aliasing on this function.
Therefore, do not assume that you can erase a polygon by drawing the
same polygon over it in the background colour. Also, be prepared for
the polygon to extend a pixel beyond its obvious bounding box as a
result of this; if you really need it not to do this to avoid
interfering with other delicate graphics, you should probably use
\cw{clip()} (\k{drawing-clip}). You can rely on horizontal and
vertical lines not being anti-aliased.

This function may be used for both drawing and printing.

\S{drawing-draw-circle} \cw{draw_circle()}

\c void draw_circle(drawing *dr, int cx, int cy, int radius,
\c                  int fillcolour, int outlinecolour);

Draws an outlined or filled circle in the puzzle window.

\c{cx} and \c{cy} give the coordinates of the centre of the circle.
\c{radius} gives its radius. The total horizontal pixel extent of
the circle is from \c{cx-radius+1} to \c{cx+radius-1} inclusive, and
the vertical extent similarly around \c{cy}.

\c{fillcolour} and \c{outlinecolour} are integer indices into the
colours array returned by the back end function \cw{colours()}
(\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
indicate that the circle should be outlined only.

The circle is first filled in \c{fillcolour}, if specified, and then
outlined in \c{outlinecolour}.

\c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
(and front ends are permitted to enforce this by assertion). This is
because different platforms disagree on whether a filled circle
should include its boundary line or not, so drawing \e{only} a
filled circle would have non-portable effects. If you want your
filled circle not to have a visible outline, you must set
\c{outlinecolour} to the same as \c{fillcolour}.

Some platforms may perform anti-aliasing on this function.
Therefore, do not assume that you can erase a circle by drawing the
same circle over it in the background colour. Also, be prepared for
the circle to extend a pixel beyond its obvious bounding box as a
result of this; if you really need it not to do this to avoid
interfering with other delicate graphics, you should probably use
\cw{clip()} (\k{drawing-clip}).

This function may be used for both drawing and printing.

\S{drawing-draw-thick-line} \cw{draw_thick_line()}

\c void draw_thick_line(drawing *dr, float thickness,
\c                      float x1, float y1, float x2, float y2,
\c                      int colour)

Draws a line in the puzzle window, giving control over the line's
thickness.

\c{x1} and \c{y1} give the coordinates of one end of the line.
\c{x2} and \c{y2} give the coordinates of the other end.
\c{thickness} gives the thickness of the line, in pixels.

Note that the coordinates and thickness are floating-point: the
continuous coordinate system is in effect here. It's important to
be able to address points with better-than-pixel precision in this
case, because one can't otherwise properly express the endpoints of
lines with both odd and even thicknesses.

Some platforms may perform anti-aliasing on this function. The
precise pixels affected by a thick-line drawing operation may vary
between platforms, and no particular guarantees are provided.
Indeed, even horizontal or vertical lines may be anti-aliased.

This function may be used for both drawing and printing.

If the specified thickness is less than 1.0, 1.0 is used.
This ensures that thin lines are visible even at small scales.

\S{drawing-draw-text} \cw{draw_text()}

\c void draw_text(drawing *dr, int x, int y, int fonttype,
\c                int fontsize, int align, int colour,
\c                const char *text);

Draws text in the puzzle window.

\c{x} and \c{y} give the coordinates of a point. The relation of
this point to the location of the text is specified by \c{align},
which is a bitwise OR of horizontal and vertical alignment flags:

\dt \cw{ALIGN_VNORMAL}

\dd Indicates that \c{y} is aligned with the baseline of the text.

\dt \cw{ALIGN_VCENTRE}

\dd Indicates that \c{y} is aligned with the vertical centre of the
text. (In fact, it's aligned with the vertical centre of normal
\e{capitalised} text: displaying two pieces of text with
\cw{ALIGN_VCENTRE} at the same \cw{y}-coordinate will cause their
baselines to be aligned with one another, even if one is an ascender
and the other a descender.)

\dt \cw{ALIGN_HLEFT}

\dd Indicates that \c{x} is aligned with the left-hand end of the
text.

\dt \cw{ALIGN_HCENTRE}

\dd Indicates that \c{x} is aligned with the horizontal centre of
the text.

\dt \cw{ALIGN_HRIGHT}

\dd Indicates that \c{x} is aligned with the right-hand end of the
text.

\c{fonttype} is either \cw{FONT_FIXED} or \cw{FONT_VARIABLE}, for a
monospaced or proportional font respectively. (No more detail than
that may be specified; it would only lead to portability issues
between different platforms.)

\c{fontsize} is the desired size, in pixels, of the text. This size
corresponds to the overall point size of the text, not to any
internal dimension such as the cap-height.

\c{colour} is an integer index into the colours array returned by
the back end function \cw{colours()} (\k{backend-colours}).

This function may be used for both drawing and printing.

The character set used to encode the text passed to this function is
specified \e{by the drawing object}, although it must be a superset
of ASCII. If a puzzle wants to display text that is not contained in
ASCII, it should use the \cw{text_fallback()} function
(\k{drawing-text-fallback}) to query the drawing object for an
appropriate representation of the characters it wants.

\S{drawing-text-fallback} \cw{text_fallback()}

\c char *text_fallback(drawing *dr, const char *const *strings,
\c                     int nstrings);

This function is used to request a translation of UTF-8 text into
whatever character encoding is expected by the drawing object's
implementation of \cw{draw_text()}.

The input is a list of strings encoded in UTF-8: \cw{nstrings} gives
the number of strings in the list, and \cw{strings[0]},
\cw{strings[1]}, ..., \cw{strings[nstrings-1]} are the strings
themselves.

The returned string (which is dynamically allocated and must be
freed when finished with) is derived from the first string in the
list that the drawing object expects to be able to display reliably;
it will consist of that string translated into the character set
expected by \cw{draw_text()}.

Drawing implementations are not required to handle anything outside
ASCII, but are permitted to assume that \e{some} string will be
successfully translated. So every call to this function must include
a string somewhere in the list (presumably the last element) which
consists of nothing but ASCII, to be used by any front end which
cannot handle anything else.

For example, if a puzzle wished to display a string including a
multiplication sign (U+00D7 in Unicode, represented by the bytes C3
97 in UTF-8), it might do something like this:

\c static const char *const times_signs[] = { "\xC3\x97", "x" };
\c char *times_sign = text_fallback(dr, times_signs, 2);
\c sprintf(buffer, "%d%s%d", width, times_sign, height);
\c sfree(times_sign);
\c draw_text(dr, x, y, font, size, align, colour, buffer);
\c sfree(buffer);

which would draw a string with a times sign in the middle on
platforms that support it, and fall back to a simple ASCII \cq{x}
where there was no alternative.

\S{drawing-clip} \cw{clip()}

\c void clip(drawing *dr, int x, int y, int w, int h);

Establishes a clipping rectangle in the puzzle window.

\c{x} and \c{y} give the coordinates of the top left pixel of the
clipping rectangle. \c{w} and \c{h} give its width and height. Thus,
the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
inclusive, and the vertical extent from \c{y} to \c{y+h-1}
inclusive. (These are exactly the same semantics as
\cw{draw_rect()}.)

After this call, no drawing operation will affect anything outside
the specified rectangle. The effect can be reversed by calling
\cw{unclip()} (\k{drawing-unclip}). The clipping rectangle is
pixel-perfect: pixels within the rectangle are affected as usual by
drawing functions; pixels outside are completely untouched.

Back ends should not assume that a clipping rectangle will be
automatically cleared up by the front end if it's left lying around;
that might work on current front ends, but shouldn't be relied upon.
Always explicitly call \cw{unclip()}.

This function may be used for both drawing and printing.

\S{drawing-unclip} \cw{unclip()}

\c void unclip(drawing *dr);

Reverts the effect of a previous call to \cw{clip()}. After this
call, all drawing operations will be able to affect the entire
puzzle window again.

This function may be used for both drawing and printing.

\S{drawing-draw-update} \cw{draw_update()}

\c void draw_update(drawing *dr, int x, int y, int w, int h);

Informs the front end that a rectangular portion of the puzzle
window has been drawn on and needs to be updated.

\c{x} and \c{y} give the coordinates of the top left pixel of the
update rectangle. \c{w} and \c{h} give its width and height. Thus,
the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
inclusive, and the vertical extent from \c{y} to \c{y+h-1}
inclusive. (These are exactly the same semantics as
\cw{draw_rect()}.)

The back end redraw function \e{must} call this function to report
any changes it has made to the window. Otherwise, those changes may
not become immediately visible, and may then appear at an
unpredictable subsequent time such as the next time the window is
covered and re-exposed.

This function is only important when drawing. It may be called when
printing as well, but doing so is not compulsory, and has no effect.
(So if you have a shared piece of code between the drawing and
printing routines, that code may safely call \cw{draw_update()}.)

\S{drawing-status-bar} \cw{status_bar()}

\c void status_bar(drawing *dr, const char *text);

Sets the text in the game's status bar to \c{text}. The text is copied
from the supplied buffer, so the caller is free to deallocate or
modify the buffer after use.

(This function is not exactly a \e{drawing} function, but it shares
with the drawing API the property that it may only be called from
within the back end redraw function. And it's implemented by front
ends via the \c{drawing_api} function pointer table. So this is the
best place to document it.)

The supplied text is filtered through the mid-end for optional
rewriting before being passed on to the front end; the mid-end will
prepend the current game time if the game is timed (and may in
future perform other rewriting if it seems like a good idea).

This function is for drawing only; it must never be called during
printing.

\S{drawing-blitter} Blitter functions

This section describes a group of related functions which save and
restore a section of the puzzle window. This is most commonly used
to implement user interfaces involving dragging a puzzle element
around the window: at the end of each call to \cw{redraw()}, if an
object is currently being dragged, the back end saves the window
contents under that location and then draws the dragged object, and
at the start of the next \cw{redraw()} the first thing it does is to
restore the background.

The front end defines an opaque type called a \c{blitter}, which is
capable of storing a rectangular area of a specified size.

Blitter functions are for drawing only; they must never be called
during printing.

\S2{drawing-blitter-new} \cw{blitter_new()}

\c blitter *blitter_new(drawing *dr, int w, int h);

Creates a new blitter object which stores a rectangle of size \c{w}
by \c{h} pixels. Returns a pointer to the blitter object.

Blitter objects are best stored in the \c{game_drawstate}. A good
time to create them is in the \cw{set_size()} function
(\k{backend-set-size}), since it is at this point that you first
know how big a rectangle they will need to save.

\S2{drawing-blitter-free} \cw{blitter_free()}

\c void blitter_free(drawing *dr, blitter *bl);

Disposes of a blitter object. Best called in \cw{free_drawstate()}.
(However, check that the blitter object is not \cw{NULL} before
attempting to free it; it is possible that a draw state might be
created and freed without ever having \cw{set_size()} called on it
in between.)

\S2{drawing-blitter-save} \cw{blitter_save()}

\c void blitter_save(drawing *dr, blitter *bl, int x, int y);

This is a true drawing API function, in that it may only be called
from within the game redraw routine. It saves a rectangular portion
of the puzzle window into the specified blitter object.

\c{x} and \c{y} give the coordinates of the top left corner of the
saved rectangle. The rectangle's width and height are the ones
specified when the blitter object was created.

This function is required to cope and do the right thing if \c{x}
and \c{y} are out of range. (The right thing probably means saving
whatever part of the blitter rectangle overlaps with the visible
area of the puzzle window.)

\S2{drawing-blitter-load} \cw{blitter_load()}

\c void blitter_load(drawing *dr, blitter *bl, int x, int y);

This is a true drawing API function, in that it may only be called
from within the game redraw routine. It restores a rectangular
portion of the puzzle window from the specified blitter object.

\c{x} and \c{y} give the coordinates of the top left corner of the
rectangle to be restored. The rectangle's width and height are the
ones specified when the blitter object was created.

Alternatively, you can specify both \c{x} and \c{y} as the special
value \cw{BLITTER_FROMSAVED}, in which case the rectangle will be
restored to exactly where it was saved from. (This is probably what
you want to do almost all the time, if you're using blitters to
implement draggable puzzle elements.)

This function is required to cope and do the right thing if \c{x}
and \c{y} (or the equivalent ones saved in the blitter) are out of
range. (The right thing probably means restoring whatever part of
the blitter rectangle overlaps with the visible area of the puzzle
window.)

If this function is called on a blitter which had previously been
saved from a partially out-of-range rectangle, then the parts of the
saved bitmap which were not visible at save time are undefined. If
the blitter is restored to a different position so as to make those
parts visible, the effect on the drawing area is undefined.

\S{print-mono-colour} \cw{print_mono_colour()}

\c int print_mono_colour(drawing *dr, int grey);

This function allocates a colour index for a simple monochrome
colour during printing.

\c{grey} must be 0 or 1. If \c{grey} is 0, the colour returned is
black; if \c{grey} is 1, the colour is white.

\S{print-grey-colour} \cw{print_grey_colour()}

\c int print_grey_colour(drawing *dr, float grey);

This function allocates a colour index for a grey-scale colour
during printing.

\c{grey} may be any number between 0 (black) and 1 (white); for
example, 0.5 indicates a medium grey.

The chosen colour will be rendered to the limits of the printer's
halftoning capability.

\S{print-hatched-colour} \cw{print_hatched_colour()}

\c int print_hatched_colour(drawing *dr, int hatch);

This function allocates a colour index which does not represent a
literal \e{colour}. Instead, regions shaded in this colour will be
hatched with parallel lines. The \c{hatch} parameter defines what
type of hatching should be used in place of this colour:

\dt \cw{HATCH_SLASH}

\dd This colour will be hatched by lines slanting to the right at 45
degrees. 

\dt \cw{HATCH_BACKSLASH}

\dd This colour will be hatched by lines slanting to the left at 45
degrees.

\dt \cw{HATCH_HORIZ}

\dd This colour will be hatched by horizontal lines.

\dt \cw{HATCH_VERT}

\dd This colour will be hatched by vertical lines.

\dt \cw{HATCH_PLUS}

\dd This colour will be hatched by criss-crossing horizontal and
vertical lines.

\dt \cw{HATCH_X}

\dd This colour will be hatched by criss-crossing diagonal lines.

Colours defined to use hatching may not be used for drawing lines or
text; they may only be used for filling areas. That is, they may be
used as the \c{fillcolour} parameter to \cw{draw_circle()} and
\cw{draw_polygon()}, and as the colour parameter to
\cw{draw_rect()}, but may not be used as the \c{outlinecolour}
parameter to \cw{draw_circle()} or \cw{draw_polygon()}, or with
\cw{draw_line()} or \cw{draw_text()}.

\S{print-rgb-mono-colour} \cw{print_rgb_mono_colour()}

\c int print_rgb_mono_colour(drawing *dr, float r, float g,
\c                           float b, float grey);

This function allocates a colour index for a fully specified RGB
colour during printing.

\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.

If printing in black and white only, these values will be ignored,
and either pure black or pure white will be used instead, according
to the \q{grey} parameter. (The fallback colour is the same as the
one which would be allocated by \cw{print_mono_colour(grey)}.)

\S{print-rgb-grey-colour} \cw{print_rgb_grey_colour()}

\c int print_rgb_grey_colour(drawing *dr, float r, float g,
\c                           float b, float grey);

This function allocates a colour index for a fully specified RGB
colour during printing.

\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.

If printing in black and white only, these values will be ignored,
and a shade of grey given by the \c{grey} parameter will be used
instead. (The fallback colour is the same as the one which would be
allocated by \cw{print_grey_colour(grey)}.)

\S{print-rgb-hatched-colour} \cw{print_rgb_hatched_colour()}

\c int print_rgb_hatched_colour(drawing *dr, float r, float g,
\c                              float b, float hatched);

This function allocates a colour index for a fully specified RGB
colour during printing.

\c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.

If printing in black and white only, these values will be ignored,
and a form of cross-hatching given by the \c{hatch} parameter will
be used instead; see \k{print-hatched-colour} for the possible
values of this parameter. (The fallback colour is the same as the
one which would be allocated by \cw{print_hatched_colour(hatch)}.)

\S{print-line-width} \cw{print_line_width()}

\c void print_line_width(drawing *dr, int width);

This function is called to set the thickness of lines drawn during
printing. It is meaningless in drawing: all lines drawn by
\cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} are one
pixel in thickness. However, in printing there is no clear
definition of a pixel and so line widths must be explicitly
specified.

The line width is specified in the usual coordinate system. Note,
however, that it is a hint only: the central printing system may
choose to vary line thicknesses at user request or due to printer
capabilities.

\S{print-line-dotted} \cw{print_line_dotted()}

\c void print_line_dotted(drawing *dr, bool dotted);

This function is called to toggle the drawing of dotted lines during
printing. It is not supported during drawing.

Setting \cq{dotted} to \cw{true} means that future lines drawn by
\cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} will be
dotted. Setting it to \cw{false} means that they will be solid.

Some front ends may impose restrictions on the width of dotted
lines. Asking for a dotted line via this front end will override any
line width request if the front end requires it.

\H{drawing-frontend} The drawing API as implemented by the front end

This section describes the drawing API in the function-pointer form
in which it is implemented by a front end.

(It isn't only platform-specific front ends which implement this
API; the platform-independent module \c{ps.c} also provides an
implementation of it which outputs PostScript. Thus, any platform
which wants to do PS printing can do so with minimum fuss.)

The following entries all describe function pointer fields in a
structure called \c{drawing_api}. Each of the functions takes a
\cq{void *} context pointer, which it should internally cast back to
a more useful type. Thus, a drawing \e{object} (\c{drawing *)}
suitable for passing to the back end redraw or printing functions
is constructed by passing a \c{drawing_api} and a \cq{void *} to the
function \cw{drawing_new()} (see \k{drawing-new}).

\S{drawingapi-draw-text} \cw{draw_text()}

\c void (*draw_text)(void *handle, int x, int y, int fonttype,
\c                   int fontsize, int align, int colour,
\c                   const char *text);

This function behaves exactly like the back end \cw{draw_text()}
function; see \k{drawing-draw-text}.

\S{drawingapi-draw-rect} \cw{draw_rect()}

\c void (*draw_rect)(void *handle, int x, int y, int w, int h,
\c                   int colour);

This function behaves exactly like the back end \cw{draw_rect()}
function; see \k{drawing-draw-rect}.

\S{drawingapi-draw-line} \cw{draw_line()}

\c void (*draw_line)(void *handle, int x1, int y1, int x2, int y2,
\c                   int colour);

This function behaves exactly like the back end \cw{draw_line()}
function; see \k{drawing-draw-line}.

\S{drawingapi-draw-polygon} \cw{draw_polygon()}

\c void (*draw_polygon)(void *handle, const int *coords, int npoints,
\c                      int fillcolour, int outlinecolour);

This function behaves exactly like the back end \cw{draw_polygon()}
function; see \k{drawing-draw-polygon}.

\S{drawingapi-draw-circle} \cw{draw_circle()}

\c void (*draw_circle)(void *handle, int cx, int cy, int radius,
\c                     int fillcolour, int outlinecolour);

This function behaves exactly like the back end \cw{draw_circle()}
function; see \k{drawing-draw-circle}.

\S{drawingapi-draw-thick-line} \cw{draw_thick_line()}

\c void draw_thick_line(drawing *dr, float thickness,
\c                      float x1, float y1, float x2, float y2,
\c                      int colour)

This function behaves exactly like the back end
\cw{draw_thick_line()} function; see \k{drawing-draw-thick-line}.

An implementation of this API which doesn't provide high-quality
rendering of thick lines is permitted to define this function
pointer to be \cw{NULL}. The middleware in \cw{drawing.c} will notice
and provide a low-quality alternative using \cw{draw_polygon()}.

\S{drawingapi-draw-update} \cw{draw_update()}

\c void (*draw_update)(void *handle, int x, int y, int w, int h);

This function behaves exactly like the back end \cw{draw_update()}
function; see \k{drawing-draw-update}.

An implementation of this API which only supports printing is
permitted to define this function pointer to be \cw{NULL} rather
than bothering to define an empty function. The middleware in
\cw{drawing.c} will notice and avoid calling it.

\S{drawingapi-clip} \cw{clip()}

\c void (*clip)(void *handle, int x, int y, int w, int h);

This function behaves exactly like the back end \cw{clip()}
function; see \k{drawing-clip}.

\S{drawingapi-unclip} \cw{unclip()}

\c void (*unclip)(void *handle);

This function behaves exactly like the back end \cw{unclip()}
function; see \k{drawing-unclip}.

\S{drawingapi-start-draw} \cw{start_draw()}

\c void (*start_draw)(void *handle);

This function is called at the start of drawing. It allows the front
end to initialise any temporary data required to draw with, such as
device contexts.

Implementations of this API which do not provide drawing services
may define this function pointer to be \cw{NULL}; it will never be
called unless drawing is attempted.

\S{drawingapi-end-draw} \cw{end_draw()}

\c void (*end_draw)(void *handle);

This function is called at the end of drawing. It allows the front
end to do cleanup tasks such as deallocating device contexts and
scheduling appropriate GUI redraw events.

Implementations of this API which do not provide drawing services
may define this function pointer to be \cw{NULL}; it will never be
called unless drawing is attempted.

\S{drawingapi-status-bar} \cw{status_bar()}

\c void (*status_bar)(void *handle, const char *text);

This function behaves exactly like the back end \cw{status_bar()}
function; see \k{drawing-status-bar}.

Front ends implementing this function need not worry about it being
called repeatedly with the same text; the middleware code in
\cw{status_bar()} will take care of this.

Implementations of this API which do not provide drawing services
may define this function pointer to be \cw{NULL}; it will never be
called unless drawing is attempted.

\S{drawingapi-blitter-new} \cw{blitter_new()}

\c blitter *(*blitter_new)(void *handle, int w, int h);

This function behaves exactly like the back end \cw{blitter_new()}
function; see \k{drawing-blitter-new}.

Implementations of this API which do not provide drawing services
may define this function pointer to be \cw{NULL}; it will never be
called unless drawing is attempted.

\S{drawingapi-blitter-free} \cw{blitter_free()}

\c void (*blitter_free)(void *handle, blitter *bl);

This function behaves exactly like the back end \cw{blitter_free()}
function; see \k{drawing-blitter-free}.

Implementations of this API which do not provide drawing services
may define this function pointer to be \cw{NULL}; it will never be
called unless drawing is attempted.

\S{drawingapi-blitter-save} \cw{blitter_save()}

\c void (*blitter_save)(void *handle, blitter *bl, int x, int y);

This function behaves exactly like the back end \cw{blitter_save()}
function; see \k{drawing-blitter-save}.

Implementations of this API which do not provide drawing services
may define this function pointer to be \cw{NULL}; it will never be
called unless drawing is attempted.

\S{drawingapi-blitter-load} \cw{blitter_load()}

\c void (*blitter_load)(void *handle, blitter *bl, int x, int y);

This function behaves exactly like the back end \cw{blitter_load()}
function; see \k{drawing-blitter-load}.

Implementations of this API which do not provide drawing services
may define this function pointer to be \cw{NULL}; it will never be
called unless drawing is attempted.

\S{drawingapi-begin-doc} \cw{begin_doc()}

\c void (*begin_doc)(void *handle, int pages);

This function is called at the beginning of a printing run. It gives
the front end an opportunity to initialise any required printing
subsystem. It also provides the number of pages in advance.

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-begin-page} \cw{begin_page()}

\c void (*begin_page)(void *handle, int number);

This function is called during printing, at the beginning of each
page. It gives the page number (numbered from 1 rather than 0, so
suitable for use in user-visible contexts).

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-begin-puzzle} \cw{begin_puzzle()}

\c void (*begin_puzzle)(void *handle, float xm, float xc,
\c                      float ym, float yc, int pw, int ph, float wmm);

This function is called during printing, just before printing a
single puzzle on a page. It specifies the size and location of the
puzzle on the page.

\c{xm} and \c{xc} specify the horizontal position of the puzzle on
the page, as a linear function of the page width. The front end is
expected to multiply the page width by \c{xm}, add \c{xc} (measured
in millimetres), and use the resulting x-coordinate as the left edge
of the puzzle.

Similarly, \c{ym} and \c{yc} specify the vertical position of the
puzzle as a function of the page height: the page height times
\c{ym}, plus \c{yc} millimetres, equals the desired distance from
the top of the page to the top of the puzzle.

(This unwieldy mechanism is required because not all printing
systems can communicate the page size back to the software. The
PostScript back end, for example, writes out PS which determines the
page size at print time by means of calling \cq{clippath}, and
centres the puzzles within that. Thus, exactly the same PS file
works on A4 or on US Letter paper without needing local
configuration, which simplifies matters.)

\cw{pw} and \cw{ph} give the size of the puzzle in drawing API
coordinates. The printing system will subsequently call the puzzle's
own print function, which will in turn call drawing API functions in
the expectation that an area \cw{pw} by \cw{ph} units is available
to draw the puzzle on.

Finally, \cw{wmm} gives the desired width of the puzzle in
millimetres. (The aspect ratio is expected to be preserved, so if
the desired puzzle height is also needed then it can be computed as
\cw{wmm*ph/pw}.)

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-end-puzzle} \cw{end_puzzle()}

\c void (*end_puzzle)(void *handle);

This function is called after the printing of a specific puzzle is
complete.

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-end-page} \cw{end_page()}

\c void (*end_page)(void *handle, int number);

This function is called after the printing of a page is finished.

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-end-doc} \cw{end_doc()}

\c void (*end_doc)(void *handle);

This function is called after the printing of the entire document is
finished. This is the moment to close files, send things to the
print spooler, or whatever the local convention is.

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-line-width} \cw{line_width()}

\c void (*line_width)(void *handle, float width);

This function is called to set the line thickness, during printing
only. Note that the width is a \cw{float} here, where it was an
\cw{int} as seen by the back end. This is because \cw{drawing.c} may
have scaled it on the way past.

However, the width is still specified in the same coordinate system
as the rest of the drawing.

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-line-dotted} \cw{line_dotted()}

\c void (*line_dotted)(void *handle, bool dotted);

This function is called to toggle drawing of dotted lines, during
printing only.

Implementations of this API which do not provide printing services
may define this function pointer to be \cw{NULL}; it will never be
called unless printing is attempted.

\S{drawingapi-text-fallback} \cw{text_fallback()}

\c char *(*text_fallback)(void *handle, const char *const *strings,
\c                        int nstrings);

This function behaves exactly like the back end \cw{text_fallback()}
function; see \k{drawing-text-fallback}.

Implementations of this API which do not support any characters
outside ASCII may define this function pointer to be \cw{NULL}, in
which case the central code in \cw{drawing.c} will provide a default
implementation.

\H{drawingapi-frontend} The drawing API as called by the front end

There are a small number of functions provided in \cw{drawing.c}
which the front end needs to \e{call}, rather than helping to
implement. They are described in this section.

\S{drawing-new} \cw{drawing_new()}

\c drawing *drawing_new(const drawing_api *api, midend *me,
\c                      void *handle);

This function creates a drawing object. It is passed a
\c{drawing_api}, which is a structure containing nothing but
function pointers; and also a \cq{void *} handle. The handle is
passed back to each function pointer when it is called.

The \c{midend} parameter is used for rewriting the status bar
contents: \cw{status_bar()} (see \k{drawing-status-bar}) has to call
a function in the mid-end which might rewrite the status bar text.
If the drawing object is to be used only for printing, or if the
game is known not to call \cw{status_bar()}, this parameter may be
\cw{NULL}.

\S{drawing-free} \cw{drawing_free()}

\c void drawing_free(drawing *dr);

This function frees a drawing object. Note that the \cq{void *}
handle is not freed; if that needs cleaning up it must be done by
the front end.

\S{drawing-print-get-colour} \cw{print_get_colour()}

\c void print_get_colour(drawing *dr, int colour,
\c                       bool printing_in_colour,
\c                       int *hatch, float *r, float *g, float *b);

This function is called by the implementations of the drawing API
functions when they are called in a printing context. It takes a
colour index as input, and returns the description of the colour as
requested by the back end.

\c{printing_in_colour} is \cw{true} iff the implementation is printing
in colour. This will alter the results returned if the colour in
question was specified with a black-and-white fallback value.

If the colour should be rendered by hatching, \c{*hatch} is filled
with the type of hatching desired. See \k{print-grey-colour} for
details of the values this integer can take.

If the colour should be rendered as solid colour, \c{*hatch} is
given a negative value, and \c{*r}, \c{*g} and \c{*b} are filled
with the RGB values of the desired colour (if printing in colour),
or all filled with the grey-scale value (if printing in black and
white).

\C{midend} The API provided by the mid-end

This chapter documents the API provided by the mid-end to be called
by the front end. You probably only need to read this if you are a
front end implementor, i.e. you are porting Puzzles to a new
platform. If you're only interested in writing new puzzles, you can
safely skip this chapter.

All the persistent state in the mid-end is encapsulated within a
\c{midend} structure, to facilitate having multiple mid-ends in any
port which supports multiple puzzle windows open simultaneously.
Each \c{midend} is intended to handle the contents of a single
puzzle window.

\H{midend-new} \cw{midend_new()}

\c midend *midend_new(frontend *fe, const game *ourgame,
\c                    const drawing_api *drapi, void *drhandle);

Allocates and returns a new mid-end structure.

The \c{fe} argument is stored in the mid-end. It will be used when
calling back to functions such as \cw{activate_timer()}
(\k{frontend-activate-timer}), and will be passed on to the back end
function \cw{colours()} (\k{backend-colours}).

The parameters \c{drapi} and \c{drhandle} are passed to
\cw{drawing_new()} (\k{drawing-new}) to construct a drawing object
which will be passed to the back end function \cw{redraw()}
(\k{backend-redraw}). Hence, all drawing-related function pointers
defined in \c{drapi} can expect to be called with \c{drhandle} as
their first argument.

The \c{ourgame} argument points to a container structure describing
a game back end. The mid-end thus created will only be capable of
handling that one game. (So even in a monolithic front end
containing all the games, this imposes the constraint that any
individual puzzle window is tied to a single game. Unless, of
course, you feel brave enough to change the mid-end for the window
without closing the window...)

\H{midend-free} \cw{midend_free()}

\c void midend_free(midend *me);

Frees a mid-end structure and all its associated data.

\H{midend-tilesize} \cw{midend_tilesize()}

\c int midend_tilesize(midend *me);

Returns the \cq{tilesize} parameter being used to display the
current puzzle (\k{backend-preferred-tilesize}).

\H{midend-set-params} \cw{midend_set_params()}

\c void midend_set_params(midend *me, game_params *params);

Sets the current game parameters for a mid-end. Subsequent games
generated by \cw{midend_new_game()} (\k{midend-new-game}) will use
these parameters until further notice.

The usual way in which the front end will have an actual
\c{game_params} structure to pass to this function is if it had
previously got it from \cw{midend_get_presets()}
(\k{midend-get-presets}). Thus, this function is usually called in
response to the user making a selection from the presets menu.

\H{midend-get-params} \cw{midend_get_params()}

\c game_params *midend_get_params(midend *me);

Returns the current game parameters stored in this mid-end.

The returned value is dynamically allocated, and should be freed
when finished with by passing it to the game's own
\cw{free_params()} function (see \k{backend-free-params}).

\H{midend-size} \cw{midend_size()}

\c void midend_size(midend *me, int *x, int *y,
\c                  bool user_size, double device_pixel_ratio);

Tells the mid-end to figure out its window size.

On input, \c{*x} and \c{*y} should contain the maximum or requested
size for the window. (Typically this will be the size of the screen
that the window has to fit on, or similar.) The mid-end will
repeatedly call the back end function \cw{compute_size()}
(\k{backend-compute-size}), searching for a tile size that best
satisfies the requirements. On exit, \c{*x} and \c{*y} will contain
the size needed for the puzzle window's drawing area. (It is of
course up to the front end to adjust this for any additional window
furniture such as menu bars and window borders, if necessary. The
status bar is also not included in this size.)

Use \c{user_size} to indicate whether \c{*x} and \c{*y} are a
requested size, or just a maximum size.

If \c{user_size} is set to \cw{true}, the mid-end will treat the
input size as a request, and will pick a tile size which
approximates it \e{as closely as possible}, going over the game's
preferred tile size if necessary to achieve this. The mid-end will
also use the resulting tile size as its preferred one until further
notice, on the assumption that this size was explicitly requested
by the user. Use this option if you want your front end to support
dynamic resizing of the puzzle window with automatic scaling of the
puzzle to fit.

If \c{user_size} is set to \cw{false}, then the game's tile size
will never go over its preferred one, although it may go under in
order to fit within the maximum bounds specified by \c{*x} and
\c{*y}. This is the recommended approach when opening a new window
at default size: the game will use its preferred size unless it has
to use a smaller one to fit on the screen. If the tile size is
shrunk for this reason, the change will not persist; if a smaller
grid is subsequently chosen, the tile size will recover.

The mid-end will try as hard as it can to return a size which is
less than or equal to the input size, in both dimensions. In extreme
circumstances it may fail (if even the lowest possible tile size
gives window dimensions greater than the input), in which case it
will return a size greater than the input size. Front ends should be
prepared for this to happen (i.e. don't crash or fail an assertion),
but may handle it in any way they see fit: by rejecting the game
parameters which caused the problem, by opening a window larger than
the screen regardless of inconvenience, by introducing scroll bars
on the window, by drawing on a large bitmap and scaling it into a
smaller window, or by any other means you can think of. It is likely
that when the tile size is that small the game will be unplayable
anyway, so don't put \e{too} much effort into handling it
creatively.

If your platform has no limit on window size (or if you're planning
to use scroll bars for large puzzles), you can pass dimensions of
\cw{INT_MAX} as input to this function. You should probably not do
that \e{and} set the \c{user_size} flag, though!

The \cw{device_pixel_ratio} allows the front end to specify that its
pixels are unusually large or small (or should be treated as such).
The mid-end uses this to adjust the tile size, both at startup (if the
ratio is not 1) and if the ratio changes.

A \cw{device_pixel_ratio} of 1 indicates normal-sized pixels.
\q{Normal} is not precisely defined, but it's about 4 pixels per
millimetre on a screen designed to be viewed from a metre away, or a
size such that text 15 pixels high is comfortably readable.  Some
platforms have a concept of a logical pixel that this can be mapped
onto.  For instance, Cascading Style Sheets (CSS) has a unit called
\cq{px} that only matches physical pixels at a \cw{device_pixel_ratio}
of 1.

The \cw{device_pixel_ratio} indicates the number of physical pixels in
a normal-sized pixel, so values less than 1 indicate unusually large
pixels and values greater than 1 indicate unusually small pixels.

The midend relies on the frontend calling \cw{midend_new_game()}
(\k{midend-new-game}) before calling \cw{midend_size()}.

\H{midend-reset-tilesize} \cw{midend_reset_tilesize()}

\c void midend_reset_tilesize(midend *me);

This function resets the midend's preferred tile size to that of the
standard puzzle.

As discussed in \k{midend-size}, puzzle resizes are typically
'sticky', in that once the user has dragged the puzzle to a different
window size, the resulting tile size will be remembered and used when
the puzzle configuration changes. If you \e{don't} want that, e.g. if
you want to provide a command to explicitly reset the puzzle size back
to its default, then you can call this just before calling
\cw{midend_size()} (which, in turn, you would probably call with
\c{user_size} set to \cw{false}).

\H{midend-new-game} \cw{midend_new_game()}

\c void midend_new_game(midend *me);

Causes the mid-end to begin a new game. Normally the game will be a
new randomly generated puzzle. However, if you have previously
called \cw{midend_game_id()} or \cw{midend_set_config()}, the game
generated might be dictated by the results of those functions. (In
particular, you \e{must} call \cw{midend_new_game()} after calling
either of those functions, or else no immediate effect will be
visible.)

You will probably need to call \cw{midend_size()} after calling this
function, because if the game parameters have been changed since the
last new game then the window size might need to change. (If you
know the parameters \e{haven't} changed, you don't need to do this.)

This function will create a new \c{game_drawstate}, but does not
actually perform a redraw (since you often need to call
\cw{midend_size()} before the redraw can be done). So after calling
this function and after calling \cw{midend_size()}, you should then
call \cw{midend_redraw()}. (It is not necessary to call
\cw{midend_force_redraw()}; that will discard the draw state and
create a fresh one, which is unnecessary in this case since there's
a fresh one already. It would work, but it's usually excessive.)

\H{midend-restart-game} \cw{midend_restart_game()}

\c void midend_restart_game(midend *me);

This function causes the current game to be restarted. This is done
by placing a new copy of the original game state on the end of the
undo list (so that an accidental restart can be undone).

This function automatically causes a redraw, i.e. the front end can
expect its drawing API to be called from \e{within} a call to this
function. Some back ends require that \cw{midend_size()}
(\k{midend-size}) is called before \cw{midend_restart_game()}.

\H{midend-force-redraw} \cw{midend_force_redraw()}

\c void midend_force_redraw(midend *me);

Forces a complete redraw of the puzzle window, by means of
discarding the current \c{game_drawstate} and creating a new one
from scratch before calling the game's \cw{redraw()} function.

The front end can expect its drawing API to be called from within a
call to this function. Some back ends require that \cw{midend_size()}
(\k{midend-size}) is called before \cw{midend_force_redraw()}.

\H{midend-redraw} \cw{midend_redraw()}

\c void midend_redraw(midend *me);

Causes a partial redraw of the puzzle window, by means of simply
calling the game's \cw{redraw()} function. (That is, the only things
redrawn will be things that have changed since the last redraw.)

The front end can expect its drawing API to be called from within a
call to this function. Some back ends require that \cw{midend_size()}
(\k{midend-size}) is called before \cw{midend_redraw()}.

\H{midend-process-key} \cw{midend_process_key()}

\c bool midend_process_key(midend *me, int x, int y, int button,
\c                         bool *handled);

The front end calls this function to report a mouse or keyboard event.
The parameters \c{x} and \c{y} are identical to the ones passed to the
back end function \cw{interpret_move()} (\k{backend-interpret-move}).

\c{button} is similar to the parameter passed to
\cw{interpret_move()}. However, the midend is more relaxed about
values passed to in, and some additional special button values
are defined for the front end to pass to the midend (see below).

Also, the front end is \e{not} required to provide guarantees about
mouse event ordering. The mid-end will sort out multiple simultaneous
button presses and changes of button; the front end's responsibility
is simply to pass on the mouse events it receives as accurately as
possible.

(Some platforms may need to emulate absent mouse buttons by means of
using a modifier key such as Shift with another mouse button. This
tends to mean that if Shift is pressed or released in the middle of
a mouse drag, the mid-end will suddenly stop receiving, say,
\cw{LEFT_DRAG} events and start receiving \cw{RIGHT_DRAG}s, with no
intervening button release or press events. This too is something
which the mid-end will sort out for you; the front end has no
obligation to maintain sanity in this area.)

The front end \e{should}, however, always eventually send some kind
of button release. On some platforms this requires special effort:
Windows, for example, requires a call to the system API function
\cw{SetCapture()} in order to ensure that your window receives a
mouse-up event even if the pointer has left the window by the time
the mouse button is released. On any platform that requires this
sort of thing, the front end \e{is} responsible for doing it.

Calling this function is very likely to result in calls back to the
front end's drawing API and/or \cw{activate_timer()}
(\k{frontend-activate-timer}).

The return value from \cw{midend_process_key()} is \cw{true} unless
the effect of the keypress was to request termination of the program.
A front end should shut down the puzzle in response to a \cw{false}
return.

If the front end passes in a non-NULL pointer in \c{handled}, the
mid-end will set \cw{*handled} to \cw{true} if it or the backend does
something in response to the keypress.  A front end can use this to
decide whether to pass the keypress on to anything else that might
want to do something in response to it.

The following additional values of \c{button} are permitted to be
passed to this function by the front end, but are never passed on to
the back end. They indicate front-end specific UI operations, such as
selecting an option from a drop-down menu. (Otherwise the front end
would have to translate the \q{New Game} menu item into an \cq{n}
keypress, for example.)

\dt \cw{UI_NEWGAME}

\dd Indicates that the user requested a new game, similar to pressing
\cq{n}.

\dt \cw{UI_SOLVE}

\dd Indicates that the user requested the solution of the current game.

\dt \cw{UI_UNDO}

\dd Indicates that the user attempted to undo a move.

\dt \cw{UI_REDO}

\dd Indicates that the user attempted to redo an undone move.

\dt \cw{UI_QUIT}

\dd Indicates that the user asked to quit the game. (Of course, a
front end might perfectly well handle this on its own. But including
it in this enumeration allows the front end to treat all these menu
items the same, by translating each of them into a button code passed
to the midend, and handle quitting by noticing the \c{false} return
value from \cw{midend_process_key()}.)

The midend tolerates any modifier being set on any key and removes
them as necessary before passing the key on to the backend.  It will
also handle translating printable characters combined with
\cw{MOD_CTRL} into control characters.

\H{midend-request-keys} \cw{midend_request_keys()}

\c key_label *midend_request_keys(midend *me, int *nkeys);

This function behaves similarly to the backend's \cw{request_keys()}
function (\k{backend-request-keys}). If the backend does not provide
\cw{request_keys()}, this function will return \cw{NULL} and set
\cw{*nkeys} to zero. Otherwise, this function will fill in the generic
labels (i.e. the \cw{key_label} items that have their \cw{label}
fields set to \cw{NULL}) by using \cw{button2label()}
(\k{utils-button2label}).

\H{midend-current-key-label} \cw{midend_current_key_label()}

\c const char *midend_current_key_label(midend *me, int button);

This is a thin wrapper around the backend's \cw{current_key_label()}
function (\k{backend-current-key-label}).  Front ends that need to
label \cw{CURSOR_SELECT} or \cw{CURSOR_SELECT2} should call this
function after each move (at least after each call to
\cw{midend_process_key()}) to get the current labels.  The front end
should arrange to copy the returned string somewhere before the next
call to the mid-end, just in case it's dynamically allocated.  If the
button supplied does nothing, the label returned will be an empty
string.

\H{midend-colours} \cw{midend_colours()}

\c float *midend_colours(midend *me, int *ncolours);

Returns an array of the colours required by the game, in exactly the
same format as that returned by the back end function \cw{colours()}
(\k{backend-colours}). Front ends should call this function rather
than calling the back end's version directly, since the mid-end adds
standard customisation facilities. (At the time of writing, those
customisation facilities are implemented hackily by means of
environment variables, but it's not impossible that they may become
more full and formal in future.)

\H{midend-timer} \cw{midend_timer()}

\c void midend_timer(midend *me, float tplus);

If the mid-end has called \cw{activate_timer()}
(\k{frontend-activate-timer}) to request regular callbacks for
purposes of animation or timing, this is the function the front end
should call on a regular basis. The argument \c{tplus} gives the
time, in seconds, since the last time either this function was
called or \cw{activate_timer()} was invoked.

One of the major purposes of timing in the mid-end is to perform
move animation. Therefore, calling this function is very likely to
result in calls back to the front end's drawing API.

\H{midend-get-presets} \cw{midend_get_presets()}

\c struct preset_menu *midend_get_presets(midend *me, int *id_limit);

Returns a data structure describing this game's collection of preset
game parameters, organised into a hierarchical structure of menus and
submenus.

The return value is a pointer to a data structure containing the
following fields (among others, which are not intended for front end
use):

\c struct preset_menu {
\c     int n_entries;
\c     struct preset_menu_entry *entries;
\c     /* and other things */
\e     iiiiiiiiiiiiiiiiiiiiii
\c };

Those fields describe the intended contents of one particular menu in
the hierarchy. \cq{entries} points to an array of \cq{n_entries}
items, each of which is a structure containing the following fields:

\c struct preset_menu_entry {
\c     char *title;
\c     game_params *params;
\c     struct preset_menu *submenu;
\c     int id;
\c };

Of these fields, \cq{title} and \cq{id} are present in every entry,
giving (respectively) the textual name of the menu item and an integer
identifier for it. The integer id will correspond to the one returned
by \c{midend_which_preset} (\k{midend-which-preset}), when that preset
is the one selected.

The other two fields are mutually exclusive. Each \c{struct
preset_menu_entry} will have one of those fields \cw{NULL} and the
other one non-null. If the menu item is an actual preset, then
\cq{params} will point to the set of game parameters that go with the
name; if it's a submenu, then \cq{submenu} instead will be non-null,
and will point at a subsidiary \c{struct preset_menu}.

The complete hierarchy of these structures is owned by the mid-end,
and will be freed when the mid-end is freed. The front end should not
attempt to free any of it.

The integer identifiers will be allocated densely from 0 upwards, so
that it's reasonable for the front end to allocate an array which uses
them as indices, if it needs to store information per preset menu
item. For this purpose, the front end may pass the second parameter
\cq{id_limit} to \cw{midend_get_presets} as the address of an \c{int}
variable, into which \cw{midend_get_presets} will write an integer one
larger than the largest id number actually used (i.e. the number of
elements the front end would need in the array).

Submenu-type entries also have integer identifiers.

\H{midend-which-preset} \cw{midend_which_preset()}

\c int midend_which_preset(midend *me);

Returns the numeric index of the preset game parameter structure
which matches the current game parameters, or a negative number if
no preset matches. Front ends could use this to maintain a tick
beside one of the items in the menu (or tick the \q{Custom} option
if the return value is less than zero).

The returned index value (if non-negative) will match the \c{id} field
of the corresponding \cw{struct preset_menu_entry} returned by
\c{midend_get_presets()} (\k{midend-get-presets}).

\H{midend-wants-statusbar} \cw{midend_wants_statusbar()}

\c bool midend_wants_statusbar(midend *me);

This function returns \cw{true} if the puzzle has a use for a
textual status line (to display score, completion status, currently
active tiles, time, or anything else).

Front ends should call this function rather than talking directly to
the back end.

\H{midend-get-config} \cw{midend_get_config()}

\c config_item *midend_get_config(midend *me, int which,
\c                                char **wintitle);

Returns a dialog box description for user configuration.

On input, \cw{which} should be set to one of three values, which
select which of the various dialog box descriptions is returned:

\dt \cw{CFG_SETTINGS}

\dd Requests the GUI parameter configuration box generated by the
puzzle itself. This should be used when the user selects \q{Custom}
from the game types menu (or equivalent). The mid-end passes this
request on to the back end function \cw{configure()}
(\k{backend-configure}).

\dt \cw{CFG_DESC}

\dd Requests a box suitable for entering a descriptive game ID (and
viewing the existing one). The mid-end generates this dialog box
description itself. This should be used when the user selects
\q{Specific} from the game menu (or equivalent).

\dt \cw{CFG_SEED}

\dd Requests a box suitable for entering a random-seed game ID (and
viewing the existing one). The mid-end generates this dialog box
description itself. This should be used when the user selects
\q{Random Seed} from the game menu (or equivalent).

(A fourth value \cw{CFG_FRONTEND_SPECIFIC} is provided in this
enumeration, so that frontends can extend it for their own internal
use. For example, you might wrap this function with a
\cw{frontend_get_config} which handles some values of \c{which} itself
and hands others on to the midend, depending on whether \cw{which <
CFG_FRONTEND_SPECIFIC}.)

The returned value is an array of \cw{config_item}s, exactly as
described in \k{backend-configure}. Another returned value is an
ASCII string giving a suitable title for the configuration window,
in \c{*wintitle}.

Both returned values are dynamically allocated and will need to be
freed. The window title can be freed in the obvious way; the
\cw{config_item} array is a slightly complex structure, so a utility
function \cw{free_cfg()} is provided to free it for you. See
\k{utils-free-cfg}.

(Of course, you will probably not want to free the \cw{config_item}
array until the dialog box is dismissed, because before then you
will probably need to pass it to \cw{midend_set_config}.)

\H{midend-set-config} \cw{midend_set_config()}

\c const char *midend_set_config(midend *me, int which,
\c                               config_item *cfg);

Passes the mid-end the results of a configuration dialog box.
\c{which} should have the same value which it had when
\cw{midend_get_config()} was called; \c{cfg} should be the array of
\c{config_item}s returned from \cw{midend_get_config()}, modified to
contain the results of the user's editing operations.

This function returns \cw{NULL} on success, or otherwise (if the
configuration data was in some way invalid) an ASCII string
containing an error message suitable for showing to the user.

If the function succeeds, it is likely that the game parameters will
have been changed and it is certain that a new game will be
requested. The front end should therefore call
\cw{midend_new_game()}, and probably also re-think the window size
using \cw{midend_size()} and eventually perform a refresh using
\cw{midend_redraw()}.

\H{midend-game-id} \cw{midend_game_id()}

\c const char *midend_game_id(midend *me, const char *id);

Passes the mid-end a string game ID (of any of the valid forms
\cq{params}, \cq{params:description} or \cq{params#seed}) which the
mid-end will process and use for the next generated game.

This function returns \cw{NULL} on success, or otherwise (if the
configuration data was in some way invalid) an ASCII string
containing an error message (not dynamically allocated) suitable for
showing to the user. In the event of an error, the mid-end's
internal state will be left exactly as it was before the call.

If the function succeeds, it is likely that the game parameters will
have been changed and it is certain that a new game will be
requested. The front end should therefore call
\cw{midend_new_game()}, and probably also re-think the window size
using \cw{midend_size()} and eventually case a refresh using
\cw{midend_redraw()}.

\H{midend-get-game-id} \cw{midend_get_game_id()}

\c char *midend_get_game_id(midend *me);

Returns a descriptive game ID (i.e. one in the form
\cq{params:description}) describing the game currently active in the
mid-end. The returned string is dynamically allocated.

\H{midend-get-random-seed} \cw{midend_get_random_seed()}

\c char *midend_get_random_seed(midend *me);

Returns a random game ID (i.e. one in the form \cq{params#seedstring})
describing the game currently active in the mid-end, if there is one.
If the game was created by entering a description, no random seed will
currently exist and this function will return \cw{NULL}.

The returned string, if it is non-\cw{NULL}, is dynamically allocated.

Unlike the descriptive game ID, the random seed can contain characters
outside the printable ASCII set.

\H{midend-can-format-as-text-now} \cw{midend_can_format_as_text_now()}

\c bool midend_can_format_as_text_now(midend *me);

Returns \cw{true} if the game code is capable of formatting puzzles
of the currently selected game type as ASCII.

If this returns \cw{false}, then \cw{midend_text_format()}
(\k{midend-text-format}) will return \cw{NULL}.

\H{midend-text-format} \cw{midend_text_format()}

\c char *midend_text_format(midend *me);

Formats the current game's current state as ASCII text suitable for
copying to the clipboard. The returned string is dynamically
allocated.

If the game's \c{can_format_as_text_ever} flag is \cw{false}, or if
its \cw{can_format_as_text_now()} function returns \cw{false}, then
this function will return \cw{NULL}.

If the returned string contains multiple lines (which is likely), it
will use the normal C line ending convention (\cw{\\n} only). On
platforms which use a different line ending convention for data in
the clipboard, it is the front end's responsibility to perform the
conversion.