1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
use super::*; use std; use std::io::Write; use std::sync::Mutex; lazy_static! { static ref PAGES: Mutex<Vec<CodePage>> = Mutex::new(vec![]); } /** Generates a tone on the speaker. # Arguments * `frequency` - The frequency of the tone, in hertz. * `duration` - The duration of the sound, in milliseconds. # Examples Plays a note of A4 frequency for 1 second. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::beep(440, 1000).unwrap(); # } ``` */ pub fn beep(frequency: u32, duration: u32) { unsafe { utilapiset::Beep(frequency, duration); } } /** Clears the console. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { println!("Hello, wolrd!"); println!("Wait, that's not right.."); console::clear().unwrap(); println!("Hello, world!"); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn clear() -> WinResult<()> { let size = get_buffer_size()?; let length = DWORD::from(size.x) * DWORD::from(size.y); fill_char(32, length, COORD { X: 0, Y: 0 })?; fill_attributes(get_text_attributes()?, length, COORD { X: 0, Y: 0 })?; set_cursor_position(0, 0) } /** Clears the console input history. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::clear_history().unwrap(); # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn clear_history() -> WinResult<()> { let old = get_history_info()?; let mut empty = old; empty.size = 0; set_history_info(empty)?; set_history_info(old)?; Ok(()) } /** Fills the console window with a specified character starting at a specified location, and returns the number of cells which were filled. Note that this only changes the character; the colors of each cell will remain the same. # Arguments * `chr` - The character to fill the console with. * `column` - The column at which the fill should begin. * `row` - The row at which the fill should begin. * `max_length` - The maximum amount of cells to fill. If None, fill the entirety of the console from the start position. # Examples Fills the entire console with 'Z'. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::fill_character('Z', 0, 0, None).unwrap(); # } ``` Fills the first ten cells with 'G'. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::fill_character('G', 0, 0, 10).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn fill_character( chr: char, column: u16, row: u16, max_length: impl Into<Option<u32>>, ) -> WinResult<u32> { let coords = COORD { X: column as i16, Y: row as i16, }; let length = match max_length.into() { Some(len) => len, None => { let size = get_buffer_size()?; let con_length = DWORD::from(size.x) * DWORD::from(size.y); let start_pos = DWORD::from(column) * DWORD::from(row); if start_pos > con_length { return Ok(0); } con_length - start_pos } }; fill_char(chr as CHAR, length, coords) } /** Fills the console window with a specified set of colors starting at a specified location, and returns the number of cells which were filled. # Arguments * `colors` - The colors to fill the console with. The first item in the tuple is the foreground color, and the second item is the background color. * `column` - The column at which the fill should begin. * `row` - The row at which the fill should begin. * `max_length` - The maximum amount of cells to fill. If None, fill the entirety of the console from the start position. # Examples Fills the entire console with a blue foreground and red background. ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::ConsoleColor; # fn main() { console::fill_colors((ConsoleColor::Blue, ConsoleColor::Red), 0, 0, None).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn fill_colors( colors: (ConsoleColor, ConsoleColor), column: u16, row: u16, max_length: impl Into<Option<u32>>, ) -> WinResult<u32> { let coords = COORD { X: column as i16, Y: row as i16, }; let length = match max_length.into() { Some(len) => len, None => { let size = get_buffer_size()?; let con_length = DWORD::from(size.x) * DWORD::from(size.y); let start_pos = DWORD::from(column) * DWORD::from(row); if start_pos > con_length { return Ok(0); } con_length - start_pos } }; let attrs = WORD::from(colors.0.get_value() | ((colors.1.get_value()) << 4)); fill_attributes(attrs, length, coords) } /** Flushes the console input buffer. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::flush_input().unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console input is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn flush_input() -> WinResult<()> { os_err!(unsafe { let handle = handle!(STDIN); wincon::FlushConsoleInputBuffer(handle) }); Ok(()) } /** Flushes the console output buffer. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::flush_output().unwrap(); # } ``` # Errors * [`IoError`]: Returned if an IO error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn flush_output() -> WinResult<()> { io::stdout().flush()?; Ok(()) } /** Sends a ctrl signal to a process group which shares the console. # Arguments * `break_event`- Should a CTRL + BREAK signal be generated? Otherwise, a CTRL + C signal will be generated. A CTRL + C signal cannot be generated for a process group. * `process_group_id` - The ID of the process group to generate the event on. If None, generate the event on processes which share the console. # Examples Generates a CTRL event. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::generate_ctrl_event(false, None).unwrap(); # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn generate_ctrl_event( break_event: bool, process_group_id: impl Into<Option<u32>>, ) -> WinResult<()> { let id: u32 = match process_group_id.into() { None => 0, Some(id) => id, }; let event = bool_to_num!(break_event) as u32; os_err!(unsafe { wincon::GenerateConsoleCtrlEvent(event, id) }); Ok(()) } /** Reads a single character from the input buffer. Note that this will wait for input from the user, and will only accept certain characters; this will not return from a control key press event. # Arguments * `suppress` - Should the character be returned without printing? # Examples Gets a character and prints it to the console. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::getch(false).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console input/output is retrieved or used. * [`IoError`]: Returned if an IO or OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn getch(suppress: bool) -> WinResult<char> { let old_mode = get_input_mode()?; let mut mode = old_mode; mode.EchoInput = false; mode.LineInput = false; set_input_mode(mode)?; let mut res: CHAR = 0; os_err!(unsafe { let mut num: DWORD = 0; let handle = handle!(STDIN); let buffer_p = &mut res as *mut CHAR as *mut VOID; let control_p: *mut CONSOLE_READCONSOLE_CONTROL = ptr::null_mut(); consoleapi::ReadConsoleA(handle, buffer_p, 1, &mut num, control_p) }); let res = res as u8; set_input_mode(old_mode)?; if !suppress { let out = io::stdout(); let mut out = out.lock(); out.write_all(&[res])?; out.flush()?; } Ok(res as char) } /** Returns the current background color of the console. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let background = console::get_background_color().unwrap(); println!("Background color: {}", background); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_background_color() -> WinResult<ConsoleColor> { let attrs = get_text_attributes()?; Ok(ConsoleColor::from((attrs & 0xF0) >> 4)) } /** Returns the size of the console output buffer. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let buffer_size = console::get_buffer_size().unwrap(); console::set_buffer_size(buffer_size.x + 1, buffer_size.y + 1); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_buffer_size() -> WinResult<Vector2<u16>> { let coords = get_screen_buffer_info()?.dwSize; Ok(Vector2::new(coords.X as u16, coords.Y as u16)) } /** Returns a `CodePageInfo` object which contains information about the `CodePage`. # Arguments * `page` - The `CodePage` to retrieve information about. # Examples ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::CodePage; # fn main() { let info = console::get_code_page_info(CodePage::utf_8).unwrap(); println!("{}", info.name); # } ``` # Errors * [`FromUtf8Error`]: Returned if an error occurs while converting to a character. * [`FromUtf16Error`]: Returned if an error occurs while converting to a character. * [`IoError`]: Returned if an OS error occurs. [`FromUtf8Error`]: ../errors/enum.WinError.html#FromUtf8.v [`FromUtf16Error`]: ../errors/enum.WinError.html#FromUtf16.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_code_page_info(page: CodePage) -> WinResult<CodePageInfo> { let mut info: CPINFOEXA = unsafe { mem::zeroed() }; let identifier: u16 = page.into(); os_err!(unsafe { winnls::GetCPInfoExA(u32::from(identifier), 0, &mut info) }); let mut cpi = CodePageInfo::default(); cpi.max_char_size = info.MaxCharSize as u8; cpi.default = buf_to_str!(info.DefaultChar); cpi.lead_byte = info.LeadByte; cpi.unicode_default = String::from_utf16(&[info.UnicodeDefaultChar])?; cpi.code_page = CodePage::from(info.CodePage as u16); cpi.name = buf_to_str!(info.CodePageName); Ok(cpi) } /** Returns the RGB color value of a `ConsoleColor`. # Examples ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::ConsoleColor; # fn main() { let black = console::get_color(ConsoleColor::Black).unwrap(); println!("{:?}", black); # } ``` */ pub fn get_color(color: ConsoleColor) -> WinResult<RGB8> { let mapping = get_color_mapping()?; Ok(mapping[color.get_value() as usize]) } /** Returns the current color mapping for the console. The indices of the returned array correspond with `ConsoleColor` values. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let mapping = console::get_color_mapping().unwrap(); let black = mapping[0]; println!("{:?}", black); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_color_mapping() -> WinResult<[RGB8; 16]> { let colors = get_screen_buffer_info_ex()?.ColorTable; let mut ret = [RGB8 { r: 0, g: 0, b: 0 }; 16]; for i in 0..16 { ret[i] = make_rgb!(colors[i]); } Ok(ret) } /** Returns the current position of the console cursor. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let position = console::get_cursor_position().unwrap(); println!("{:?}", position); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_cursor_position() -> WinResult<Vector2<u16>> { let pos = get_screen_buffer_info()?.dwCursorPosition; Ok(Vector2::new(pos.X as u16, pos.Y as u16)) } /** Returns the size of the console cursor. The size of the console cursor will always be between 0 and 100 (inclusive). # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let cursor_size = console::get_cursor_size().unwrap(); println!("{}", cursor_size); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_cursor_size() -> WinResult<u8> { let info = get_cursor_info()?; Ok(info.dwSize as u8) } /** Returns information about the current console font. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let font = console::get_font().unwrap(); println!("{}", font.name); # } ``` # Errors * [`FromUtf8Error`]: Returned if an error occurs while converting to a string. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`FromUtf8Error`]: ../errors/enum.WinError.html#FromUtf8.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_font() -> WinResult<ConsoleFont> { let info = get_font_info_ex(false)?; let size = info.dwFontSize; Ok(ConsoleFont { family: info.FontFamily, index: info.nFont, name: buf_to_str!(info.FaceName), size: Vector2::new(size.X as u16, size.Y as u16), weight: info.FontWeight, }) } /** Returns the current foreground color of the console. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let foreground = console::get_foreground_color().unwrap(); println!("Foreground color: {}", foreground); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_foreground_color() -> WinResult<ConsoleColor> { let attrs = get_text_attributes()?; Ok(ConsoleColor::from(attrs & 0xF)) } /** Returns a `HistoryInfo` object containing information about console input history settings. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let history_settings = console::get_history_info().unwrap(); println!("{:?}", history_settings); # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_history_info() -> WinResult<HistoryInfo> { let mut info: CONSOLE_HISTORY_INFO = unsafe { mem::zeroed() }; info.cbSize = mem::size_of::<CONSOLE_HISTORY_INFO>() as DWORD; os_err!(unsafe { wincon::GetConsoleHistoryInfo(&mut info) }); let mut history = HistoryInfo::default(); history.size = info.HistoryBufferSize; history.number_of_buffers = info.NumberOfHistoryBuffers; history.duplicates_allowed = info.dwFlags & 0x1 == 0; Ok(history) } /** Returns the input code page used by the console. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let page = console::get_input_code_page(); println!("{}", page); # } ``` */ pub fn get_input_code_page() -> CodePage { CodePage::from(unsafe { consoleapi::GetConsoleCP() } as u16) } /** Returns settings related to console input. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let mode = console::get_input_mode().unwrap(); println!("{}", mode); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console input is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_input_mode() -> WinResult<InputSettings> { let mode = get_mode(STDIN)?; Ok(InputSettings::from(mode)) } /** Returns a list of installed code pages. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let pages = console::get_installed_code_pages().unwrap(); for page in pages { println!("{}", page); } # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_installed_code_pages() -> WinResult<Vec<CodePage>> { get_code_pages(1) } /** Returns the size of the largest possible console window in character cells, based on the current font and the size of the display. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let largest_size = console::get_largest_window_size().unwrap(); println!("Largest size: {:?}", largest_size); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_largest_window_size() -> WinResult<Vector2<u16>> { let coord = unsafe { let handle = handle!(STDOUT); wincon::GetLargestConsoleWindowSize(handle) }; if coord.X == 0 && coord.Y == 0 { return os_err!(); } Ok(Vector2::new(coord.X as u16, coord.Y as u16)) } /** Returns the original title of the console window. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let original_title = console::get_original_title().unwrap(); println!("{}", original_title); # } ``` # Errors * [`FromUtf8Error`]: Returned if an error occurs while converting to a string. * [`IoError`]: Returned if an OS error occurs. [`FromUtf8Error`]: ../errors/enum.WinError.html#FromUtf8.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_original_title() -> WinResult<String> { let mut buffer: [CHAR; MAX_PATH] = [0; MAX_PATH]; let length = unsafe { let buffer_p = &mut buffer[0] as *mut CHAR; wincon::GetConsoleOriginalTitleA(buffer_p, MAX_PATH as u32) }; os_err!(length, true); Ok(buf_to_str!(buffer)) } /** Returns the output code page used by the console. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let page = console::get_output_code_page(); println!("{}", page); # } ``` */ pub fn get_output_code_page() -> CodePage { CodePage::from(unsafe { consoleapi::GetConsoleOutputCP() } as u16) } /** Returns settings related to console output. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let mode = console::get_output_mode().unwrap(); println!("{}", mode); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_output_mode() -> WinResult<OutputSettings> { let mode = get_mode(STDOUT)?; Ok(OutputSettings::from(mode)) } /** Returns the current scroll position of a window scroll bar. # Arguments * `vertical` - Should the position of the vertical bar be returned, or the horizontal bar? # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let vertical_position = console::get_scroll_position(true).unwrap(); println!("{}", vertical_position); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_scroll_position(vertical: bool) -> WinResult<u16> { let rect = get_screen_buffer_info()?.srWindow; if vertical { Ok(rect.Top as u16) } else { Ok(rect.Left as u16) } } /** Returns a `SelectionInfo` object containing information about console selection. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let selection = console::get_selection_info().unwrap(); println!("{:?}", selection); # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_selection_info() -> WinResult<SelectionInfo> { let mut info: CONSOLE_SELECTION_INFO = unsafe { mem::zeroed() }; os_err!(unsafe { wincon::GetConsoleSelectionInfo(&mut info) }); let anchor = info.dwSelectionAnchor; let rect = info.srSelection; let flags = info.dwFlags; let rect = Rect::new( rect.Top as u16, rect.Left as u16, rect.Bottom as u16, rect.Top as u16, ); let mut selection = SelectionInfo::default(); selection.anchor = Vector2::new(anchor.X as u16, anchor.Y as u16); selection.empty = flags & 0x2 == 0; selection.mouse_down = flags & 0x8 != 0; selection.rect = rect; selection.selecting = flags & 0x1 != 0; Ok(selection) } /** Returns a `ConsoleState` object containing information about the current state of the console. # Arguments * `copy_output` - Should the state contain information about the output buffer? * `copy_all` - Should the state copy all of the output buffer (as opposed to reading the buffer from the start to the current cursor position)? # Examples Retrieves the state of the console, copying the output up to the location of the console cursor. ``` # extern crate winconsole; # use winconsole::console; # fn main() { let state = console::get_state(true, false).unwrap(); println!("{}", state.output.len()); # } ``` # Errors * [`FromUtf8Error`]: Returned if an error occurs while converting to a string. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`FromUtf8Error`]: ../errors/enum.WinError.html#FromUtf8.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_state(copy_output: bool, copy_all: bool) -> WinResult<ConsoleState> { let mut state = ConsoleState::default(); let buffer_size = get_buffer_size()?; let cursor_position = get_cursor_position()?; state.background_color = get_background_color()?; state.buffer_size = buffer_size; state.color_mapping = get_color_mapping()?; state.cursor_position = cursor_position; state.cursor_size = get_cursor_size()?; state.cursor_visible = is_cursor_visible()?; state.font = get_font()?; state.foreground_color = get_foreground_color()?; state.input_code_page = get_input_code_page(); state.input_mode = get_input_mode()?; state.output_code_page = get_output_code_page(); state.output_mode = get_output_mode()?; state.title = get_title()?; if copy_output { let length: u32 = if copy_all { u32::from(buffer_size.x) * u32::from(buffer_size.y) } else { u32::from(buffer_size.x) * u32::from(cursor_position.y) + u32::from(cursor_position.x) }; state.output = read_output(0, 0, length)?; state.output_colors = read_output_colors(0, 0, length)?; } Ok(state) } /** Returns a list of supported code pages. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let pages = console::get_supported_code_pages().unwrap(); for page in pages { println!("{}", page); } # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_supported_code_pages() -> WinResult<Vec<CodePage>> { get_code_pages(2) } /** Returns the title of the console window. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let title = console::get_title().unwrap(); println!("{}", title); # } ``` # Errors * [`FromUtf8Error`]: Returned if an error occurs while converting to a string. * [`IoError`]: Returned if an OS error occurs. [`FromUtf8Error`]: ../errors/enum.WinError.html#FromUtf8.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_title() -> WinResult<String> { let mut buffer: [CHAR; MAX_PATH] = [0; MAX_PATH]; let length = unsafe { let buffer_p = &mut buffer[0] as *mut CHAR; wincon::GetConsoleTitleA(buffer_p, MAX_PATH as u32) }; os_err!(length, true); Ok(buf_to_str!(buffer)) } /** Returns the size of the window in character cells. These dimensions also serve as minimum values for the size of the buffer. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let size = console::get_window_size().unwrap(); println!("Minimum columns: {}. Minimum rows: {}.", size.x, size.y); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn get_window_size() -> WinResult<Vector2<u16>> { let rect = get_screen_buffer_info()?.srWindow; Ok(Vector2::new( (rect.Right - rect.Left + 1) as u16, (rect.Bottom - rect.Top + 1) as u16, )) } /** Returns a boolean representing whether or not the console cursor is visible. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let visible = console::is_cursor_visible().unwrap(); println!("Is the cursor visible? {}", visible); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn is_cursor_visible() -> WinResult<bool> { let info = get_cursor_info()?; Ok(info.bVisible == 1) } /** Returns a boolean representing whether or not the supplied value is a valid code page. A code page is considered valid if it is installed on the system. # Arguments * `identifier` - The code page identifier to check. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let valid = console::is_valid_code_page(0); assert_eq!(valid, false); # } ``` */ pub fn is_valid_code_page(identifier: u16) -> bool { let valid = unsafe { winnls::IsValidCodePage(u32::from(identifier)) }; valid != 0 } /** Maps a `ConsoleColor` to an RGB8 value. # Arguments * `color` - The `ConsoleColor` to map. * `rgb` - The RGB color which the `ConsoleColor` should represent. # Examples Maps `ConsoleColor::Black` to white. ``` # extern crate winconsole; # extern crate rgb; # use winconsole::console; # use winconsole::console::ConsoleColor; # fn main() { use rgb::RGB8; console::map_color(ConsoleColor::Black, RGB8 { r: 255, g: 255, b: 255 }).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn map_color(color: ConsoleColor, rgb: RGB8) -> WinResult<()> { let mut info = get_screen_buffer_info_ex()?; info.ColorTable[color.get_value() as usize] = make_colorref!(rgb); info.srWindow.Bottom += 1; info.srWindow.Right += 1; set_screen_buffer_info_ex(&mut info) } /** Moves data from a rectangle of the console output to another point in the output. The effects of the move can be limited by specifying a clipping rectangle, so the contents of the console screen buffer outside the clipping rectangle are unchanged. # Arguments * `scroll` - The rectangle to be moved. * `dest` - The upper-left corner of the new location of the contents. * `clip` - An optional clipping rectangle. * `fill_char` - A character to fill in spaces which were left empty as a result of the move. * `fill_fg_color` - The foreground to fill in spaces which were left empty as a result of the move. * `fill_bg_color` - The background to fill in spaces which were left empty as a result of the move. # Examples ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::{Rect, Vector2}; # fn main() { let scroll = Rect::new(0, 0, 10, 10); let dest = Vector2::new(0, 3); console::move_contents(scroll, dest, None, None, None, None).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn move_contents( scroll: Rect, dest: Vector2<i16>, clip: impl Into<Option<Rect>>, fill_char: impl Into<Option<char>>, fill_fg_color: impl Into<Option<ConsoleColor>>, fill_bg_color: impl Into<Option<ConsoleColor>>, ) -> WinResult<()> { let fill_char = match fill_char.into() { Some(f) => f, None => ' ', }; let attrs = { let fg_color = match fill_fg_color.into() { Some(f) => f, None => get_foreground_color()?, }; let bg_color = match fill_bg_color.into() { Some(f) => f, None => get_background_color()?, }; ((bg_color as WORD) << 4) | (fg_color as WORD) }; let dest = COORD { X: dest.x, Y: dest.y, }; let scroll = SMALL_RECT { Top: scroll.top as i16, Bottom: scroll.bottom as i16, Left: scroll.left as i16, Right: scroll.right as i16, }; os_err!(unsafe { let handle = handle!(STDOUT); let scroll_p = &scroll as *const SMALL_RECT; let clip_p = match clip.into() { Some(c) => { let rect = SMALL_RECT { Top: c.top as i16, Bottom: c.bottom as i16, Left: c.left as i16, Right: c.right as i16, }; &rect as *const SMALL_RECT } None => ptr::null(), }; let info_p = { let mut char_info: CHAR_INFO = mem::zeroed(); let mut chr: CHAR_INFO_Char = mem::zeroed(); *chr.AsciiChar_mut() = fill_char as CHAR; char_info.Attributes = attrs; char_info.Char = chr; &char_info as *const CHAR_INFO }; wincon::ScrollConsoleScreenBufferA(handle, scroll_p, clip_p, dest, info_p) }); Ok(()) } /** Reads a string from the console output starting at a specified location. Note that this method reads the output buffer _directly_ (i.e., an empty end of a line will be made up of multiple space characters rather than a newline character sequence). # Arguments * `column` - The column at which reading should begin. * `row` - The row at which reading should begin. * `max_length` - The maximum amount of characters to read. If None, the entire output buffer is read. # Examples Reads the entire console output buffer. ``` # extern crate winconsole; # use winconsole::console; # fn main() { let output = console::read_output(0, 0, None).unwrap(); println!("{}", output.len()); # } ``` # Errors * [`ArgumentError`]: Returned if `column` or `row` is not within the output buffer. * [`FromUtf8Error`]: Returned if an error occurs while converting to a string. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`FromUtf8Error`]: ../errors/enum.WinError.html#FromUtf8.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn read_output(column: u16, row: u16, max_length: impl Into<Option<u32>>) -> WinResult<String> { let buffer_size = get_buffer_size()?; if column >= buffer_size.x { throw_err!(ArgumentError::new( "column", "column must be within the buffer" )); } else if row >= buffer_size.y { throw_err!(ArgumentError::new("row", "row must be within the buffer")); } let max_length = match max_length.into() { Some(len) => len, None => { let size = get_buffer_size()?; let con_length = DWORD::from(size.x) * DWORD::from(size.y); let start_pos = DWORD::from(column) * DWORD::from(row); if start_pos > con_length { return Ok(String::new()); } con_length - start_pos } }; if max_length == 0 { return Ok(String::new()); } let mut num: DWORD = 0; let mut buffer: Box<[CHAR]> = buf!(max_length as usize); let coords = COORD { X: column as i16, Y: row as i16, }; os_err!(unsafe { let handle = handle!(STDOUT); let buffer_p = &mut (*buffer)[0] as *mut CHAR; wincon::ReadConsoleOutputCharacterA(handle, buffer_p, max_length, coords, &mut num) }); Ok(buf_to_str!(buffer)) } /** Reads colors from the console output starting at a specified location, and returns a vector of tuples. The first item in each tuple is the foreground color, and the second is the background color. # Arguments * `column` - The column at which reading should begin. * `row` - The row at which reading should begin. * `max_length` - The maximum amount of colors to read. If None, the entire output buffer is read. # Examples Prints the colors in the first cell. ``` # extern crate winconsole; # use winconsole::console; # fn main() { let colors = console::read_output_colors(0, 0, 1).unwrap(); println!("{} {}", colors[0].0, colors[0].1); # } ``` # Errors * [`ArgumentError`]: Returned if `column` or `row` is not within the output buffer. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn read_output_colors( column: u16, row: u16, max_length: impl Into<Option<u32>>, ) -> WinResult<Vec<(ConsoleColor, ConsoleColor)>> { let buffer_size = get_buffer_size()?; if column >= buffer_size.x { throw_err!(ArgumentError::new( "column", "column must be within the buffer" )); } else if row >= buffer_size.y { throw_err!(ArgumentError::new("row", "row must be within the buffer")); } let max_length = match max_length.into() { Some(len) => len, None => { let size = get_buffer_size()?; let con_length = DWORD::from(size.x) * DWORD::from(size.y); let start_pos = DWORD::from(column) * DWORD::from(row); if start_pos > con_length { return Ok(Vec::new()); } con_length - start_pos } }; if max_length == 0 { return Ok(Vec::new()); } let mut num: DWORD = 0; let mut buffer: Box<[WORD]> = buf!(max_length as usize); let coords = COORD { X: column as i16, Y: row as i16, }; os_err!(unsafe { let handle = handle!(STDOUT); let buffer_p = &mut (*buffer)[0] as *mut WORD; wincon::ReadConsoleOutputAttribute(handle, buffer_p, max_length, coords, &mut num) }); let vec: Vec<(ConsoleColor, ConsoleColor)> = buffer .iter() .map(|attrs| { ( ConsoleColor::from(attrs & 0xF), ConsoleColor::from((attrs & 0xF0) >> 4), ) }) .collect(); Ok(vec) } /** Scrolls the console window by the specified amount relative to its current position, in character cells. If the resultant position is greater than the maximum scroll position, the window is scrolled to the maximum position. # Arguments * `amount` - The amount to scroll by. * `vertical` - Should the window scroll vertically, or horizontally? # Examples Scrolls down 5 rows. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::scroll_by(5, true).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn scroll_by(amount: i16, vertical: bool) -> WinResult<()> { let position = get_screen_buffer_info()?.srWindow.Top; scroll(position + amount, 1, vertical) } /** Scrolls the console window to the specified position, in character cells. If the specified position is greater than the maximum scroll position, the window is scrolled to the maximum position. # Arguments * `position` - The position to scroll to. * `vertical` - Should the window scroll vertically, or horizontally? # Examples Scrolls to the top of the window. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::scroll_to(0, true).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn scroll_to(position: u16, vertical: bool) -> WinResult<()> { scroll(position as i16, 1, vertical) } /** Sets the background color of the console. # Arguments * `color` - The color which will be assigned to the background. # Examples ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::ConsoleColor; # fn main() { console::set_background_color(ConsoleColor::DarkBlue).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_background_color(color: ConsoleColor) -> WinResult<()> { let color = color as WORD; let current = get_text_attributes()?; set_text_attributes(color << 4 | (current & 0xF)) } /** Sets the size of the output buffer. # Arguments * `width` - The amount of columns the screen buffer should have. * `height` - The amount of rows the screen buffer should have. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::set_buffer_size(200, 100).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `width` or `height` is less than the window's minimum amounts. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_buffer_size(width: u16, height: u16) -> WinResult<()> { let window_size = get_window_size()?; if width < window_size.x { throw_err!(ArgumentError::new( "width", "width must be more than window width" )); } else if height < window_size.y { throw_err!(ArgumentError::new( "height", "height must be more than window height" )); } let coords = COORD { X: width as i16, Y: height as i16, }; os_err!(unsafe { let handle = handle!(STDOUT); wincon::SetConsoleScreenBufferSize(handle, coords) }); Ok(()) } /** Sets the color mapping of the console. The indices of the array correspond with `ConsoleColor` values. # Arguments * `mapping` - The color mapping to set. # Examples ``` # extern crate winconsole; # extern crate rgb; # use winconsole::console; # fn main() { use rgb::RGB8; let mut mapping = console::get_color_mapping().unwrap(); mapping[0] = RGB8 { r: 255, g: 255, b: 255 }; console::set_color_mapping(&mapping).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_color_mapping(mapping: &[RGB8; 16]) -> WinResult<()> { let mut info = get_screen_buffer_info_ex()?; let mut colors = info.ColorTable; for i in 0..16 { let color = mapping[i]; colors[i] = make_colorref!(color); } info.ColorTable = colors; info.srWindow.Bottom += 1; info.srWindow.Right += 1; set_screen_buffer_info_ex(&mut info) } /** Adds or removes a handler routine from the console. # Arguments * `routine` - The callback function. If this is None, a value of `true` for `add` will ignore CTRL + C input, and a value of `false` will restore normal processing. * `add` - Should the routine be added or removed? # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { unsafe extern "system" fn handler(event_type: u32) -> i32 { if event_type == 0 { println!("CTRL + C pressed."); return 1; // TRUE } return 0; // FALSE } console::set_ctrl_handler(Some(handler), true).unwrap(); # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v # See [`HandlerRoutine`](https://docs.microsoft.com/en-us/windows/console/handlerroutine). */ pub fn set_ctrl_handler(handler: Option<HandlerRoutine>, add: bool) -> WinResult<()> { os_err!(unsafe { consoleapi::SetConsoleCtrlHandler(handler, bool_to_num!(add)) }); Ok(()) } /** Sets the position of the console cursor. # Arguments * `column` - The column of the new cursor position. * `row` - The row of the new cursor position. # Examples Sets the cursor position to the start position of the console. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::set_cursor_position(0, 0).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `column` or `row` is not within the output buffer. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_cursor_position(column: u16, row: u16) -> WinResult<()> { let buffer_size = get_buffer_size()?; if column >= buffer_size.x { throw_err!(ArgumentError::new( "column", "column must be within the buffer bounds" )); } else if row >= buffer_size.y { throw_err!(ArgumentError::new( "row", "row must be within the buffer bounds" )); } let coords = COORD { X: column as i16, Y: row as i16, }; os_err!(unsafe { let handle = handle!(STDOUT); wincon::SetConsoleCursorPosition(handle, coords) }); Ok(()) } /** Sets the size of the console cursor. Must be between 0 and 100 (inclusive). # Arguments * `size` - The new cursor size. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::set_cursor_size(50).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `size` exceeds 100. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_cursor_size(size: u8) -> WinResult<()> { if size > 100 { throw_err!(ArgumentError::new( "size", "size must be in [0, 100] (inclusive)" )); } let mut info = get_cursor_info()?; info.dwSize = u32::from(size); set_cursor_info(info)?; Ok(()) } /** Sets the visibility of the console cursor. # Arguments * `visible` - True if the cursor should be visible, false otherwise. # Examples Hides the console cursor. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::set_cursor_visible(false).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_cursor_visible(visible: bool) -> WinResult<()> { let mut info = get_cursor_info()?; info.bVisible = bool_to_num!(visible); set_cursor_info(info)?; Ok(()) } /** Sets information about the console font. # Arguments * `font` - A `ConsoleFont` which contains the font information. # Examples Changes the console font to Consolas. ``` # extern crate winconsole; # use winconsole::console; # fn main() { let mut font = console::get_font().unwrap(); font.name = "Consolas".to_string(); console::set_font(&font).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_font(font: &ConsoleFont) -> WinResult<()> { let mut info: CONSOLE_FONT_INFOEX = unsafe { mem::zeroed() }; info.nFont = font.index as DWORD; info.dwFontSize = COORD { X: font.size.x as i16, Y: font.size.y as i16, }; info.FontFamily = font.family as UINT; info.FontWeight = font.weight as UINT; info.FaceName = str_to_buf_w!(font.name, 32); set_font_info_ex(&mut info, false) } /** Sets the foreground color of the console. # Arguments * `color` - The color which will be assigned to the foreground. # Examples ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::ConsoleColor; # fn main() { console::set_foreground_color(ConsoleColor::Red).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_foreground_color(color: ConsoleColor) -> WinResult<()> { let color = color as WORD; let current = get_text_attributes()?; set_text_attributes((current & 0xF0) | color) } /** Sets information about console input history settings. # Arguments * `history` - The `HistoryInfo` to assign. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let mut history_settings = console::get_history_info().unwrap(); history_settings.duplicates_allowed = false; console::set_history_info(history_settings).unwrap(); # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_history_info(history: HistoryInfo) -> WinResult<()> { let mut info: CONSOLE_HISTORY_INFO = unsafe { mem::zeroed() }; info.cbSize = mem::size_of::<CONSOLE_HISTORY_INFO>() as DWORD; info.HistoryBufferSize = history.size; info.NumberOfHistoryBuffers = history.number_of_buffers; info.dwFlags = bool_to_num!(!history.duplicates_allowed); os_err!(unsafe { wincon::SetConsoleHistoryInfo(&mut info) }); Ok(()) } /** Sets the input code page to be used by the console. # Arguments * `page` - The code page to use. # Examples ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::CodePage; # fn main() { console::set_input_code_page(CodePage::utf_8).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `page` is `CodePage::None` or `CodePage::Invalid`. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_input_code_page(page: CodePage) -> WinResult<()> { if page == CodePage::None || page == CodePage::Invalid { throw_err!(ArgumentError::new( "page", "page cannot be CodePage::None or CodePage::Invalid" )); } let page: u16 = page.into(); os_err!(unsafe { wincon::SetConsoleCP(u32::from(page)) }); Ok(()) } /** Sets settings related to console input. # Arguments * `settings` - Settings to assign to the console input. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let mut mode = console::get_input_mode().unwrap(); mode.InsertMode = true; console::set_input_mode(mode).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `settings.LineInput` is disabled while `settings.EchoInput` is enabled. * [`InvalidHandleError`]: Returned if an invalid handle to the console input is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_input_mode(settings: InputSettings) -> WinResult<()> { if settings.EchoInput && !settings.LineInput { throw_err!(ArgumentError::new( "settings", "disabling LineInput requires EchoInput to be disabled" )); } let mode: u32 = settings.into(); set_mode(STDIN, mode)?; Ok(()) } /** Sets the output code page to be used by the console. # Arguments * `page` - The code page to use. # Examples ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::CodePage; # fn main() { console::set_output_code_page(CodePage::IBM437).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `page` is `CodePage::None` or `CodePage::Invalid`. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_output_code_page(page: CodePage) -> WinResult<()> { if page == CodePage::None || page == CodePage::Invalid { throw_err!(ArgumentError::new( "page", "page cannot be CodePage::None or CodePage::Invalid" )); } let page: u16 = page.into(); os_err!(unsafe { wincon::SetConsoleOutputCP(u32::from(page)) }); Ok(()) } /** Sets settings related to console output. # Arguments * `settings` - Settings to assign to the console output. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let mut mode = console::get_output_mode().unwrap(); mode.WrapAtEol = false; mode.DisableNewlineAutoReturn = true; console::set_output_mode(mode).unwrap(); # } ``` # Errors * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_output_mode(settings: OutputSettings) -> WinResult<()> { let mode: u32 = settings.into(); set_mode(STDOUT, mode) } /** Sets the state of the console to a `ConsoleState`. # Arguments * `state` - A `ConsoleState` containing state information. * `clear` - Should the console be cleared before writing to the output? * `write_output` - Should the stored text be written to the output? # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { println!("Message 1."); let state = console::get_state(true, false).unwrap(); println!("Message 2."); console::set_state(&state, true, true).unwrap(); println!("Great Scott!"); # } ``` # Errors * [`ArgumentError`]: Returned if data in the state is invalid. * [`FromUtf8Error`]: Returned if an error occurs while converting to a string. * [`InvalidHandleError`]: Returned if an invalid handle to the console input/output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`FromUtf8Error`]: ../errors/enum.WinError.html#FromUtf8.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_state(state: &ConsoleState, clear: bool, write_output: bool) -> WinResult<()> { set_background_color(state.background_color)?; set_color_mapping(&state.color_mapping)?; set_cursor_size(state.cursor_size)?; set_foreground_color(state.foreground_color)?; set_input_code_page(state.input_code_page)?; set_output_code_page(state.output_code_page)?; set_input_mode(state.input_mode)?; set_output_mode(state.output_mode)?; set_font(&state.font)?; set_title(&state.title)?; if clear { self::clear()?; } if write_output { write_output_colors(&state.output_colors, 0, 0)?; self::write_output(&state.output, 0, 0)?; } set_cursor_position(state.cursor_position.x, state.cursor_position.y)?; set_buffer_size(state.buffer_size.x, state.buffer_size.y)?; Ok(()) } /** Sets the title of the console window. # Arguments * `title` - The string to use as the title. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::set_title("My Console").unwrap(); # } ``` # Errors * [`IoError`]: Returned if an OS error occurs. [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_title(title: &str) -> WinResult<()> { let mut buffer = str_to_buf!(title, MAX_PATH); os_err!(unsafe { let buffer_p = &mut buffer[0] as *mut CHAR; wincon::SetConsoleTitleA(buffer_p) }); Ok(()) } /** Sets the size of the console window in character cells. If the screen buffer is too small for the new size, it is resized as well. # Examples ``` # extern crate winconsole; # use winconsole::console; # fn main() { let size = console::get_window_size().unwrap(); console::set_window_size(size.x + 10, size.y + 10).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if either `columns` or `rows` is less than zero, exceeds the maximum window size, or if addition will result in a value which is greater than the i16 maximum value. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn set_window_size(columns: u16, rows: u16) -> WinResult<()> { if columns == 0 { throw_err!(ArgumentError::new( "columns", "columns must greater than zero" )); } else if rows == 0 { throw_err!(ArgumentError::new("rows", "rows must greater than zero")); } let csbi = get_screen_buffer_info()?; let buffer_size = csbi.dwSize; let mut window_rect = csbi.srWindow; let mut needs_resize = false; let mut resize_x = buffer_size.X; let mut resize_y = buffer_size.Y; let columns_i16 = columns as i16; let rows_i16 = rows as i16; let left = window_rect.Left; let top = window_rect.Top; if buffer_size.X < left + columns_i16 { if window_rect.Left >= std::i16::MAX - columns_i16 { throw_err!(ArgumentError::new( "columns", "(window left + columns) is greater than i16::MAX" )); } resize_x = left + columns_i16; needs_resize = true; } if buffer_size.Y < top + rows_i16 { if window_rect.Top >= std::i16::MAX - rows_i16 { throw_err!(ArgumentError::new( "rows", "(window top + rows) is greater than i16::MAX" )); } resize_y = top + rows_i16; needs_resize = true; } if needs_resize { set_buffer_size(resize_x as u16, resize_y as u16)?; } window_rect.Right = left + columns_i16 - 1; window_rect.Bottom = top + rows_i16 - 1; unsafe { let handle = handle!(STDOUT); let rect_p = &window_rect as *const SMALL_RECT; if wincon::SetConsoleWindowInfo(handle, 1, rect_p) == 0 { let err = os_err!(); if needs_resize { wincon::SetConsoleScreenBufferSize(handle, buffer_size); } let max = wincon::GetLargestConsoleWindowSize(handle); if columns > (max.X as u16) { throw_err!(ArgumentError::new( "columns", "columns is greater than maximum window columns" )); } else if rows > (max.Y as u16) { throw_err!(ArgumentError::new( "rows", "rows is greater than maximum window rows" )); } return err; } } Ok(()) } /** Writes characters to the output at a specified position, and returns the number of cells which were written to. Note that this method writes characters _directly_ to the output buffer (i.e., newline characters do not move output to the next line, but instead write the newline character). # Arguments * `string` - The string to write to the output. * `column` - The column at which writing will begin. * `row` - The row at which writing will begin. # Examples Writes `"Hello, world!"` on the 10th row starting at the 10th column. ``` # extern crate winconsole; # use winconsole::console; # fn main() { console::write_output("Hello, world!", 10, 10).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `column` or `row` is not within the output buffer. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn write_output(string: &str, column: u16, row: u16) -> WinResult<u32> { let buffer_size = get_buffer_size()?; if column >= buffer_size.x { throw_err!(ArgumentError::new( "column", "column must be within the buffer" )); } else if row >= buffer_size.y { throw_err!(ArgumentError::new("row", "row must be within the buffer")); } let mut num: DWORD = 0; let coords = COORD { X: column as i16, Y: row as i16, }; let chars: Box<[CHAR]> = str_to_buf!(string); let length = chars.len() as DWORD; if length == 0 { return Ok(0); } os_err!(unsafe { let handle = handle!(STDOUT); let chars_p = &(*chars)[0] as *const CHAR; wincon::WriteConsoleOutputCharacterA(handle, chars_p, length, coords, &mut num) }); Ok(num) } /** Changes the output colors starting at a specified position, and returns the number of cells which were written to. # Arguments * `colors` - The colors to write to the console. The first item in each tuple is the foreground color, and the second is the background color. * `column` - The column at which writing will begin. * `row` - The row at which writing will begin. # Examples Writes colors to the console starting at <0, 0>. ``` # extern crate winconsole; # use winconsole::console; # use winconsole::console::ConsoleColor; # fn main() { let colors = vec![ (ConsoleColor::Red, ConsoleColor::Blue), (ConsoleColor::Blue, ConsoleColor::Red), (ConsoleColor::Red, ConsoleColor::Blue), (ConsoleColor::Blue, ConsoleColor::Red) ]; console::write_output_colors(&colors, 0, 0).unwrap(); # } ``` # Errors * [`ArgumentError`]: Returned if `column` or `row` is not within the output buffer. * [`InvalidHandleError`]: Returned if an invalid handle to the console output is retrieved or used. * [`IoError`]: Returned if an OS error occurs. [`ArgumentError`]: ../errors/enum.WinError.html#Argument.v [`InvalidHandleError`]: ../errors/enum.WinError.html#InvalidHandle.v [`IoError`]: ../errors/enum.WinError.html#Io.v */ pub fn write_output_colors( colors: &[(ConsoleColor, ConsoleColor)], column: u16, row: u16, ) -> WinResult<u32> { let buffer_size = get_buffer_size()?; if column >= buffer_size.x { throw_err!(ArgumentError::new( "column", "column must be within the buffer" )); } else if row >= buffer_size.y { throw_err!(ArgumentError::new("row", "row must be within the buffer")); } let mut num: DWORD = 0; let coords = COORD { X: column as i16, Y: row as i16, }; let length = colors.len() as DWORD; if length == 0 { return Ok(0); } let attrs: Box<[WORD]> = { let res: Vec<WORD> = colors .iter() .map(|&(ref fg, ref bg)| WORD::from(fg.get_value() | ((bg.get_value()) << 4))) .collect(); res.into_boxed_slice() }; os_err!(unsafe { let handle = handle!(STDOUT); let attrs_p = &(*attrs)[0] as *const WORD; wincon::WriteConsoleOutputAttribute(handle, attrs_p, length, coords, &mut num) }); Ok(num) } fn fill_attributes(attributes: WORD, length: DWORD, coords: COORD) -> WinResult<DWORD> { let mut num: DWORD = 0; os_err!(unsafe { let handle = handle!(STDOUT); wincon::FillConsoleOutputAttribute(handle, attributes, length, coords, &mut num) }); Ok(num) } fn fill_char(character: CHAR, length: DWORD, coords: COORD) -> WinResult<DWORD> { let mut num: DWORD = 0; os_err!(unsafe { let handle = handle!(STDOUT); wincon::FillConsoleOutputCharacterA(handle, character, length, coords, &mut num) }); Ok(num) } fn get_code_pages(flags: u32) -> WinResult<Vec<CodePage>> { unsafe extern "system" fn enum_pages(ptr: *mut i8) -> i32 { let mut identifier = String::new(); let mut offset = 0; loop { let chr = *ptr.offset(offset) as u8 as char; if chr == '\0' { break; } identifier.push(chr); offset += 1; } if let Ok(id) = identifier.parse::<u16>() { let cp = CodePage::from(id); if cp != CodePage::Invalid { match PAGES.lock() { Ok(mut pages) => pages.push(cp), Err(_) => return 0, } } } 1 } os_err!(unsafe { winnls::EnumSystemCodePagesA(Some(enum_pages), flags) }); match PAGES.lock() { Ok(mut pages) => { let ret = pages.clone(); pages.clear(); Ok(ret) } Err(err) => { let mut pages = err.into_inner(); let ret = pages.clone(); pages.clear(); Ok(ret) } } } fn get_cursor_info() -> WinResult<CONSOLE_CURSOR_INFO> { let mut info: CONSOLE_CURSOR_INFO = unsafe { mem::zeroed() }; os_err!(unsafe { let handle = handle!(STDOUT); wincon::GetConsoleCursorInfo(handle, &mut info) }); Ok(info) } fn get_font_info_ex(maximum: bool) -> WinResult<CONSOLE_FONT_INFOEX> { let mut info: CONSOLE_FONT_INFOEX = unsafe { mem::zeroed() }; os_err!(unsafe { let handle = handle!(STDOUT); info.cbSize = mem::size_of::<CONSOLE_FONT_INFOEX>() as DWORD; wincon::GetCurrentConsoleFontEx(handle, bool_to_num!(maximum), &mut info) }); Ok(info) } fn get_mode(handle_id: DWORD) -> WinResult<DWORD> { let mut num: DWORD = 0; os_err!(unsafe { let handle = handle!(handle_id); consoleapi::GetConsoleMode(handle, &mut num) }); Ok(num) } fn get_screen_buffer_info() -> WinResult<CONSOLE_SCREEN_BUFFER_INFO> { let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = unsafe { mem::zeroed() }; os_err!(unsafe { let handle = handle!(STDOUT); wincon::GetConsoleScreenBufferInfo(handle, &mut csbi) }); Ok(csbi) } fn get_screen_buffer_info_ex() -> WinResult<CONSOLE_SCREEN_BUFFER_INFOEX> { let mut csbi: CONSOLE_SCREEN_BUFFER_INFOEX = unsafe { mem::zeroed() }; os_err!(unsafe { let handle = handle!(STDOUT); csbi.cbSize = mem::size_of::<CONSOLE_SCREEN_BUFFER_INFOEX>() as DWORD; wincon::GetConsoleScreenBufferInfoEx(handle, &mut csbi) }); Ok(csbi) } fn get_text_attributes() -> WinResult<WORD> { let csbi = get_screen_buffer_info()?; Ok(csbi.wAttributes) } fn scroll(position: i16, absolute: i32, vertical: bool) -> WinResult<()> { let buffer_size = get_buffer_size()?; let mut rect = get_screen_buffer_info()?.srWindow; let mut position = position; if vertical { let max = buffer_size.y as i16 - rect.Bottom - 1; let diff = rect.Bottom - rect.Top; if position > max { position = max; } else if position < 0 { position = 0; } rect.Top = position; rect.Bottom = position + diff; } else { let max = buffer_size.x as i16 - rect.Right - 1; let diff = rect.Right - rect.Left; if position > max { position = max; } else if position < 0 { position = 0; } rect.Left = position; rect.Right = position + diff; } os_err!(unsafe { let handle = handle!(STDOUT); let rect_p = &rect as *const SMALL_RECT; wincon::SetConsoleWindowInfo(handle, absolute, rect_p) }); Ok(()) } fn set_cursor_info(value: CONSOLE_CURSOR_INFO) -> WinResult<()> { os_err!(unsafe { let handle = handle!(STDOUT); let value_p = &value as *const CONSOLE_CURSOR_INFO; wincon::SetConsoleCursorInfo(handle, value_p) }); Ok(()) } fn set_font_info_ex(value: &mut CONSOLE_FONT_INFOEX, maximum: bool) -> WinResult<()> { os_err!(unsafe { let handle = handle!(STDOUT); value.cbSize = mem::size_of::<CONSOLE_FONT_INFOEX>() as DWORD; let value_p = value as *mut CONSOLE_FONT_INFOEX; wincon::SetCurrentConsoleFontEx(handle, bool_to_num!(maximum), value_p) }); Ok(()) } fn set_mode(handle_id: DWORD, value: DWORD) -> WinResult<()> { os_err!(unsafe { let handle = handle!(handle_id); consoleapi::SetConsoleMode(handle, value) }); Ok(()) } fn set_screen_buffer_info_ex(value: &mut CONSOLE_SCREEN_BUFFER_INFOEX) -> WinResult<()> { os_err!(unsafe { let handle = handle!(STDOUT); let value_p = value as *mut CONSOLE_SCREEN_BUFFER_INFOEX; wincon::SetConsoleScreenBufferInfoEx(handle, value_p) }); Ok(()) } fn set_text_attributes(value: WORD) -> WinResult<()> { os_err!(unsafe { let handle = handle!(STDOUT); wincon::SetConsoleTextAttribute(handle, value) }); Ok(()) }