All files / client keyboard.js

30.64% Statements 349/1139
8.12% Branches 35/431
23.57% Functions 29/123
30.69% Lines 338/1101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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          4x   8x                                       8x 8x 8x 8x 1536x     8x 8x 2048x 800x 800x 64x 64x         8x 8x 64x   8x   8x     8x 8x     8x 3x 3x 36x 36x   36x 36x       36x 36x 36x   36x 36x   36x                         8x 96x 96x 96x 96x                         96x         96x 96x   96x           96x           96x 8x     8x 8x     8x                                                                                 8x 3x 3x     8x 2x       8x 8x 8x 8x   8x           4x             4x 4x 4x 4x     4x 4x 4x   4x         4x 4x 4x     4x         4x         4x 4x     4x 4x 4x 4x 4x 4x 4x     4x     4x 4x     4x 4x 4x   4x 4x 4x   4x 4x 4x 4x     4x 4x   4x   3x 1x           4x 4x   4x   3x 1x           4x           4x 1x     4x 1x     4x       4x       4x       4x       4x       4x       4x       4x                 4x                   4x                                                                                                                                                           4x           4x           4x         4x 4x 4x 4x 4x 4x 4x 4x 4x   4x                                       4x 3x   3x   3x 3x 3x 3x 3x   3x                         3x                             3x           3x             3x                   3x                   3x                       3x                     3x   3x             3x       3x 3x 3x   3x                       4x 3x 3x 3x   3x                           3x                             3x                                                               3x                                                                       3x                                                         3x                                                                     3x                                 3x                                     3x                                   3x                                     3x                                 3x                                       3x                                                                                                                                         3x                                                                                                                                                                                                                                                                                       3x   3x                                                                                 3x 3x 3x             3x                   3x 2x 2x 2x 2x 2x 2x 2x   2x 2x     2x     3x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x     3x               3x               3x                                   4x   4x 4x 4x 4x 4x   4x 2x 2x 2x 2x 2x     2x 2x 2x 2x     4x               4x         4x 1x                       4x             4x                   4x                                                                                                                                                                         4x                                                                         4x   4x                     4x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x   9x   9x                                       9x                       9x                             9x 2x 2x     2x   2x 10x 10x 50x         10x 10x 50x 50x 50x   50x               50x   50x                       9x 2x 2x     2x   2x 10x 10x 50x         10x 10x 50x 50x 50x   50x               50x   50x                       9x                                                                     9x                                                                                                           9x                         9x                                                                                                                                                                   9x     9x 3x   3x 3x 3x 3x 3x 3x 3x           9x                               9x                                     9x                               9x                                     9x               9x                     9x               9x                     9x                       9x                       9x                                                                                             9x                                                                               9x                                                                                                                                                                                                   9x 3x 3x 3x 3x 3x 3x 3x 3x 3x       3x                 3x       3x                                       9x 3x 3x 3x 3x 3x 3x     3x                                                                                                                   3x 3x 3x 3x       9x       9x                                      
import State from './state.js';
import Toolbar from './toolbar.js';
import { $, createCanvas } from './ui.js';
import magicNumbers from './magicNumbers.js';
 
const createFKeys = () => {
	// Stolen "savagely" from Moebius, who stole it "mercilessly" from PabloDraw, thanks Curtis! lol
	const predefinedSets = [
		[218, 191, 192, 217, 196, 179, 195, 180, 193, 194, 32, 32],
		[201, 187, 200, 188, 205, 186, 204, 185, 202, 203, 32, 32],
		[213, 184, 212, 190, 205, 179, 198, 181, 207, 209, 32, 32],
		[214, 183, 211, 189, 196, 186, 199, 182, 208, 210, 32, 32],
		[197, 206, 216, 215, 232, 232, 155, 156, 153, 239, 32, 32],
		[176, 177, 178, 219, 223, 220, 221, 222, 254, 250, 7, 32],
		[1, 2, 3, 4, 5, 6, 240, 14, 15, 32, 32, 32],
		[24, 25, 30, 31, 16, 17, 18, 29, 20, 21, 32, 32],
		[174, 175, 242, 243, 169, 170, 253, 246, 171, 172, 32, 32],
		[227, 241, 244, 245, 234, 157, 228, 248, 251, 252, 32, 32],
		[224, 225, 226, 229, 230, 231, 235, 236, 237, 238, 32, 32],
		[128, 135, 165, 164, 152, 159, 247, 249, 173, 168, 32, 32],
		[131, 132, 133, 160, 166, 134, 142, 143, 145, 146, 32, 32],
		[136, 137, 138, 130, 144, 140, 139, 141, 161, 158, 32, 32],
		[147, 148, 149, 162, 167, 150, 129, 151, 163, 154, 32, 32],
		[47, 92, 40, 41, 123, 125, 91, 93, 96, 39, 32, 32],
	];
 
	// Generate additional sets to cover all 256 characters
	const generateCharSets = () => {
		const charSets = [...predefinedSets];
		const usedChars = new Set();
		predefinedSets.forEach(set => {
			set.forEach(char => usedChars.add(char));
		});
		// Generate sets for remaining characters
		let currentSet = [];
		for (let i = 0; i < 256; i++) {
			if (!usedChars.has(i)) {
				currentSet.push(i);
				if (currentSet.length === 12) {
					charSets.push([...currentSet]);
					currentSet = [];
				}
			}
		}
		// Add any remaining characters as a final set
		Eif (currentSet.length > 0) {
			while (currentSet.length < 12) {
				currentSet.push(32); // Pad with spaces
			}
			charSets.push(currentSet);
		}
		return charSets;
	};
 
	const fkeySets = generateCharSets();
	let currentSetIndex = 5; // Default to set 5 (blocks, half-blocks, etc.)
 
	// Update all fkey canvases with current set
	const updateFKeyDisplays = () => {
		const currentSet = fkeySets[currentSetIndex];
		for (let i = 0; i < 12; i++) {
			const canvas = $('fkey' + i);
			Eif (canvas) {
				// Set canvas internal dimensions
				canvas.width = State.font.getWidth();
				canvas.height = State.font.getHeight();
 
				// Keep CSS display size fixed at 1.5x of BASE font size
				// This maintains the original UI appearance regardless of zoom
				const baseWidth = State.fontWidth;
				const baseHeight = State.fontHeight;
				const fixedScale = 1.5;
 
				canvas.style.width = baseWidth * fixedScale + 'px';
				canvas.style.height = baseHeight * fixedScale + 'px';
 
				State.font.draw(
					currentSet[i],
					State.palette.getForegroundColor(),
					State.palette.getBackgroundColor(),
					canvas.getContext('2d'),
					0,
					0,
				);
			}
		}
	};
 
	// Initialize fkey canvases
	for (let i = 0; i < 12; i++) {
		const canvas = $('fkey' + i);
		const wrap = $('fkey' + i + 'w');
		Eif (canvas && wrap) {
			const insert = () => {
				State.textArtCanvas.startUndo();
				State.textArtCanvas.draw(callback => {
					callback(
						fkeySets[currentSetIndex][i],
						State.palette.getForegroundColor(),
						State.palette.getBackgroundColor(),
						State.cursor.getX(),
						State.cursor.getY(),
					);
				}, false);
				State.cursor.right();
			};
			wrap.addEventListener('click', insert);
		}
	}
 
	// Set up navigation
	const prevButton = $('fkeySetPrev');
	const nextButton = $('fkeySetNext');
 
	const previousCharacterSet = () => {
		currentSetIndex =
			currentSetIndex <= 0 ? fkeySets.length - 1 : currentSetIndex - 1;
		updateFKeyDisplays();
	};
 
	const nextCharacterSet = () => {
		currentSetIndex =
			currentSetIndex >= fkeySets.length - 1 ? 0 : currentSetIndex + 1;
		updateFKeyDisplays();
	};
 
	if (prevButton) {
		prevButton.addEventListener('click', previousCharacterSet);
	}
 
	Eif (nextButton) {
		nextButton.addEventListener('click', nextCharacterSet);
	}
 
	const keyDown = e => {
		// Handle F1-F12 function keys
		const fKeyMatch = e.code.match(/^F(\d+)$/);
		if (
			!e.altKey &&
			!e.ctrlKey &&
			!e.metaKey &&
			fKeyMatch &&
			fKeyMatch[1] >= 1 &&
			fKeyMatch[1] <= 12
		) {
			e.preventDefault();
			State.textArtCanvas.startUndo();
			State.textArtCanvas.draw(callback => {
				callback(
					fkeySets[currentSetIndex][fKeyMatch[1] - 1],
					State.palette.getForegroundColor(),
					State.palette.getBackgroundColor(),
					State.cursor.getX(),
					State.cursor.getY(),
				);
			}, false);
			State.cursor.right();
		}
		// 'Ctrl+[' - previous character set
		else if (e.ctrlKey && !e.altKey && !e.metaKey && e.code === 'BracketLeft') {
			e.preventDefault();
			previousCharacterSet();
		}
		// 'Ctrl+]' - next character set
		else if (
			e.ctrlKey &&
			!e.altKey &&
			!e.metaKey &&
			e.code === 'BracketRight'
		) {
			e.preventDefault();
			nextCharacterSet();
		}
	};
 
	const enable = () => {
		document.addEventListener('keydown', keyDown);
		updateFKeyDisplays();
	};
 
	const disable = () => {
		document.removeEventListener('keydown', keyDown);
	};
 
	// Update displays when palette/font changes
	document.addEventListener('onPaletteChange', updateFKeyDisplays);
	document.addEventListener('onForegroundChange', updateFKeyDisplays);
	document.addEventListener('onBackgroundChange', updateFKeyDisplays);
	document.addEventListener('onFontChange', updateFKeyDisplays);
 
	return {
		enable: enable,
		disable: disable,
	};
};
 
const calculateRowsPerScreen = (viewport, fontHeight) => {
	if (!viewport) {
		return 0;
	}
	return Math.floor(viewport.clientHeight / fontHeight);
};
 
const createCursor = canvasContainer => {
	const canvas = createCanvas(State.font.getWidth(), State.font.getHeight());
	const viewport = $('viewport');
	Iif (!viewport) {
		console.error('viewport element missing, focus scroll disabled');
	}
	let x = 0;
	let y = 0;
	let visible = false;
 
	const show = () => {
		canvas.style.display = 'block';
		visible = true;
	};
 
	const hide = () => {
		canvas.style.display = 'none';
		visible = false;
	};
 
	const startSelection = () => {
		State.selectionCursor.setStart(x, y);
		hide();
	};
 
	const endSelection = () => {
		State.selectionCursor.hide();
		show();
	};
 
	const move = (newX, newY) => {
		Iif (State.selectionCursor.isVisible()) {
			endSelection();
		}
		x = Math.min(Math.max(newX, 0), State.textArtCanvas.getColumns() - 1);
		y = Math.min(Math.max(newY, 0), State.textArtCanvas.getRows() - 1);
		const canvasWidth = State.font.getWidth();
		canvas.style.left = x * canvasWidth - 1 + 'px';
		canvas.style.top = y * State.font.getHeight() - 1 + 'px';
		State.positionInfo.update(x, y);
		State.pasteTool.setSelection(x, y, 1, 1);
 
		// Auto-scroll viewport to keep cursor visible
		scrollViewportToCursor();
	};
 
	const scrollViewportToCursor = () => {
		Iif (!viewport) {
			return;
		}
		const fontHeight = State.font.getHeight();
		const fontWidth = State.font.getWidth();
		const bufferRows = 5; // Number of rows as buffer
 
		const cursorPixelY = y * fontHeight;
		const cursorPixelX = x * fontWidth;
		const bufferPixels = bufferRows * fontHeight;
 
		const viewportHeight = viewport.clientHeight;
		const viewportWidth = viewport.clientWidth;
		const scrollTop = viewport.scrollTop;
		const scrollLeft = viewport.scrollLeft;
 
		// Check vertical scrolling
		const cursorTop = cursorPixelY - bufferPixels;
		const cursorBottom = cursorPixelY + fontHeight + bufferPixels;
 
		if (cursorTop < scrollTop) {
			// Cursor is above viewport, scroll up
			viewport.scrollTop = Math.max(0, cursorTop);
		} else Iif (cursorBottom > scrollTop + viewportHeight) {
			// Cursor is below viewport, scroll down
			viewport.scrollTop = Math.max(0, cursorBottom - viewportHeight);
		}
 
		// Check horizontal scrolling
		const cursorLeft = cursorPixelX - bufferRows * fontWidth;
		const cursorRight = cursorPixelX + fontWidth + bufferRows * fontWidth;
 
		if (cursorLeft < scrollLeft) {
			// Cursor is left of viewport, scroll left
			viewport.scrollLeft = Math.max(0, cursorLeft);
		} else Iif (cursorRight > scrollLeft + viewportWidth) {
			// Cursor is right of viewport, scroll right
			viewport.scrollLeft = Math.max(0, cursorRight - viewportWidth);
		}
	};
 
	const updateDimensions = () => {
		canvas.width = State.font.getWidth() + 1;
		canvas.height = State.font.getHeight() + 1;
		move(x, y);
	};
 
	const getX = () => {
		return x;
	};
 
	const getY = () => {
		return y;
	};
 
	const left = () => {
		move(x - 1, y);
	};
 
	const right = () => {
		move(x + 1, y);
	};
 
	const up = () => {
		move(x, y - 1);
	};
 
	const down = () => {
		move(x, y + 1);
	};
 
	const newLine = () => {
		move(0, y + 1);
	};
 
	const startOfCurrentRow = () => {
		move(0, y);
	};
 
	const endOfCurrentRow = () => {
		move(State.textArtCanvas.getColumns() - 1, y);
	};
 
	const pageUp = () => {
		const rowsPerScreen = calculateRowsPerScreen(
			viewport,
			State.font.getHeight(),
		);
		const newY = Math.max(0, y - rowsPerScreen);
		move(x, newY);
	};
 
	const pageDown = () => {
		const rowsPerScreen = calculateRowsPerScreen(
			viewport,
			State.font.getHeight(),
		);
		const maxY = State.textArtCanvas.getRows() - 1;
		const newY = Math.min(maxY, y + rowsPerScreen);
		move(x, newY);
	};
 
	const keyDown = e => {
		if (!e.ctrlKey && !e.altKey) {
			if (!e.shiftKey && !e.metaKey) {
				switch (e.code) {
					case 'Enter': // Enter key
						e.preventDefault();
						newLine();
						break;
					case 'End':
						e.preventDefault();
						endOfCurrentRow();
						break;
					case 'Home':
						e.preventDefault();
						startOfCurrentRow();
						break;
					case 'PageUp':
						e.preventDefault();
						pageUp();
						break;
					case 'PageDown':
						e.preventDefault();
						pageDown();
						break;
					case 'ArrowLeft':
						e.preventDefault();
						left();
						break;
					case 'ArrowUp':
						e.preventDefault();
						up();
						break;
					case 'ArrowRight':
						e.preventDefault();
						right();
						break;
					case 'ArrowDown':
						e.preventDefault();
						down();
						break;
					default:
						break;
				}
			} else if (e.metaKey && !e.shiftKey) {
				switch (e.code) {
					// Cmd/Meta + Left arrow
					case 'ArrowLeft':
						e.preventDefault();
						startOfCurrentRow();
						break;
					// Cmd/Meta + Right arrow
					case 'ArrowRight':
						e.preventDefault();
						endOfCurrentRow();
						break;
					default:
						break;
				}
			} else if (e.shiftKey && !e.metaKey) {
				// Shift + arrow keys trigger selection - switch to selection tool
				switch (e.code) {
					case 'ArrowLeft':
					case 'ArrowUp':
					case 'ArrowRight':
					case 'ArrowDown':
						e.preventDefault();
						// Set pending action so selection tool can apply it immediately
						State.selectionTool.setPendingAction(e.code);
						State.cursor.startSelection();
						Toolbar.switchTool('selection');
						break;
					default:
						break;
				}
			}
		}
	};
 
	const enable = () => {
		document.addEventListener('keydown', keyDown);
		show();
		State.pasteTool.setSelection(x, y, 1, 1);
	};
 
	const disable = () => {
		document.removeEventListener('keydown', keyDown);
		hide();
		State.pasteTool.disable();
	};
 
	const isVisible = () => {
		return visible;
	};
 
	// init
	canvas.classList.add('cursor');
	hide();
	canvasContainer.insertBefore(canvas, canvasContainer.firstChild);
	document.addEventListener('onLetterSpacingChange', updateDimensions);
	document.addEventListener('onTextCanvasSizeChange', updateDimensions);
	document.addEventListener('onFontChange', updateDimensions);
	document.addEventListener('onOpenedFile', updateDimensions);
	document.addEventListener('onScaleFactorChange', updateDimensions);
	move(x, y);
 
	return {
		show: show,
		hide: hide,
		move: move,
		getX: getX,
		getY: getY,
		left: left,
		right: right,
		up: up,
		down: down,
		newLine: newLine,
		startOfCurrentRow: startOfCurrentRow,
		endOfCurrentRow: endOfCurrentRow,
		enable: enable,
		disable: disable,
		isVisible: isVisible,
		startSelection: startSelection,
	};
};
 
const createSelectionCursor = element => {
	const cursor = createCanvas(0, 0);
	let sx, sy, dx, dy, x, y, width, height;
	let visible = false;
	// Marching ants animation state
	let dashOffset = 0;
	let animationId = null;
	const dashPattern = [4, 4]; // dash, gap length
	const dashSpeed = 0.1; // px per frame
	x = y = 0;
 
	const processCoords = () => {
		x = Math.min(sx, dx);
		y = Math.min(sy, dy);
		x = Math.max(x, 0);
		y = Math.max(y, 0);
		const columns = State.textArtCanvas.getColumns();
		const rows = State.textArtCanvas.getRows();
		width = Math.abs(dx - sx) + 1;
		height = Math.abs(dy - sy) + 1;
		width = Math.min(width, columns - x);
		height = Math.min(height, rows - y);
	};
 
	const drawBorder = () => {
		const ctx = cursor.getContext('2d');
		ctx.clearRect(0, 0, cursor.width, cursor.height);
		const antsColor = cursor.classList.contains('moveMode')
			? '#ff7518'
			: '#fff';
		ctx.save();
		ctx.strokeStyle = antsColor;
		ctx.lineWidth = 1;
		ctx.setLineDash(dashPattern);
		ctx.lineDashOffset = -dashOffset;
		ctx.strokeRect(1, 1, cursor.width - 2, cursor.height - 2);
		ctx.restore();
	};
 
	const animateBorder = () => {
		dashOffset = (dashOffset + dashSpeed) % (dashPattern[0] + dashPattern[1]);
		drawBorder();
		animationId = requestAnimationFrame(animateBorder);
	};
 
	const show = () => {
		cursor.style.display = 'block';
		if (!animationId) {
			animateBorder();
		}
	};
 
	const hide = () => {
		cursor.style.display = 'none';
		visible = false;
		State.pasteTool.disable();
		if (animationId) {
			cancelAnimationFrame(animationId);
			animationId = null;
		}
	};
 
	const updateCursor = () => {
		const fontWidth = State.font.getWidth();
		const fontHeight = State.font.getHeight();
		cursor.style.left = x * fontWidth - 1 + 'px';
		cursor.style.top = y * fontHeight - 1 + 'px';
		cursor.width = width * fontWidth + 1;
		cursor.height = height * fontHeight + 1;
		drawBorder();
	};
 
	const setStart = (startX, startY) => {
		sx = startX;
		sy = startY;
		processCoords();
		x = startX;
		y = startY;
		width = 1;
		height = 1;
		updateCursor();
		State.pasteTool.setSelection(x, y, width, height);
	};
 
	const setEnd = (endX, endY) => {
		show();
		dx = endX;
		dy = endY;
		processCoords();
		updateCursor();
		State.pasteTool.setSelection(x, y, width, height);
		visible = true;
		State.positionInfo.update(x, y);
	};
 
	const isVisible = () => visible;
 
	const getSelection = () => {
		if (visible) {
			return { x, y, width, height };
		}
		return null;
	};
 
	const getPos = () => {
		return { x, y };
	};
 
	cursor.classList.add('selectionCursor');
	cursor.style.display = 'none';
	element.appendChild(cursor);
 
	return {
		show,
		hide,
		setStart,
		setEnd,
		isVisible,
		getPos,
		getSelection,
		getElement: () => cursor,
	};
};
 
const createKeyboardController = () => {
	const fkeys = createFKeys();
	let enabled = false;
	let ignored = false;
 
	const draw = charCode => {
		State.textArtCanvas.startUndo();
		State.textArtCanvas.draw(callback => {
			callback(
				charCode,
				State.palette.getForegroundColor(),
				State.palette.getBackgroundColor(),
				State.cursor.getX(),
				State.cursor.getY(),
			);
		}, false);
		State.cursor.right();
	};
 
	const deleteText = () => {
		State.textArtCanvas.startUndo();
		State.textArtCanvas.draw(callback => {
			callback(
				magicNumbers.CHAR_NULL,
				magicNumbers.COLOR_WHITE,
				magicNumbers.COLOR_BLACK,
				State.cursor.getX() - 1,
				State.cursor.getY(),
			);
		}, false);
		State.cursor.left();
	};
 
	// Edit actions for insert, delete, and erase operations
	const insertRow = () => {
		const currentRows = State.textArtCanvas.getRows();
		const currentColumns = State.textArtCanvas.getColumns();
		const cursorY = State.cursor.getY();
		State.textArtCanvas.startUndo();
		const newImageData = new Uint16Array(currentColumns * (currentRows + 1));
		const oldImageData = State.textArtCanvas.getImageData();
 
		for (let y = 0; y < cursorY; y++) {
			for (let x = 0; x < currentColumns; x++) {
				newImageData[y * currentColumns + x] =
					oldImageData[y * currentColumns + x];
			}
		}
		for (let x = 0; x < currentColumns; x++) {
			newImageData[cursorY * currentColumns + x] = magicNumbers.BLANK_CELL;
		}
		for (let y = cursorY; y < currentRows; y++) {
			for (let x = 0; x < currentColumns; x++) {
				newImageData[(y + 1) * currentColumns + x] =
					oldImageData[y * currentColumns + x];
			}
		}
 
		State.textArtCanvas.setImageData(
			currentColumns,
			currentRows + 1,
			newImageData,
			State.textArtCanvas.getIceColors(),
		);
	};
 
	const deleteRow = () => {
		const currentRows = State.textArtCanvas.getRows();
		const currentColumns = State.textArtCanvas.getColumns();
		const cursorY = State.cursor.getY();
		if (currentRows <= 1) {
			return;
		} // Don't delete if only one row
		State.textArtCanvas.startUndo();
		const newImageData = new Uint16Array(currentColumns * (currentRows - 1));
		const oldImageData = State.textArtCanvas.getImageData();
 
		for (let y = 0; y < cursorY; y++) {
			for (let x = 0; x < currentColumns; x++) {
				newImageData[y * currentColumns + x] =
					oldImageData[y * currentColumns + x];
			}
		}
		// Skip the row at cursor position (delete it)
		// Copy rows after cursor position
		for (let y = cursorY + 1; y < currentRows; y++) {
			for (let x = 0; x < currentColumns; x++) {
				newImageData[(y - 1) * currentColumns + x] =
					oldImageData[y * currentColumns + x];
			}
		}
		State.textArtCanvas.setImageData(
			currentColumns,
			currentRows - 1,
			newImageData,
			State.textArtCanvas.getIceColors(),
		);
		if (State.cursor.getY() >= currentRows - 1) {
			State.cursor.move(State.cursor.getX(), currentRows - 2);
		}
	};
 
	const insertColumn = () => {
		const currentRows = State.textArtCanvas.getRows();
		const currentColumns = State.textArtCanvas.getColumns();
		const cursorX = State.cursor.getX();
		State.textArtCanvas.startUndo();
		const newImageData = new Uint16Array((currentColumns + 1) * currentRows);
		const oldImageData = State.textArtCanvas.getImageData();
 
		for (let y = 0; y < currentRows; y++) {
			for (let x = 0; x < cursorX; x++) {
				newImageData[y * (currentColumns + 1) + x] =
					oldImageData[y * currentColumns + x];
			}
			newImageData[y * (currentColumns + 1) + cursorX] =
				magicNumbers.BLANK_CELL;
 
			for (let x = cursorX; x < currentColumns; x++) {
				newImageData[y * (currentColumns + 1) + x + 1] =
					oldImageData[y * currentColumns + x];
			}
		}
		State.textArtCanvas.setImageData(
			currentColumns + 1,
			currentRows,
			newImageData,
			State.textArtCanvas.getIceColors(),
		);
	};
 
	const deleteColumn = () => {
		const currentRows = State.textArtCanvas.getRows();
		const currentColumns = State.textArtCanvas.getColumns();
		const cursorX = State.cursor.getX();
		if (currentColumns <= 1) {
			return;
		} // Don't delete if only one column
		State.textArtCanvas.startUndo();
		const newImageData = new Uint16Array((currentColumns - 1) * currentRows);
		const oldImageData = State.textArtCanvas.getImageData();
 
		for (let y = 0; y < currentRows; y++) {
			for (let x = 0; x < cursorX; x++) {
				newImageData[y * (currentColumns - 1) + x] =
					oldImageData[y * currentColumns + x];
			}
			// Skip the column at cursor position (delete it)
			for (let x = cursorX + 1; x < currentColumns; x++) {
				newImageData[y * (currentColumns - 1) + x - 1] =
					oldImageData[y * currentColumns + x];
			}
		}
 
		State.textArtCanvas.setImageData(
			currentColumns - 1,
			currentRows,
			newImageData,
			State.textArtCanvas.getIceColors(),
		);
 
		if (State.cursor.getX() >= currentColumns - 1) {
			State.cursor.move(currentColumns - 2, State.cursor.getY());
		}
	};
 
	const eraseRow = () => {
		const currentColumns = State.textArtCanvas.getColumns();
		const cursorY = State.cursor.getY();
		State.textArtCanvas.startUndo();
		for (let x = 0; x < currentColumns; x++) {
			State.textArtCanvas.draw(callback => {
				callback(
					magicNumbers.CHAR_SPACE,
					magicNumbers.COLOR_WHITE,
					magicNumbers.COLOR_BLACK,
					x,
					cursorY,
				);
			}, false);
		}
	};
 
	const eraseToStartOfRow = () => {
		const cursorX = State.cursor.getX();
		const cursorY = State.cursor.getY();
 
		State.textArtCanvas.startUndo();
 
		for (let x = 0; x <= cursorX; x++) {
			State.textArtCanvas.draw(callback => {
				callback(
					magicNumbers.CHAR_SPACE,
					magicNumbers.COLOR_WHITE,
					magicNumbers.COLOR_BLACK,
					x,
					cursorY,
				);
			}, false);
		}
	};
 
	const eraseToEndOfRow = () => {
		const currentColumns = State.textArtCanvas.getColumns();
		const cursorX = State.cursor.getX();
		const cursorY = State.cursor.getY();
		State.textArtCanvas.startUndo();
		for (let x = cursorX; x < currentColumns; x++) {
			State.textArtCanvas.draw(callback => {
				callback(
					magicNumbers.CHAR_SPACE,
					magicNumbers.COLOR_WHITE,
					magicNumbers.COLOR_BLACK,
					x,
					cursorY,
				);
			}, false);
		}
	};
 
	const eraseColumn = () => {
		const currentRows = State.textArtCanvas.getRows();
		const cursorX = State.cursor.getX();
 
		State.textArtCanvas.startUndo();
 
		for (let y = 0; y < currentRows; y++) {
			State.textArtCanvas.draw(callback => {
				callback(
					magicNumbers.CHAR_SPACE,
					magicNumbers.COLOR_WHITE,
					magicNumbers.COLOR_BLACK,
					cursorX,
					y,
				);
			}, false);
		}
	};
 
	const eraseToStartOfColumn = () => {
		const cursorX = State.cursor.getX();
		const cursorY = State.cursor.getY();
		State.textArtCanvas.startUndo();
		for (let y = 0; y <= cursorY; y++) {
			State.textArtCanvas.draw(callback => {
				callback(
					magicNumbers.CHAR_SPACE,
					magicNumbers.COLOR_WHITE,
					magicNumbers.COLOR_BLACK,
					cursorX,
					y,
				);
			}, false);
		}
	};
 
	const eraseToEndOfColumn = () => {
		const currentRows = State.textArtCanvas.getRows();
		const cursorX = State.cursor.getX();
		const cursorY = State.cursor.getY();
 
		State.textArtCanvas.startUndo();
 
		for (let y = cursorY; y < currentRows; y++) {
			State.textArtCanvas.draw(callback => {
				callback(
					magicNumbers.CHAR_SPACE,
					magicNumbers.COLOR_WHITE,
					magicNumbers.COLOR_BLACK,
					cursorX,
					y,
				);
			}, false);
		}
	};
 
	const keyDown = e => {
		if (!ignored) {
			if (!e.altKey && !e.ctrlKey && !e.metaKey) {
				// Tab key - insert tab character
				if (e.code === 'Tab') {
					e.preventDefault();
					draw(9); // Tab character code
				} else if (e.code === 'Backspace') {
					e.preventDefault();
					if (State.cursor.getX() > 0) {
						deleteText();
					}
				}
			} else if (e.altKey && !e.ctrlKey && !e.metaKey) {
				switch (e.code) {
					// Alt+Up Arrow - Insert Row
					case 'ArrowUp':
						e.preventDefault();
						insertRow();
						break;
					// Alt+Down Arrow - Delete Row
					case 'ArrowDown':
						e.preventDefault();
						deleteRow();
						break;
					// Alt+Right Arrow - Insert Column
					case 'ArrowRight':
						e.preventDefault();
						insertColumn();
						break;
					// Alt+Left Arrow - Delete Column
					case 'ArrowLeft':
						e.preventDefault();
						deleteColumn();
						break;
					// Alt+E - Erase Row (or Alt+Shift+E for Erase Column)
					case 'KeyE':
						e.preventDefault();
						if (e.shiftKey) {
							eraseColumn();
						} else {
							eraseRow();
						}
						break;
					// Alt+Home - Erase to Start of Row
					case 'Home':
						e.preventDefault();
						eraseToStartOfRow();
						break;
					// Alt+End - Erase to End of Row
					case 'End':
						e.preventDefault();
						eraseToEndOfRow();
						break;
					// Alt+Page Up - Erase to Start of Column
					case 'PageUp':
						e.preventDefault();
						eraseToStartOfColumn();
						break;
					// Alt+Page Down - Erase to End of Column
					case 'PageDown':
						e.preventDefault();
						eraseToEndOfColumn();
						break;
				}
			}
		}
	};
 
	const unicodeMapping = new Map([
		[0x2302, 127], // HOUSE (โŒ‚)
		[0x00c7, 128], // CAPITAL LETTER C WITH CEDILLA (ร‡)
		[0x00fc, 129], // SMALL LETTER U WITH DIAERESIS (รผ)
		[0x00e9, 130], // SMALL LETTER E WITH ACUTE (รฉ)
		[0x00e2, 131], // SMALL LETTER A WITH CIRCUMFLEX (รข)
		[0x00e4, 132], // SMALL LETTER A WITH DIAERESIS (รค)
		[0x00e0, 133], // SMALL LETTER A WITH GRAVE (ร )
		[0x00e5, 134], // SMALL LETTER A WITH RING ABOVE (รฅ)
		[0x00e7, 135], // SMALL LETTER C WITH CEDILLA (รง)
		[0x00ea, 136], // SMALL LETTER E WITH CIRCUMFLEX (รช)
		[0x00eb, 137], // SMALL LETTER E WITH DIAERESIS (รซ)
		[0x00e8, 138], // SMALL LETTER E WITH GRAVE (รจ)
		[0x00ef, 139], // SMALL LETTER I WITH DIAERESIS (รฏ)
		[0x00ee, 140], // SMALL LETTER I WITH CIRCUMFLEX (รฎ)
		[0x00ec, 141], // SMALL LETTER I WITH GRAVE (รฌ)
		[0x00c4, 142], // CAPITAL LETTER A WITH DIAERESIS (ร„)
		[0x00c5, 143], // CAPITAL LETTER A WITH RING ABOVE (ร…)
		[0x00c9, 144], // CAPITAL LETTER E WITH ACUTE (ร‰)
		[0x00e6, 145], // SMALL LETTER AE (รฆ)
		[0x00c6, 146], // CAPITAL LETTER AE (ร†)
		[0x00f4, 147], // SMALL LETTER O WITH CIRCUMFLEX (รด)
		[0x00f6, 148], // SMALL LETTER O WITH DIAERESIS (รถ)
		[0x00f2, 149], // SMALL LETTER O WITH GRAVE (รฒ)
		[0x00fb, 150], // SMALL LETTER U WITH CIRCUMFLEX (รป)
		[0x00f9, 151], // SMALL LETTER U WITH GRAVE (รน)
		[0x00ff, 152], // SMALL LETTER Y WITH DIAERESIS (รฟ)
		[0x00d6, 153], // CAPITAL LETTER O WITH DIAERESIS (ร–)
		[0x00dc, 154], // CAPITAL LETTER U WITH DIAERESIS (รœ)
		[0x00a2, 155], // CENT SIGN (ยข)
		[0x00a3, 156], // POUND SIGN (ยฃ)
		[0x00a5, 157], // YEN SIGN (ยฅ)
		[0x20a7, 158], // PESETA SIGN (โ‚ง)
		[0x0192, 159], // SMALL LETTER F WITH HOOK (ฦ’)
		[0x00e1, 160], // SMALL LETTER A WITH ACUTE (รก)
		[0x00ed, 161], // SMALL LETTER I WITH ACUTE (รญ)
		[0x00f3, 162], // SMALL LETTER O WITH ACUTE (รณ)
		[0x00fa, 163], // SMALL LETTER U WITH ACUTE (รบ)
		[0x00f1, 164], // SMALL LETTER N WITH TILDE (รฑ)
		[0x00d1, 165], // CAPITAL LETTER N WITH TILDE (ร‘)
		[0x00aa, 166], // FEMININE ORDINAL INDICATOR (ยช)
		[0x00ba, 167], // MASCULINE ORDINAL INDICATOR (ยบ)
		[0x00bf, 168], // INVERTED QUESTION MARK (ยฟ)
		[0x2310, 169], // REVERSED NOT SIGN (โŒ)
		[0x00ac, 170], // NOT SIGN (ยฌ)
		[0x00bd, 171], // VULGAR FRACTION ONE HALF (ยฝ)
		[0x00bc, 172], // VULGAR FRACTION ONE QUARTER (ยผ)
		[0x00a1, 173], // INVERTED EXCLAMATION MARK (ยก)
		[0x00ab, 174], // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK (ยซ)
		[0x00bb, 175], // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK (ยป)
		[0x2591, 176], // LIGHT SHADE (โ–‘)
		[0x2592, 177], // MEDIUM SHADE (โ–’)
		[0x2593, 178], // DARK SHADE (โ–“)
		[0x2502, 179], // BOX DRAWINGS LIGHT VERTICAL (โ”‚)
		[0x2524, 180], // BOX DRAWINGS LIGHT VERTICAL AND LEFT (โ”ค)
		[0x2561, 181], // BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE (โ•ก)
		[0x2562, 182], // BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE (โ•ข)
		[0x2556, 183], // BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE (โ•–)
		[0x2555, 184], // BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE (โ••)
		[0x2563, 185], // BOX DRAWINGS DOUBLE VERTICAL AND LEFT (โ•ฃ)
		[0x2551, 186], // BOX DRAWINGS DOUBLE VERTICAL (โ•‘)
		[0x2557, 187], // BOX DRAWINGS DOUBLE DOWN AND LEFT (โ•—)
		[0x255d, 188], // BOX DRAWINGS DOUBLE UP AND LEFT (โ•)
		[0x255c, 189], // BOX DRAWINGS UP DOUBLE AND LEFT SINGLE (โ•œ)
		[0x255b, 190], // BOX DRAWINGS UP SINGLE AND LEFT DOUBLE (โ•›)
		[0x2510, 191], // BOX DRAWINGS LIGHT DOWN AND LEFT (โ”)
		[0x2514, 192], // BOX DRAWINGS LIGHT UP AND RIGHT (โ””)
		[0x2534, 193], // BOX DRAWINGS LIGHT UP AND HORIZONTAL (โ”ด)
		[0x252c, 194], // BOX DRAWINGS LIGHT DOWN AND HORIZONTAL (โ”ฌ)
		[0x251c, 195], // BOX DRAWINGS LIGHT VERTICAL AND RIGHT (โ”œ)
		[0x2500, 196], // BOX DRAWINGS LIGHT HORIZONTAL (โ”€)
		[0x253c, 197], // BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL (โ”ผ)
		[0x255e, 198], // BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE (โ•ž)
		[0x255f, 199], // BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE (โ•Ÿ)
		[0x255a, 200], // BOX DRAWINGS DOUBLE UP AND RIGHT (โ•š)
		[0x2554, 201], // BOX DRAWINGS DOUBLE DOWN AND RIGHT (โ•”)
		[0x2569, 202], // BOX DRAWINGS DOUBLE UP AND HORIZONTAL (โ•ฉ)
		[0x2566, 203], // BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL (โ•ฆ)
		[0x2560, 204], // BOX DRAWINGS DOUBLE VERTICAL AND RIGHT (โ• )
		[0x2550, 205], // BOX DRAWINGS DOUBLE HORIZONTAL (โ•)
		[0x256c, 206], // BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL (โ•ฌ)
		[0x2567, 207], // BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE (โ•ง)
		[0x2568, 208], // BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE (โ•จ)
		[0x2564, 209], // BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE (โ•ค)
		[0x2565, 210], // BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE (โ•ฅ)
		[0x2559, 211], // BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE (โ•™)
		[0x2558, 212], // BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE (โ•˜)
		[0x2552, 213], // BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE (โ•’)
		[0x2553, 214], // BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE (โ•“)
		[0x256b, 215], // BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE (โ•ซ)
		[0x256a, 216], // BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE (โ•ช)
		[0x2518, 217], // BOX DRAWINGS LIGHT UP AND LEFT (โ”˜)
		[0x250c, 218], // BOX DRAWINGS LIGHT DOWN AND RIGHT (โ”Œ)
		[0x2588, 219], // FULL BLOCK (โ–ˆ)
		[0x2584, 220], // LOWER HALF BLOCK (โ–„)
		[0x258c, 221], // LEFT HALF BLOCK (โ–Œ)
		[0x2590, 222], // RIGHT HALF BLOCK (โ–)
		[0x2580, 223], // UPPER HALF BLOCK (โ–€)
		[0x03b1, 224], // GREEK SMALL LETTER ALPHA (ฮฑ)
		[0x00df, 225], // SMALL LETTER SHARP S (รŸ)
		[0x0393, 226], // GREEK CAPITAL LETTER GAMMA (ฮ“)
		[0x03c0, 227], // GREEK SMALL LETTER PI (ฯ€)
		[0x03a3, 228], // GREEK CAPITAL LETTER SIGMA (ฮฃ)
		[0x03c3, 229], // GREEK SMALL LETTER SIGMA (ฯƒ)
		[0x00b5, 230], // MICRO SIGN (ยต)
		[0x03c4, 231], // GREEK SMALL LETTER TAU (ฯ„)
		[0x03a6, 232], // GREEK CAPITAL LETTER PHI (ฮฆ)
		[0x0398, 233], // GREEK CAPITAL LETTER THETA (ฮ˜)
		[0x03a9, 234], // GREEK CAPITAL LETTER OMEGA (ฮฉ)
		[0x03b4, 235], // GREEK SMALL LETTER DELTA (ฮด)
		[0x221e, 236], // INFINITY (โˆž)
		[0x03c6, 237], // GREEK SMALL LETTER PHI (ฯ†)
		[0x03b5, 238], // GREEK SMALL LETTER EPSILON (ฮต)
		[0x2229, 239], // INTERSECTION (โˆฉ)
		[0x2261, 240], // IDENTICAL TO (โ‰ก)
		[0x00b1, 241], // PLUS-MINUS SIGN (ยฑ)
		[0x2265, 242], // GREATER-THAN OR EQUAL TO (โ‰ฅ)
		[0x2264, 243], // LESS-THAN OR EQUAL TO (โ‰ค)
		[0x2320, 244], // TOP HALF INTEGRAL (โŒ )
		[0x2321, 245], // BOTTOM HALF INTEGRAL (โŒก)
		[0x00f7, 246], // DIVISION SIGN (รท)
		[0x2248, 247], // ALMOST EQUAL TO (โ‰ˆ)
		[0x00b0, 248], // DEGREE SIGN (ยฐ)
		[0x2219, 249], // BULLET OPERATOR (โˆ™)
		[0x00b7, 250], // MIDDLE DOT (ยท)
		[0x221a, 251], // SQUARE ROOT (โˆš)
		[0x207f, 252], // SUPERSCRIPT SMALL LETTER N (โฟ)
		[0x00b2, 253], // SUPERSCRIPT TWO (ยฒ)
		[0x25a0, 254], // BLACK SQUARE (โ– )
		[0x00a0, 255], // NO-BREAK SPACE ( )
	]);
 
	/**
	 * Converts a Unicode code point to the corresponding code in the custom code page.
	 * If the code point exists in the unicodeMapping Map, returns the mapped value.
	 * Otherwise, returns the original code point.
	 *
	 * @param {number} keyCode - The Unicode code point to convert.
	 * @returns {number} The mapped code page value or the original code point.
	 */
	const convertUnicode = keyCode => unicodeMapping.get(keyCode) ?? keyCode;
 
	const keyPress = e => {
		if (!ignored) {
			if (!e.altKey && !e.ctrlKey && !e.metaKey) {
				// Check for printable characters
				if (e.key.length === 1) {
					// Single character keys (printable characters)
					e.preventDefault();
					draw(convertUnicode(e.key.charCodeAt(0)));
				} else if (e.key === 'Enter') {
					// Enter key - cursor to new line
					e.preventDefault();
					State.cursor.newLine();
				} else if (e.key === 'Backspace') {
					// Backspace key - delete text
					e.preventDefault();
					if (State.cursor.getX() > 0) {
						deleteText();
					}
				}
 
				// Special case for section sign
				if (e.key === 'ยง') {
					e.preventDefault();
					draw(21);
				}
			} else if (e.ctrlKey) {
				// Handle Ctrl key combinations
				if (e.key === 'u' || e.key === 'U') {
					// Ctrl+U - Pick up colors from current position
					e.preventDefault();
					const block = State.textArtCanvas.getBlock(
						State.cursor.getX(),
						State.cursor.getY(),
					);
					State.palette.setForegroundColor(block.foregroundColor);
					State.palette.setBackgroundColor(block.backgroundColor);
				}
			}
		}
	};
 
	let selectionStartX = 0;
	let selectionStartY = 0;
	const textCanvasDown = e => {
		State.cursor.move(e.detail.x, e.detail.y);
		// Store start position but don't create selection yet
		selectionStartX = e.detail.x;
		selectionStartY = e.detail.y;
	};
 
	const textCanvasDrag = e => {
		// Only switch to selection if we've dragged to a different cell
		if (e.detail.x !== selectionStartX || e.detail.y !== selectionStartY) {
			State.cursor.hide();
			Toolbar.switchTool('selection');
			State.selectionCursor.setStart(selectionStartX, selectionStartY);
			State.selectionCursor.setEnd(e.detail.x, e.detail.y);
		}
	};
 
	const enable = () => {
		document.addEventListener('keydown', keyDown);
		document.addEventListener('keypress', keyPress);
		document.addEventListener('onTextCanvasDown', textCanvasDown);
		document.addEventListener('onTextCanvasDrag', textCanvasDrag);
		State.cursor.enable();
		fkeys.enable();
		State.positionInfo.update(State.cursor.getX(), State.cursor.getY());
		// Check if there's an active selection and inherit its position
		const selection = State.selectionCursor.getPos();
		Iif (selection) {
			State.cursor.move(selection.x, selection.y);
		}
		enabled = true;
	};
 
	const disable = () => {
		document.removeEventListener('keydown', keyDown);
		document.removeEventListener('keypress', keyPress);
		document.removeEventListener('onTextCanvasDown', textCanvasDown);
		document.removeEventListener('onTextCanvasDrag', textCanvasDrag);
		const selection = State.selectionCursor.getPos();
		Iif (selection) {
			State.cursor.move(selection.x, selection.y);
		}
		State.selectionCursor.hide();
		State.cursor.disable();
		fkeys.disable();
		enabled = false;
	};
 
	const ignore = () => {
		ignored = true;
		if (enabled) {
			State.cursor.disable();
			fkeys.disable();
		}
	};
 
	const unignore = () => {
		ignored = false;
		if (enabled) {
			State.cursor.enable();
			fkeys.enable();
		}
	};
 
	return {
		enable: enable,
		disable: disable,
		ignore: ignore,
		unignore: unignore,
		insertRow: insertRow,
		deleteRow: deleteRow,
		insertColumn: insertColumn,
		deleteColumn: deleteColumn,
		eraseRow: eraseRow,
		eraseToStartOfRow: eraseToStartOfRow,
		eraseToEndOfRow: eraseToEndOfRow,
		eraseColumn: eraseColumn,
		eraseToStartOfColumn: eraseToStartOfColumn,
		eraseToEndOfColumn: eraseToEndOfColumn,
	};
};
 
const createPasteTool = (cutItem, copyItem, pasteItem, deleteItem) => {
	let buffer;
	let x = 0;
	let y = 0;
	let width = 0;
	let height = 0;
	let enabled = false;
 
	const setSelection = (newX, newY, newWidth, newHeight) => {
		x = newX;
		y = newY;
		width = newWidth;
		height = newHeight;
		Iif (buffer !== undefined) {
			pasteItem.classList.remove('disabled');
		}
		cutItem.classList.remove('disabled');
		copyItem.classList.remove('disabled');
		deleteItem.classList.remove('disabled');
		enabled = true;
	};
 
	const disable = () => {
		pasteItem.classList.add('disabled');
		cutItem.classList.add('disabled');
		copyItem.classList.add('disabled');
		deleteItem.classList.add('disabled');
		enabled = false;
	};
 
	const copy = () => {
		buffer = State.textArtCanvas.getArea(x, y, width, height);
		pasteItem.classList.remove('disabled');
	};
 
	const deleteSelection = () => {
		Iif (State.selectionCursor.isVisible() || State.cursor.isVisible()) {
			State.textArtCanvas.startUndo();
			State.textArtCanvas.deleteArea(
				x,
				y,
				width,
				height,
				State.palette.getBackgroundColor(),
			);
		}
	};
 
	const cut = () => {
		if (State.selectionCursor.isVisible() || State.cursor.isVisible()) {
			copy();
			deleteSelection();
		}
	};
 
	const paste = () => {
		if (
			buffer !== undefined &&
			(State.selectionCursor.isVisible() || State.cursor.isVisible())
		) {
			State.textArtCanvas.startUndo();
			State.textArtCanvas.setArea(buffer, x, y);
		}
	};
 
	const systemPaste = () => {
		if (!navigator.clipboard || !navigator.clipboard.readText) {
			console.warn('[Keyboard] Clipboard API not available');
			return;
		}
		navigator.clipboard
			.readText()
			.then(text => {
				if (
					text &&
					(State.selectionCursor.isVisible() || State.cursor.isVisible())
				) {
					const columns = State.textArtCanvas.getColumns();
					const rows = State.textArtCanvas.getRows();
					// Check for oversized content
					const lines = text.split(/\r\n|\r|\n/);
					// Check single line width
					if (
						lines.length === 1 &&
						lines[0].length > columns * magicNumbers.MAX_COPY_LINES
					) {
						alert(
							`Paste buffer too large. Single line content exceeds ${columns * magicNumbers.MAX_COPY_LINES} characters. Please copy smaller blocks.`,
						);
						return;
					}
					// Check multi-line height
					if (lines.length > rows * magicNumbers.MAX_COPY_LINES) {
						alert(
							`Paste buffer too large. Content exceeds ${rows * magicNumbers.MAX_COPY_LINES} lines. Please copy smaller blocks.`,
						);
						return;
					}
					State.textArtCanvas.startUndo();
					let currentX = x;
					let currentY = y;
					const startX = x; // Remember starting column for line breaks
					const foreground = State.palette.getForegroundColor();
					const background = State.palette.getBackgroundColor();
 
					State.textArtCanvas.draw(draw => {
						for (let i = 0; i < text.length; i++) {
							const char = text.charAt(i);
							// Handle newline characters
							if (char === '\n' || char === '\r') {
								currentY++;
								currentX = startX;
								// Skip \r\n combination
								if (
									char === '\r' &&
									i + 1 < text.length &&
									text.charAt(i + 1) === '\n'
								) {
									i++;
								}
								continue;
							}
							// Check bounds - stop if we're beyond canvas vertically
							if (currentY >= rows) {
								break;
							}
							// Handle edge truncation - skip characters that exceed the right edge
							if (currentX >= columns) {
								// Skip this character and continue until we hit a newline
								continue;
							}
							// Handle non-printable characters
							let charCode = char.charCodeAt(0);
							// Convert tabs and other whitespace/non-printable characters to space
							if (char === '\t' || charCode < 32 || charCode === 127) {
								charCode = magicNumbers.CHAR_SPACE;
							}
							// Draw the character
							draw(charCode, foreground, background, currentX, currentY);
 
							currentX++;
						}
					}, false);
				}
			})
			.catch(err => {
				console.error('[Keyboard] Failed to read clipboard:', err);
			});
	};
 
	const keyDown = e => {
		if (enabled) {
			if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey) {
				switch (e.code) {
					case 'KeyX': // Ctrl/Cmd+X - Cut
						e.preventDefault();
						cut();
						break;
					case 'KeyC': // Ctrl/Cmd+C - Copy
						e.preventDefault();
						copy();
						break;
					case 'KeyV': // Ctrl/Cmd+V - Paste
						e.preventDefault();
						paste();
						break;
					default:
						break;
				}
			}
			// System paste with Ctrl+Shift+V
			if (
				(e.ctrlKey || e.metaKey) &&
				e.shiftKey &&
				!e.altKey &&
				e.code === 'KeyV'
			) {
				e.preventDefault();
				systemPaste();
			}
		}
		if ((e.ctrlKey || e.metaKey) && e.code === 'Backspace') {
			// Ctrl/Cmd+Backspace - Delete selection
			e.preventDefault();
			deleteSelection();
		}
	};
	document.addEventListener('keydown', keyDown);
 
	return {
		setSelection: setSelection,
		cut: cut,
		copy: copy,
		paste: paste,
		systemPaste: systemPaste,
		deleteSelection: deleteSelection,
		disable: disable,
	};
};
 
const createSelectionTool = () => {
	const viewport = $('viewport');
	const panel = $('selectionToolbar');
	const flipHButton = $('flipHorizontal');
	const flipVButton = $('flipVertical');
	const moveButton = $('moveBlocks');
	let moveMode = false;
	let selectionData = null;
	let isDragging = false;
	let dragStartX = 0;
	let dragStartY = 0;
	let originalPosition = null; // Original position when move mode started
	let underlyingData = null; // Content currently underneath the moving blocks
	// Selection expansion state
	let selectionStartX = 0;
	let selectionStartY = 0;
	let selectionEndX = 0;
	let selectionEndY = 0;
	// Pending initial action when switching from keyboard mode
	let pendingInitialAction = null;
 
	const canvasDown = e => {
		if (moveMode) {
			const selection = State.selectionCursor.getSelection();
			if (
				selection &&
				e.detail.x >= selection.x &&
				e.detail.x < selection.x + selection.width &&
				e.detail.y >= selection.y &&
				e.detail.y < selection.y + selection.height
			) {
				isDragging = true;
				dragStartX = e.detail.x;
				dragStartY = e.detail.y;
			}
		} else {
			State.selectionCursor.setStart(e.detail.x, e.detail.y);
			State.selectionCursor.setEnd(e.detail.x, e.detail.y);
		}
	};
 
	const canvasDrag = e => {
		if (moveMode && isDragging) {
			const deltaX = e.detail.x - dragStartX;
			const deltaY = e.detail.y - dragStartY;
			moveSelection(deltaX, deltaY);
			dragStartX = e.detail.x;
			dragStartY = e.detail.y;
		} else if (!moveMode) {
			State.selectionCursor.setEnd(e.detail.x, e.detail.y);
		}
	};
 
	const canvasUp = _ => {
		if (moveMode && isDragging) {
			isDragging = false;
		} else {
			// Sync selection expansion state after mouse selection
			const selection = State.selectionCursor.getSelection();
			if (selection) {
				selectionStartX = selection.x;
				selectionStartY = selection.y;
				selectionEndX = selection.x + selection.width - 1;
				selectionEndY = selection.y + selection.height - 1;
			}
		}
	};
 
	const flipHorizontal = () => {
		const selection = State.selectionCursor.getSelection();
		Iif (!selection) {
			return;
		}
		State.textArtCanvas.startUndo();
		// Get all blocks in the selection
		for (let y = 0; y < selection.height; y++) {
			const blocks = [];
			for (let x = 0; x < selection.width; x++) {
				blocks.push(
					State.textArtCanvas.getBlock(selection.x + x, selection.y + y),
				);
			}
			// Flip the row horizontally
			State.textArtCanvas.draw(callback => {
				for (let x = 0; x < selection.width; x++) {
					const sourceBlock = blocks[x];
					const targetX = selection.x + (selection.width - 1 - x);
					let charCode = sourceBlock.charCode;
					// Transform left/right half blocks
					switch (charCode) {
						case 221: // LEFT_HALF_BLOCK
							charCode = 222; // RIGHT_HALF_BLOCK
							break;
						case 222: // RIGHT_HALF_BLOCK
							charCode = 221; // LEFT_HALF_BLOCK
							break;
						default:
							break;
					}
					callback(
						charCode,
						sourceBlock.foregroundColor,
						sourceBlock.backgroundColor,
						targetX,
						selection.y + y,
					);
				}
			}, false);
		}
	};
 
	const flipVertical = () => {
		const selection = State.selectionCursor.getSelection();
		Iif (!selection) {
			return;
		}
		State.textArtCanvas.startUndo();
		// Get all blocks in the selection
		for (let x = 0; x < selection.width; x++) {
			const blocks = [];
			for (let y = 0; y < selection.height; y++) {
				blocks.push(
					State.textArtCanvas.getBlock(selection.x + x, selection.y + y),
				);
			}
			// Flip the column vertically
			State.textArtCanvas.draw(callback => {
				for (let y = 0; y < selection.height; y++) {
					const sourceBlock = blocks[y];
					const targetY = selection.y + (selection.height - 1 - y);
					let charCode = sourceBlock.charCode;
					// Transform upper/lower half blocks
					switch (charCode) {
						case 223: // UPPER_HALF_BLOCK
							charCode = 220; // LOWER_HALF_BLOCK
							break;
						case 220: // LOWER_HALF_BLOCK
							charCode = 223; // UPPER_HALF_BLOCK
							break;
						default:
							break;
					}
					callback(
						charCode,
						sourceBlock.foregroundColor,
						sourceBlock.backgroundColor,
						selection.x + x,
						targetY,
					);
				}
			}, false);
		}
	};
 
	const setAreaSelective = (area, targetArea, x, y) => {
		const columns = State.textArtCanvas.getColumns();
		const rows = State.textArtCanvas.getRows();
		const maxWidth = Math.min(area.width, columns - x);
		const maxHeight = Math.min(area.height, rows - y);
 
		State.textArtCanvas.draw(draw => {
			for (let py = 0; py < maxHeight; py++) {
				for (let px = 0; px < maxWidth; px++) {
					const srcIndex = py * area.width + px;
					const sourceAttrib = area.data[srcIndex] || 0;
 
					if (sourceAttrib !== 0) {
						const charCode = sourceAttrib >> 8;
						const fg = sourceAttrib & 15;
						const bg = (sourceAttrib >> 4) & 15;
						draw(charCode, fg, bg, x + px, y + py);
					} else if (
						targetArea &&
						px < targetArea.width &&
						py < targetArea.height
					) {
						const tgtIndex = py * targetArea.width + px;
						const targetAttrib = targetArea.data[tgtIndex] || 0;
						const charCode = targetAttrib >> 8;
						const fg = targetAttrib & 15;
						const bg = (targetAttrib >> 4) & 15;
						draw(charCode, fg, bg, x + px, y + py);
					}
					// else: leave existing canvas pixel alone
				}
			}
		}, false); // batch the whole operation for consistent commit/undo
	};
 
	const moveSelection = (deltaX, deltaY) => {
		const selection = State.selectionCursor.getSelection();
		if (!selection) {
			return;
		}
		const newX = Math.max(
			0,
			Math.min(
				selection.x + deltaX,
				State.textArtCanvas.getColumns() - selection.width,
			),
		);
		const newY = Math.max(
			0,
			Math.min(
				selection.y + deltaY,
				State.textArtCanvas.getRows() - selection.height,
			),
		);
		// Don't process if we haven't actually moved
		if (newX === selection.x && newY === selection.y) {
			return;
		}
		State.textArtCanvas.startUndo();
		// Only update the current selection data if we don't have it
		if (!selectionData) {
			selectionData = State.textArtCanvas.getArea(
				selection.x,
				selection.y,
				selection.width,
				selection.height,
			);
		}
		// Restore what was underneath the current position (if any)
		if (underlyingData) {
			State.textArtCanvas.setArea(underlyingData, selection.x, selection.y);
		}
		// Store what's underneath the new position
		underlyingData = State.textArtCanvas.getArea(
			newX,
			newY,
			selection.width,
			selection.height,
		);
		// Apply the selection at the new position, but only non-blank characters
		setAreaSelective(selectionData, underlyingData, newX, newY);
		// Update the selection cursor to the new position
		State.selectionCursor.setStart(newX, newY);
		State.selectionCursor.setEnd(
			newX + selection.width - 1,
			newY + selection.height - 1,
		);
	};
 
	const createEmptyArea = (width, height) => {
		// Create an area filled with empty/blank characters (char code 0, colors 0)
		const data = new Uint16Array(width * height);
		for (let i = 0; i < data.length; i++) {
			data[i] = 0; // char code 0, foreground 0, background 0
		}
		return {
			data: data,
			width: width,
			height: height,
		};
	};
 
	const toggleMoveMode = () => {
		moveMode = !moveMode;
		if (moveMode) {
			// Enable move mode
			moveButton.classList.add('enabled');
			State.selectionCursor.getElement().classList.add('moveMode');
			// Store selection data and original position when entering move mode
			const selection = State.selectionCursor.getSelection();
			if (selection) {
				selectionData = State.textArtCanvas.getArea(
					selection.x,
					selection.y,
					selection.width,
					selection.height,
				);
				originalPosition = {
					x: selection.x,
					y: selection.y,
					width: selection.width,
					height: selection.height,
				};
				// For a move operation, the old position should be cleared (empty)
				// We'll restore empty space as we move away
				underlyingData = createEmptyArea(selection.width, selection.height);
			}
		} else {
			// Disable move mode - finalize the move by clearing original position if different
			const currentSelection = State.selectionCursor.getSelection();
			if (
				originalPosition &&
				currentSelection &&
				(currentSelection.x !== originalPosition.x ||
				  currentSelection.y !== originalPosition.y)
			) {
				// Check if the original and current positions overlap
				const xOverlap =
					originalPosition.x < currentSelection.x + currentSelection.width &&
					originalPosition.x + originalPosition.width > currentSelection.x;
				const yOverlap =
					originalPosition.y < currentSelection.y + currentSelection.height &&
					originalPosition.y + originalPosition.height > currentSelection.y;
				const hasOverlap = xOverlap && yOverlap;
 
				State.textArtCanvas.startUndo();
				if (hasOverlap) {
					// If there's overlap, selectively clear only the non-overlapping parts
					const emptyData = createEmptyArea(
						originalPosition.width,
						originalPosition.height,
					);
					// Get what's currently at the original position (which includes part of the moved selection)
					const currentAtOriginal = State.textArtCanvas.getArea(
						originalPosition.x,
						originalPosition.y,
						originalPosition.width,
						originalPosition.height,
					);
					// Apply empty data, but preserve anything from the current selection
					setAreaSelective(
						emptyData,
						currentAtOriginal,
						originalPosition.x,
						originalPosition.y,
					);
				} else {
					// No overlap
					State.textArtCanvas.deleteArea(
						originalPosition.x,
						originalPosition.y,
						originalPosition.width,
						originalPosition.height,
						State.palette.getBackgroundColor(),
					);
				}
			}
			moveButton.classList.remove('enabled');
			State.selectionCursor.getElement().classList.remove('moveMode');
			selectionData = null;
			originalPosition = null;
			underlyingData = null;
		}
	};
	const isMoveMode = () => moveMode;
 
	// Selection expansion methods - delegated from cursor
	const startSelectionExpansion = () => {
		Eif (!State.selectionCursor.isVisible()) {
			// Start selection from current cursor position
			selectionStartX = State.cursor.getX();
			selectionStartY = State.cursor.getY();
			selectionEndX = selectionStartX;
			selectionEndY = selectionStartY;
			State.selectionCursor.setStart(selectionStartX, selectionStartY);
			State.selectionCursor.setEnd(selectionEndX, selectionEndY);
			State.cursor.hide();
		}
		// If selection already exists, keep using the current anchor (selectionStartX/Y)
		// and end (selectionEndX/Y) coordinates. Don't reinitialize from bounds.
	};
 
	const moveSelectionLeft = () => {
		const selection = State.selectionCursor.getSelection();
		if (!selection) {
			return;
		}
		const newX = Math.max(0, selection.x - 1);
		const newY = selection.y;
		selectionStartX = newX;
		selectionStartY = newY;
		selectionEndX = newX + selection.width - 1;
		selectionEndY = newY + selection.height - 1;
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const moveSelectionRight = () => {
		const selection = State.selectionCursor.getSelection();
		if (!selection) {
			return;
		}
		const newX = Math.min(
			State.textArtCanvas.getColumns() - selection.width,
			selection.x + 1,
		);
		const newY = selection.y;
		selectionStartX = newX;
		selectionStartY = newY;
		selectionEndX = newX + selection.width - 1;
		selectionEndY = newY + selection.height - 1;
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const moveSelectionUp = () => {
		const selection = State.selectionCursor.getSelection();
		if (!selection) {
			return;
		}
		const newX = selection.x;
		const newY = Math.max(0, selection.y - 1);
		selectionStartX = newX;
		selectionStartY = newY;
		selectionEndX = newX + selection.width - 1;
		selectionEndY = newY + selection.height - 1;
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const moveSelectionDown = () => {
		const selection = State.selectionCursor.getSelection();
		if (!selection) {
			return;
		}
		const newX = selection.x;
		const newY = Math.min(
			State.textArtCanvas.getRows() - selection.height,
			selection.y + 1,
		);
		selectionStartX = newX;
		selectionStartY = newY;
		selectionEndX = newX + selection.width - 1;
		selectionEndY = newY + selection.height - 1;
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const shiftLeft = () => {
		startSelectionExpansion();
		selectionEndX = Math.max(selectionEndX - 1, 0);
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const shiftRight = () => {
		startSelectionExpansion();
		selectionEndX = Math.min(
			selectionEndX + 1,
			State.textArtCanvas.getColumns() - 1,
		);
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const shiftUp = () => {
		startSelectionExpansion();
		selectionEndY = Math.max(selectionEndY - 1, 0);
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const shiftDown = () => {
		startSelectionExpansion();
		selectionEndY = Math.min(
			selectionEndY + 1,
			State.textArtCanvas.getRows() - 1,
		);
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const shiftToStartOfRow = () => {
		startSelectionExpansion();
		selectionEndX = 0;
		// Ensure coordinates are ordered (start <= end)
		if (selectionStartX > selectionEndX) {
			[selectionStartX, selectionEndX] = [selectionEndX, selectionStartX];
		}
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const shiftToEndOfRow = () => {
		startSelectionExpansion();
		selectionEndX = State.textArtCanvas.getColumns() - 1;
		// Ensure coordinates are ordered (start <= end)
		if (selectionStartX > selectionEndX) {
			[selectionStartX, selectionEndX] = [selectionEndX, selectionStartX];
		}
		State.selectionCursor.setStart(selectionStartX, selectionStartY);
		State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		scrollViewportToSelection();
	};
 
	const scrollViewportToSelection = () => {
		if (!viewport) {
			return;
		}
 
		const selection = State.selectionCursor.getSelection();
		if (!selection) {
			return;
		}
 
		const fontHeight = State.font.getHeight();
		const fontWidth = State.font.getWidth();
		const bufferRows = 5; // Same buffer as cursor
 
		// Use the end position of the selection for focus
		const selectionPixelY = selection.y * fontHeight;
		const selectionPixelX = selection.x * fontWidth;
		const bufferPixels = bufferRows * fontHeight;
 
		const viewportHeight = viewport.clientHeight;
		const viewportWidth = viewport.clientWidth;
		const scrollTop = viewport.scrollTop;
		const scrollLeft = viewport.scrollLeft;
 
		// Check vertical scrolling
		const selectionTop = selectionPixelY - bufferPixels;
		const selectionBottom =
			selectionPixelY + selection.height * fontHeight + bufferPixels;
 
		if (selectionTop < scrollTop) {
			viewport.scrollTop = Math.max(0, selectionTop);
		} else if (selectionBottom > scrollTop + viewportHeight) {
			viewport.scrollTop = Math.max(0, selectionBottom - viewportHeight);
		}
 
		// Check horizontal scrolling
		const selectionLeft = selectionPixelX - bufferRows * fontWidth;
		const selectionRight =
			selectionPixelX + selection.width * fontWidth + bufferRows * fontWidth;
 
		if (selectionLeft < scrollLeft) {
			viewport.scrollLeft = Math.max(0, selectionLeft);
		} else if (selectionRight > scrollLeft + viewportWidth) {
			viewport.scrollLeft = Math.max(0, selectionRight - viewportWidth);
		}
	};
 
	const pageScroll = (direction = 'down') => {
		if (!viewport) {
			return;
		}
 
		const rowsPerScreen = calculateRowsPerScreen(
			viewport,
			State.font.getHeight(),
		);
		const maxY = State.textArtCanvas.getRows() - 1;
		const delta = direction === 'up' ? -rowsPerScreen : rowsPerScreen;
 
		if (moveMode && State.selectionCursor.getSelection()) {
			moveSelection(0, delta);
		} else {
			startSelectionExpansion();
			const selection = State.selectionCursor.getSelection();
			const selectionHeight = selection ? selection.height : 1;
 
			// Calculate new position
			let newStartY = selectionStartY + delta;
			let newEndY = selectionEndY + delta;
 
			// Clamp to canvas bounds while preserving selection height
			if (newEndY > maxY) {
				newEndY = maxY;
				newStartY = Math.max(0, maxY - selectionHeight + 1);
			} else if (newStartY < 0) {
				newStartY = 0;
				newEndY = Math.min(maxY, selectionHeight - 1);
			}
 
			selectionStartY = newStartY;
			selectionEndY = newEndY;
			State.selectionCursor.setStart(selectionStartX, selectionStartY);
			State.selectionCursor.setEnd(selectionEndX, selectionEndY);
		}
		scrollViewportToSelection();
	};
 
	const keyDown = e => {
		// These keys work with or without modifiers
		if (e.code === 'Enter') {
			// Enter - exit selection and use default cursor behavior
			e.preventDefault();
			Toolbar.switchTool('keyboard');
			State.cursor.newLine();
		} else if (e.code === 'End') {
			// End key - expand selection to end of current row
			e.preventDefault();
			shiftToEndOfRow();
		} else if (e.code === 'Home') {
			// Home key - expand selection to start of current row
			e.preventDefault();
			shiftToStartOfRow();
		}
		if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {
			if (e.key === '[') {
				// '[' key - flip horizontal
				e.preventDefault();
				flipHorizontal();
			} else if (e.key === ']') {
				// ']' key - flip vertical
				e.preventDefault();
				flipVertical();
			} else if (e.key === 'M' || e.key === 'm') {
				// 'M' key - toggle move mode
				e.preventDefault();
				toggleMoveMode();
			} else if (e.code === 'PageUp') {
				e.preventDefault();
				pageScroll('up');
			} else if (e.code === 'PageDown') {
				e.preventDefault();
				pageScroll('down');
			} else if (moveMode && State.selectionCursor.getSelection()) {
				// Arrow key shift selection contents in move mode
				if (e.code === 'ArrowLeft') {
					e.preventDefault();
					moveSelection(-1, 0);
				} else if (e.code === 'ArrowUp') {
					e.preventDefault();
					moveSelection(0, -1);
				} else if (e.code === 'ArrowRight') {
					e.preventDefault();
					moveSelection(1, 0);
				} else if (e.code === 'ArrowDown') {
					e.preventDefault();
					moveSelection(0, 1);
				}
			} else {
				switch (e.code) {
					// arrow keys move selection area
					case 'ArrowLeft':
						e.preventDefault();
						moveSelectionLeft();
						break;
					case 'ArrowUp':
						e.preventDefault();
						moveSelectionUp();
						break;
					case 'ArrowRight':
						e.preventDefault();
						moveSelectionRight();
						break;
					case 'ArrowDown':
						e.preventDefault();
						moveSelectionDown();
						break;
					default:
						break;
				}
			}
		} else if (e.shiftKey && !e.metaKey) {
			// Arrows + Shift key combinations expand selection
			switch (e.code) {
				case 'ArrowLeft':
					e.preventDefault();
					shiftLeft();
					break;
				case 'ArrowUp':
					e.preventDefault();
					shiftUp();
					break;
				case 'ArrowRight':
					e.preventDefault();
					shiftRight();
					break;
				case 'ArrowDown':
					e.preventDefault();
					shiftDown();
					break;
				default:
					break;
			}
		}
	};
 
	const enable = () => {
		State.selectionCursor.show();
		panel.style.display = 'flex';
		document.addEventListener('onTextCanvasDown', canvasDown);
		document.addEventListener('onTextCanvasDrag', canvasDrag);
		document.addEventListener('onTextCanvasUp', canvasUp);
		document.addEventListener('keydown', keyDown);
		flipHButton.addEventListener('click', flipHorizontal);
		flipVButton.addEventListener('click', flipVertical);
		moveButton.addEventListener('click', toggleMoveMode);
 
		// If there's already a selection visible (switched from keyboard mode),
		// initialize our selection expansion state
		Iif (State.selectionCursor.isVisible()) {
			const selection = State.selectionCursor.getSelection();
			if (selection) {
				selectionStartX = selection.x;
				selectionStartY = selection.y;
				selectionEndX = selection.x + selection.width - 1;
				selectionEndY = selection.y + selection.height - 1;
			}
		} else {
			startSelectionExpansion();
		}
 
		// Execute pending initial action if one was set from keyboard mode
		Iif (pendingInitialAction) {
			const action = pendingInitialAction;
			pendingInitialAction = null; // Clear it immediately
			switch (action) {
				case 'ArrowLeft':
					shiftLeft();
					break;
				case 'ArrowRight':
					shiftRight();
					break;
				case 'ArrowUp':
					shiftUp();
					break;
				case 'ArrowDown':
					shiftDown();
					break;
			}
		}
	};
 
	const disable = () => {
		State.selectionCursor.hide();
		panel.style.display = 'none';
		document.removeEventListener('onTextCanvasDown', canvasDown);
		document.removeEventListener('onTextCanvasDrag', canvasDrag);
		document.removeEventListener('onTextCanvasUp', canvasUp);
		document.removeEventListener('keydown', keyDown);
 
		// Reset move mode if it was active and finalize any pending move
		Iif (moveMode) {
			// Finalize the move by clearing original position if different
			const currentSelection = State.selectionCursor.getSelection();
			if (
				originalPosition &&
				currentSelection &&
				(currentSelection.x !== originalPosition.x ||
				  currentSelection.y !== originalPosition.y)
			) {
				// Check if the original and current positions overlap
				const xOverlap =
					originalPosition.x < currentSelection.x + currentSelection.width &&
					originalPosition.x + originalPosition.width > currentSelection.x;
				const yOverlap =
					originalPosition.y < currentSelection.y + currentSelection.height &&
					originalPosition.y + originalPosition.height > currentSelection.y;
				const hasOverlap = xOverlap && yOverlap;
 
				State.textArtCanvas.startUndo();
				if (hasOverlap) {
					// If there's overlap, we need to selectively clear only the non-overlapping parts
					// For now, use setAreaSelective with empty data to preserve the moved selection
					const emptyData = createEmptyArea(
						originalPosition.width,
						originalPosition.height,
					);
					// Get what's currently at the original position (which includes part of the moved selection)
					const currentAtOriginal = State.textArtCanvas.getArea(
						originalPosition.x,
						originalPosition.y,
						originalPosition.width,
						originalPosition.height,
					);
					// Apply empty data, but preserve anything from the current selection
					setAreaSelective(
						emptyData,
						currentAtOriginal,
						originalPosition.x,
						originalPosition.y,
					);
				} else {
					// No overlap - safe to delete the entire original area
					State.textArtCanvas.deleteArea(
						originalPosition.x,
						originalPosition.y,
						originalPosition.width,
						originalPosition.height,
						State.palette.getBackgroundColor(),
					);
				}
			}
			moveMode = false;
			moveButton.classList.remove('enabled');
			State.selectionCursor.getElement().classList.remove('moveMode');
			selectionData = null;
			originalPosition = null;
			underlyingData = null;
		}
		flipHButton.removeEventListener('click', flipHorizontal);
		flipVButton.removeEventListener('click', flipVertical);
		moveButton.removeEventListener('click', toggleMoveMode);
		State.pasteTool.disable();
	};
 
	// Method to set pending initial action when switching from keyboard mode
	const setPendingAction = keyCode => {
		pendingInitialAction = keyCode;
	};
 
	return {
		enable: enable,
		disable: disable,
		scrollViewportToSelection: scrollViewportToSelection,
		flipHorizontal: flipHorizontal,
		flipVertical: flipVertical,
		setPendingAction: setPendingAction,
		toggleMoveMode: toggleMoveMode,
		isMoveMode: isMoveMode,
	};
};
export {
	createFKeys,
	createCursor,
	createSelectionCursor,
	createKeyboardController,
	createPasteTool,
	createSelectionTool,
};