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
|
/***********************************************************************
* fterm.cpp - Base class for terminal control *
* *
* This file is part of the FINAL CUT widget toolkit *
* *
* Copyright 2012-2023 Markus Gans *
* *
* FINAL CUT is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation; either version 3 of *
* the License, or (at your option) any later version. *
* *
* FINAL CUT is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this program. If not, see *
* <http://www.gnu.org/licenses/>. *
***********************************************************************/
#if defined(__CYGWIN__)
#include "final/fconfig.h" // includes _GNU_SOURCE for strsignal()
#endif
#include <algorithm>
#include <array>
#include <string>
#include <unordered_map>
#include <vector>
#include "final/fapplication.h"
#include "final/fc.h"
#include "final/fstartoptions.h"
#include "final/input/fkeyboard.h"
#include "final/input/fkey_map.h"
#include "final/input/fmouse.h"
#include "final/output/tty/fcharmap.h"
#include "final/output/tty/foptiattr.h"
#include "final/output/tty/foptimove.h"
#include "final/output/tty/ftermcap.h"
#include "final/output/tty/ftermcapquirks.h"
#include "final/output/tty/ftermdebugdata.h"
#include "final/output/tty/ftermdetection.h"
#include "final/output/tty/fterm.h"
#include "final/output/tty/ftermios.h"
#include "final/output/tty/ftermxterminal.h"
#include "final/util/flog.h"
#include "final/util/fstring.h"
#include "final/util/fsystemimpl.h"
#include "final/vterm/fvtermbuffer.h"
#if defined(UNIT_TEST)
#include "final/output/tty/ftermlinux.h"
#include "final/output/tty/ftermfreebsd.h"
#include "final/output/tty/ftermopenbsd.h"
#elif defined(__linux__)
#include "final/output/tty/ftermlinux.h"
#elif defined(__FreeBSD__) || defined(__DragonFly__)
#include "final/output/tty/ftermfreebsd.h"
#elif defined(__NetBSD__) || defined(__OpenBSD__)
#include "final/output/tty/ftermopenbsd.h"
#endif
namespace finalcut
{
namespace internal
{
struct var
{
static FTerm* init_term_object; // Global FTerm object
static bool term_initialized; // Global init state
static std::size_t object_counter; // Counts the number of object instances
};
FTerm* var::init_term_object{nullptr};
bool var::term_initialized{false};
std::size_t var::object_counter{0};
} // namespace internal
//----------------------------------------------------------------------
// class FTerm
//----------------------------------------------------------------------
// constructors and destructor
//----------------------------------------------------------------------
FTerm::FTerm()
{
internal::var::object_counter++;
}
//----------------------------------------------------------------------
FTerm::~FTerm() // destructor
{
if ( internal::var::init_term_object == this )
finish(); // Resetting console settings
internal::var::object_counter--;
if ( internal::var::object_counter == 0 )
printExitMessage();
}
// public methods of FTerm
//----------------------------------------------------------------------
auto FTerm::getLineNumber() -> std::size_t
{
static auto& fterm_data = FTermData::getInstance();
const auto& term_geometry = fterm_data.getTerminalGeometry();
if ( term_geometry.getHeight() == 0 )
detectTermSize();
return term_geometry.getHeight();
}
//----------------------------------------------------------------------
auto FTerm::getColumnNumber() -> std::size_t
{
static auto& fterm_data = FTermData::getInstance();
const auto& term_geometry = fterm_data.getTerminalGeometry();
if ( term_geometry.getWidth() == 0 )
detectTermSize();
return term_geometry.getWidth();
}
//----------------------------------------------------------------------
auto FTerm::getKeyName (FKey keynum) -> FString
{
static const auto& keyboard = FKeyboard::getInstance();
return keyboard.getKeyName (keynum);
}
//----------------------------------------------------------------------
auto FTerm::getCharSubstitutionMap() & -> FCharSubstitution&
{
static auto& fterm_data = FTermData::getInstance();
return fterm_data.getCharSubstitutionMap();
}
//----------------------------------------------------------------------
auto FTerm::getTTYFileDescriptor() -> int
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.getTTYFileDescriptor();
}
//----------------------------------------------------------------------
auto FTerm::getTermType() -> std::string
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.getTermType();
}
//----------------------------------------------------------------------
auto FTerm::getTermFileName() -> std::string
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.getTermFileName();
}
//----------------------------------------------------------------------
auto FTerm::getTabstop() -> int
{
return FTermcap::tabstop;
}
//----------------------------------------------------------------------
auto FTerm::getMaxColor() -> int
{
return FTermcap::max_color;
}
//----------------------------------------------------------------------
auto FTerm::hasUTF8() -> bool
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.hasUTF8Console();
}
//----------------------------------------------------------------------
auto FTerm::isMonochron() -> bool
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.isMonochron();
}
//----------------------------------------------------------------------
auto FTerm::isNewFont() -> bool
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.isNewFont();
}
//----------------------------------------------------------------------
auto FTerm::isInitialized() -> bool
{
return internal::var::term_initialized;
}
//----------------------------------------------------------------------
auto FTerm::isCursorHideable() -> bool
{
const auto& cursor_off_str = disableCursorString();
return ! cursor_off_str.empty();
}
//----------------------------------------------------------------------
auto FTerm::isEncodable (const wchar_t& c) -> bool
{
const auto& ch = charEncode(c);
return ch > 0 && ch != c;
}
//----------------------------------------------------------------------
auto FTerm::hasChangedTermSize() -> bool
{
static auto& fterm_data = FTermData::getInstance();
return fterm_data.hasTermResized();
}
//----------------------------------------------------------------------
auto FTerm::hasShadowCharacter() -> bool
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.hasShadowCharacter();
}
//----------------------------------------------------------------------
auto FTerm::hasHalfBlockCharacter() -> bool
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.hasHalfBlockCharacter();
}
//----------------------------------------------------------------------
auto FTerm::hasAlternateScreen() -> bool
{
static const auto& fterm_data = FTermData::getInstance();
return fterm_data.hasAlternateScreen();
}
//----------------------------------------------------------------------
auto FTerm::canChangeColorPalette() -> bool
{
static const auto& fterm_data = FTermData::getInstance();
if ( fterm_data.isTermType ( FTermType::cygwin
| FTermType::kde_konsole
| FTermType::tera_term
| FTermType::mlterm
| FTermType::netbsd_con
| FTermType::openbsd_con
| FTermType::sun_con
| FTermType::ansi ) )
return false;
return FTermcap::can_change_color_palette;
}
//----------------------------------------------------------------------
void FTerm::setTermType (const std::string& term_name)
{
static auto& fterm_data = FTermData::getInstance();
fterm_data.setTermType(term_name);
}
//----------------------------------------------------------------------
void FTerm::setInsertCursor (bool enable)
{
if ( enable )
setInsertCursorStyle();
else
setOverwriteCursorStyle();
}
//----------------------------------------------------------------------
void FTerm::redefineDefaultColors (bool enable)
{
if ( isNewFont() ) // NewFont need the reverse-video attribute
return;
FTermXTerminal::getInstance().redefineDefaultColors (enable);
}
//----------------------------------------------------------------------
void FTerm::setDblclickInterval (const uInt64 timeout)
{
static const auto& mouse = FMouseControl::getInstance();
mouse.setDblclickInterval(timeout);
}
//----------------------------------------------------------------------
void FTerm::useAlternateScreen (bool enable)
{
// Sets alternate screen usage
FTermData::getInstance().useAlternateScreen(enable);
}
//----------------------------------------------------------------------
auto FTerm::setUTF8 (bool enable) -> bool // UTF-8 (Unicode)
{
static auto& data = FTermData::getInstance();
if ( data.isUTF8() == enable )
return enable;
data.setUTF8(enable);
#if defined(__linux__)
FTermLinux::getInstance().setUTF8 (enable);
#endif
return data.isUTF8();
}
//----------------------------------------------------------------------
auto FTerm::setVGAFont() -> bool
{
static auto& data = FTermData::getInstance();
if ( data.isVGAFont() )
return data.isVGAFont();
if ( hasNoFontSettingOption() )
return false;
if ( data.isTermType ( FTermType::xterm
| FTermType::screen
| FTermType::urxvt )
|| FTermcap::osc_support )
{
data.setVGAFont(true);
// Set font in xterm to vga
FTermXTerminal::getInstance().setFont("vga");
data.setTermEncoding (Encoding::PC);
data.setNewFont(false);
}
#if defined(__linux__)
else if ( data.isTermType(FTermType::linux_con) )
{
static auto& linux_console = FTermLinux::getInstance();
data.setVGAFont(linux_console.loadVGAFont());
}
#endif // defined(__linux__)
else
data.setVGAFont(false);
if ( data.isVGAFont() )
{
data.supportShadowCharacter (true);
data.supportHalfBlockCharacter (true);
}
return data.isVGAFont();
}
//----------------------------------------------------------------------
auto FTerm::setNewFont() -> bool
{
static auto& data = FTermData::getInstance();
if ( isNewFont() )
return true;
if ( hasNoFontSettingOption() )
return false;
if ( data.isTermType ( FTermType::xterm
| FTermType::screen
| FTermType::urxvt )
|| FTermcap::osc_support )
{
data.setNewFont(true);
// Set font in xterm to 8x16graph
FTermXTerminal::getInstance().setFont("8x16graph");
}
#if defined(__linux__)
else if ( data.isTermType(FTermType::linux_con) )
{
static auto& linux_console = FTermLinux::getInstance();
data.setNewFont(linux_console.loadNewFont());
}
#endif // defined(__linux__)
else
data.setNewFont(false);
if ( isNewFont() )
{
data.supportShadowCharacter (true);
data.supportHalfBlockCharacter (true);
}
return isNewFont();
}
//----------------------------------------------------------------------
auto FTerm::resetFont() -> bool
{
bool retval{false};
auto& data = FTermData::getInstance();
if ( ! (data.isNewFont() || data.isVGAFont()) )
return false;
data.setNewFont(false);
data.setVGAFont(false);
if ( data.isTermType ( FTermType::xterm
| FTermType::screen
| FTermType::urxvt )
|| FTermcap::osc_support )
{
const auto& font = data.getXtermFont();
if ( font.getLength() > 2 )
{
// restore saved xterm font
FTermXTerminal::getInstance().setFont(font);
}
else
{
// Set font in xterm to vga
FTermXTerminal::getInstance().setFont("vga");
}
retval = true;
}
#if defined(__linux__)
else if ( data.isTermType(FTermType::linux_con) )
{
static auto& linux_console = FTermLinux::getInstance();
retval = linux_console.loadOldFont();
}
#endif // defined(__linux__)
if ( retval )
{
data.setVGAFont(false);
data.setNewFont(false);
}
return retval;
}
//----------------------------------------------------------------------
auto FTerm::openConsole() -> int
{
static auto& data = FTermData::getInstance();
int fd = data.getTTYFileDescriptor();
const auto& termfilename = data.getTermFileName();
if ( termfilename.empty() )
return 0;
if ( fd >= 0 ) // console is already opened
return 0;
constexpr std::array<const char*, 6> terminal_devices =
{{
"/proc/self/fd/0",
"/dev/tty",
"/dev/tty0",
"/dev/vc/0",
"/dev/systty",
"/dev/console"
}};
for (auto&& entry : terminal_devices)
{
static const auto& fsys = FSystem::getInstance();
fd = fsys->open(entry, O_RDWR, 0);
data.setTTYFileDescriptor(fd);
if ( fd >= 0 )
return 0;
}
return -1; // No file descriptor referring to the console
}
//----------------------------------------------------------------------
auto FTerm::closeConsole() -> int
{
static auto& data = FTermData::getInstance();
const int fd = data.getTTYFileDescriptor();
int ret{-1};
if ( fd < 0 ) // console is already closed
return 0;
static const auto& fsys = FSystem::getInstance();
ret = fsys->close(fd); // close console
data.setTTYFileDescriptor(-1);
if ( ret == 0 )
return 0;
return -1;
}
//----------------------------------------------------------------------
auto FTerm::moveCursorString (int xold, int yold, int xnew, int ynew) -> std::string
{
// Returns the cursor move string
static const auto& data = FTermData::getInstance();
if ( data.hasCursorOptimisation() )
{
static auto& opti_move = FOptiMove::getInstance();
return opti_move.moveCursor (xold, yold, xnew, ynew);
}
const auto& cursor_addr = FTermcap::encodeMotionParameter(TCAP(t_cursor_address), xnew, ynew);
return cursor_addr;
}
//----------------------------------------------------------------------
auto FTerm::cursorsVisibilityString (bool enable) -> std::string
{
// Hides or shows the input cursor on the terminal
std::string visibility_str{};
static auto& data = FTermData::getInstance();
if ( data.isCursorHidden() == enable )
return {};
if ( enable )
{
visibility_str = disableCursorString();
if ( ! visibility_str.empty() )
data.setCursorHidden (true); // Global state
}
else
{
visibility_str = enableCursorString();
if ( ! visibility_str.empty() )
data.setCursorHidden (false); // Global state
}
return visibility_str;
}
//----------------------------------------------------------------------
void FTerm::detectTermSize()
{
// Detect the terminal width and height
struct winsize win_size{};
static auto& data = FTermData::getInstance();
auto& term_geometry = data.getTerminalGeometry();
int ret{};
errno = 0;
do
{
static const auto& fsys = FSystem::getInstance();
ret = fsys->ioctl (FTermios::getStdOut(), TIOCGWINSZ, &win_size);
}
while ( errno == EINTR );
if ( ret != 0 || win_size.ws_col == 0 || win_size.ws_row == 0 )
{
term_geometry.setPos (1, 1);
// Use COLUMNS or fallback to the xterm default width of 80 characters
const auto& Columns = env2uint ("COLUMNS");
term_geometry.setWidth( ( Columns == 0) ? 80 : Columns);
// Use LINES or fallback to the xterm default height of 24 characters
const auto& Lines = env2uint ("LINES");
term_geometry.setHeight( ( Lines == 0 ) ? 24 : Lines);
}
else
{
term_geometry.setRect(1, 1, win_size.ws_col, win_size.ws_row);
}
static auto& opti_move = FOptiMove::getInstance();
opti_move.setTermSize ( term_geometry.getWidth()
, term_geometry.getHeight() );
}
//----------------------------------------------------------------------
void FTerm::setTermSize (const FSize& size)
{
// Set xterm size
static auto& xterm = FTermXTerminal::getInstance();
xterm.setTermSize (size);
}
//----------------------------------------------------------------------
void FTerm::setTermTitle (const FString& title)
{
// Set the xterm window title
static auto& xterm = FTermXTerminal::getInstance();
xterm.setTitle (title);
}
//----------------------------------------------------------------------
void FTerm::setKDECursor (KdeKonsoleCursorShape style)
{
// Set cursor style in KDE konsole
if ( ! FTermData::getInstance().isTermType(FTermType::kde_konsole) )
return;
oscPrefix();
paddingPrintf (OSC "50;CursorShape=%d" BEL, style);
oscPostfix();
std::fflush(stdout);
}
//----------------------------------------------------------------------
void FTerm::saveColorMap()
{
#if defined(__linux__)
FTermLinux::getInstance().saveColorMap();
#endif
}
//----------------------------------------------------------------------
void FTerm::resetColorMap()
{
const auto& oc = TCAP(t_orig_colors);
const auto& op = TCAP(t_orig_pair);
if ( oc )
paddingPrint (oc);
#if defined(__linux__)
else
FTermLinux::getInstance().resetColorMap();
#endif
if ( op )
paddingPrint (op);
std::fflush(stdout);
}
//----------------------------------------------------------------------
void FTerm::clearTerminalAttributes()
{
// Turn off all attributes
if ( TCAP(t_exit_attribute_mode) )
{
paddingPrint (TCAP(t_exit_attribute_mode));
std::fflush(stdout);
}
// Turn off pc charset mode
if ( TCAP(t_exit_pc_charset_mode) )
{
paddingPrint (TCAP(t_exit_pc_charset_mode));
std::fflush(stdout);
}
}
//----------------------------------------------------------------------
void FTerm::setPalette (FColor index, int r, int g, int b)
{
// Redefine RGB color value for a palette entry
const auto& Ic = TCAP(t_initialize_color);
const auto& Ip = TCAP(t_initialize_pair);
bool state{false};
index = FOptiAttr::vga2ansi(index);
if ( Ic || Ip )
{
const int rr = (r * 1001) / 256;
const int gg = (g * 1001) / 256;
const int bb = (b * 1001) / 256;
const std::string& color_str = \
[&index, &rr, &gg, &bb, &Ic, &Ip] ()
{
if ( Ic )
return FTermcap::encodeParameter(Ic, uInt16(index), rr, gg, bb);
if ( Ip )
return FTermcap::encodeParameter(Ip, uInt16(index), 0, 0, 0, rr, gg, bb);
return std::string{};
}();
if ( ! color_str.empty() )
{
paddingPrint (color_str);
state = true;
}
}
#if defined(__linux__)
else
{
state = FTermLinux::getInstance().setPalette(index, r, g, b);
}
#endif
if ( state )
std::fflush(stdout);
}
//----------------------------------------------------------------------
#if defined(__linux__) || defined(UNIT_TEST)
void FTerm::setBeep (int Hz, int ms)
{
FTermLinux::getInstance().setBeep (Hz, ms);
}
#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
void FTerm::setBeep (int Hz, int ms)
{
FTermFreeBSD::getInstance().setBeep (Hz, ms);
}
#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(UNIT_TEST)
void FTerm::setBeep (int Hz, int ms)
{
FTermOpenBSD::getInstance().setBeep (Hz, ms);
}
#else
void FTerm::setBeep (int, int)
{ }
#endif // defined(__linux__)
//----------------------------------------------------------------------
void FTerm::resetBeep()
{
#if defined(__linux__) || defined(UNIT_TEST)
FTermLinux::getInstance().resetBeep();
#endif
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
FTermFreeBSD::getInstance().resetBeep();
#endif
#if defined(__NetBSD__) || defined(__OpenBSD__) || defined(UNIT_TEST)
FTermOpenBSD::getInstance().resetBeep();
#endif
}
//----------------------------------------------------------------------
void FTerm::beep()
{
if ( TCAP(t_bell) )
{
paddingPrint (TCAP(t_bell));
std::fflush(stdout);
}
}
//----------------------------------------------------------------------
void FTerm::setEncoding (Encoding enc)
{
assert ( enc == Encoding::UTF8
|| enc == Encoding::VT100 // VT100 line drawing
|| enc == Encoding::PC // CP-437
|| enc == Encoding::ASCII
|| enc == Encoding::Unknown
|| enc == Encoding::NUM_OF_ENCODINGS );
static auto& data = FTermData::getInstance();
data.setTermEncoding (enc);
if ( data.isTermType(FTermType::linux_con) )
{
static auto& opti_move = FOptiMove::getInstance();
if ( enc == Encoding::VT100 || enc == Encoding::PC )
{
const char* empty{nullptr};
opti_move.set_tabular (empty);
}
else
opti_move.set_tabular (TCAP(t_tab));
}
}
//----------------------------------------------------------------------
auto FTerm::getEncodingString() -> std::string
{
static auto& data = FTermData::getInstance();
const auto& term_encoding = data.getTerminalEncoding();
const auto& encoding_list = data.getEncodingList();
const auto& found = \
std::find_if ( encoding_list.cbegin()
, encoding_list.cend()
, [&term_encoding] (const auto& entry)
{
return entry.second == term_encoding;
} );
return ( found != encoding_list.cend() ) ? found->first : "";
}
//----------------------------------------------------------------------
auto FTerm::charEncode (const wchar_t& c) -> wchar_t
{
static const auto& data = FTermData::getInstance();
return charEncode (c, data.getTerminalEncoding());
}
//----------------------------------------------------------------------
auto FTerm::charEncode (const wchar_t& c, const Encoding& enc) -> wchar_t
{
const auto& character = FCharMap::getCharEncodeMap();
const auto& cend = character.cend();
const auto& found = \
std::find_if ( character.cbegin(), cend
, [&c] (const auto& entry)
{
return entry.unicode == c;
} );
if ( found == cend )
return c;
const auto& ch_enc = FCharMap::getCharacter(*found, enc);
if ( enc == Encoding::PC && ch_enc == c )
return finalcut::unicode_to_cp437(c);
return ch_enc;
}
//----------------------------------------------------------------------
auto FTerm::scrollTermForward() -> bool
{
if ( TCAP(t_scroll_forward) )
{
paddingPrint (TCAP(t_scroll_forward));
std::fflush(stdout);
return true;
}
return false;
}
//----------------------------------------------------------------------
auto FTerm::scrollTermReverse() -> bool
{
if ( TCAP(t_scroll_reverse) )
{
paddingPrint (TCAP(t_scroll_reverse));
std::fflush(stdout);
return true;
}
return false;
}
//----------------------------------------------------------------------
void FTerm::paddingPrint (const std::string& str, int affcnt)
{
auto status = FTermcap::paddingPrint (str, affcnt);
if ( status == FTermcap::Status::Error )
{
// Possible error handling
}
}
//----------------------------------------------------------------------
void FTerm::stringPrint (const std::string& str)
{
auto status = FTermcap::stringPrint (str);
if ( status == FTermcap::Status::Error )
{
// Possible error handling
}
}
// protected methods of FTerm
//----------------------------------------------------------------------
void FTerm::initScreenSettings()
{
#if defined(__linux__)
// Important: Do not use setNewFont() or setVGAFont() after
// the console character mapping has been initialized
FTermLinux::getInstance().initCharMap();
#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
FTermFreeBSD::getInstance().initCharMap();
#endif
// set xterm underline cursor
FTermXTerminal::getInstance().setCursorStyle (XTermCursorStyle::BlinkingUnderline);
// set xterm color settings to defaults
FTermXTerminal::getInstance().setDefaults();
}
//----------------------------------------------------------------------
void FTerm::changeTermSizeFinished()
{
static auto& data = FTermData::getInstance();
data.setTermResized(false);
}
// private methods of FTerm
//----------------------------------------------------------------------
inline auto FTerm::getStartOptions() -> FStartOptions&
{
static auto& start_options = FStartOptions::getInstance();
return start_options;
}
//----------------------------------------------------------------------
void FTerm::init_global_values()
{
// Initialize global values
FTermData::getInstance().setNewFont(false); // Preset to false
if ( ! getStartOptions().terminal_detection )
{
FTermDetection::getInstance().setTerminalDetection (false);
}
}
//----------------------------------------------------------------------
void FTerm::init_terminal_device_path()
{
std::array<char, 256> termfilename{};
const auto& stdout_no = FTermios::getStdOut();
if ( ttyname_r(stdout_no, termfilename.data(), termfilename.size()) )
termfilename[0] = '\0';
FTermData::getInstance().setTermFileName(termfilename.data());
}
//----------------------------------------------------------------------
void FTerm::oscPrefix()
{
static const auto& data = FTermData::getInstance();
if ( data.isTermType(FTermType::tmux) )
{
// tmux device control string
paddingPrint (ESC "Ptmux;" ESC);
}
else if ( data.isTermType(FTermType::screen) )
{
// GNU Screen device control string
paddingPrint (ESC "P");
}
}
//----------------------------------------------------------------------
void FTerm::oscPostfix()
{
static const auto& data = FTermData::getInstance();
if ( data.isTermType(FTermType::screen)
|| data.isTermType(FTermType::tmux) )
{
// GNU Screen/tmux string terminator
paddingPrint (ESC "\\");
}
}
//----------------------------------------------------------------------
void FTerm::init_alt_charset()
{
// Read the used VT100 pairs
std::unordered_map<uChar, uChar> vt100_alt_char;
auto& character = FCharMap::getCharEncodeMap();
if ( TCAP(t_acs_chars) )
{
for (std::size_t n{0}; TCAP(t_acs_chars)[n]; n += 2)
{
// insert the VT100 key/value pairs into a map
const auto& p1 = uChar(TCAP(t_acs_chars)[n]);
const auto& p2 = uChar(TCAP(t_acs_chars)[n + 1]);
vt100_alt_char[p1] = p2;
}
}
// Update array 'character' with discovered VT100 pairs
for (auto&& pair : FCharMap::getDECSpecialGraphics())
{
const auto& keyChar = uChar(pair.key);
const auto& altChar = wchar_t(vt100_alt_char[keyChar]);
const auto& utf8char = wchar_t(pair.unicode);
const auto& p = std::find_if ( character.cbegin()
, character.cend()
, [&utf8char] (const auto& entry)
{ return entry.unicode == utf8char; } );
if ( p != character.cend() ) // found in character
{
const auto item = std::size_t(std::distance(character.cbegin(), p));
if ( altChar ) // update alternate character set
FCharMap::setCharacter(character[item], Encoding::VT100) = altChar;
else // delete VT100 char in character
FCharMap::setCharacter(character[item], Encoding::VT100) = L'\0';
}
}
}
//----------------------------------------------------------------------
void FTerm::init_pc_charset()
{
bool reinit{false};
static auto& opti_attr = FOptiAttr::getInstance();
static const auto& data = FTermData::getInstance();
// rxvt does not support pc charset
if ( data.isTermType(FTermType::rxvt | FTermType::urxvt) )
return;
if ( data.isTermType ( FTermType::gnome_terminal
| FTermType::linux_con ) )
{
// Fallback if tcap "S2" is not found
if ( ! TCAP(t_enter_pc_charset_mode) )
{
if ( data.hasUTF8Console() )
{
// Select iso8859-1 + null mapping
TCAP(t_enter_pc_charset_mode) = ESC "%@" ESC "(U";
}
else
{
// Select null mapping
TCAP(t_enter_pc_charset_mode) = ESC "(U";
}
opti_attr.set_enter_pc_charset_mode \
(TCAP(t_enter_pc_charset_mode));
reinit = true;
}
// Fallback if tcap "S3" is not found
if ( ! TCAP(t_exit_pc_charset_mode) )
{
if ( data.hasUTF8Console() )
{
// Select ascii mapping + utf8
TCAP(t_exit_pc_charset_mode) = ESC "(B" ESC "%G";
}
else
{
// Select ascii mapping
TCAP(t_enter_pc_charset_mode) = ESC "(B";
}
opti_attr.set_exit_pc_charset_mode \
(TCAP(t_exit_pc_charset_mode));
reinit = true;
}
}
if ( reinit )
opti_attr.initialize();
}
//----------------------------------------------------------------------
void FTerm::init_cygwin_charmap()
{
// Replace don't printable PC charset characters in a Cygwin terminal
static auto& data = FTermData::getInstance();
if ( ! data.isTermType(FTermType::cygwin) )
return;
// PC encoding changes
for (auto&& entry : FCharMap::getCharEncodeMap())
{
if ( entry.unicode == UniChar::BlackUpPointingTriangle ) // ▲
entry.pc = 0x18;
if ( entry.unicode == UniChar::BlackDownPointingTriangle ) // ▼
entry.pc = 0x19;
if ( entry.unicode == UniChar::InverseBullet // ◘
|| entry.unicode == UniChar::InverseWhiteCircle // ◙
|| entry.unicode == UniChar::UpDownArrow // ↕
|| entry.unicode == UniChar::LeftRightArrow // ↔
|| entry.unicode == UniChar::DoubleExclamationMark // ‼
|| entry.unicode == UniChar::BlackRectangle // ▬
|| entry.unicode == UniChar::RightwardsArrow // →
|| entry.unicode == UniChar::Section // §
|| entry.unicode == UniChar::SquareRoot ) // SquareRoot √
entry.pc = entry.ascii;
}
// General encoding changes
auto& sub_map = data.getCharSubstitutionMap();
sub_map.setCharMapping({L'•', L'*'});
sub_map.setCharMapping({L'●', L'*'});
sub_map.setCharMapping({L'◘', L'*'});
sub_map.setCharMapping({L'○', L'*'});
sub_map.setCharMapping({L'◙', L'*'});
sub_map.setCharMapping({L'♪', L'♫'});
sub_map.setCharMapping({L'√', L'x'});
sub_map.setCharMapping({L'ˣ', L'`'});
sub_map.sort();
}
//----------------------------------------------------------------------
void FTerm::init_fixed_max_color()
{
// Initialize maximum number of colors for known terminals
static const auto& data = FTermData::getInstance();
if ( data.isTermType ( FTermType::cygwin
| FTermType::putty
| FTermType::tera_term
| FTermType::rxvt ) )
{
FTermcap::max_color = 16;
}
}
//----------------------------------------------------------------------
void FTerm::init_teraterm_charmap()
{
// Tera Term can't print ascii characters < 0x20
if ( ! FTermData::getInstance().isTermType(FTermType::tera_term) )
return;
for (auto&& entry : FCharMap::getCharEncodeMap())
if ( entry.pc < 0x20 )
entry.pc = entry.ascii;
}
//----------------------------------------------------------------------
void FTerm::init_termcap()
{
// Initialize the terminal capabilities
FTermcap::init();
}
//----------------------------------------------------------------------
void FTerm::init_quirks()
{
// Initialize terminal quirks
FTermcapQuirks::terminalFixup(); // Fix terminal quirks
}
//----------------------------------------------------------------------
void FTerm::init_optiMove()
{
// Duration precalculation of the cursor movement strings
const FOptiMove::TermEnv optimove_env =
{
TCAP(t_cursor_home),
TCAP(t_carriage_return),
TCAP(t_cursor_to_ll),
TCAP(t_tab),
TCAP(t_back_tab),
TCAP(t_cursor_up),
TCAP(t_cursor_down),
TCAP(t_cursor_left),
TCAP(t_cursor_right),
TCAP(t_cursor_address),
TCAP(t_column_address),
TCAP(t_row_address),
TCAP(t_parm_up_cursor),
TCAP(t_parm_down_cursor),
TCAP(t_parm_left_cursor),
TCAP(t_parm_right_cursor),
TCAP(t_erase_chars),
TCAP(t_repeat_char),
TCAP(t_clr_bol),
TCAP(t_clr_eol),
FTermcap::tabstop,
FTermcap::automatic_left_margin,
FTermcap::eat_nl_glitch
};
static auto& opti_move = FOptiMove::getInstance();
opti_move.setTermEnvironment(optimove_env);
}
//----------------------------------------------------------------------
void FTerm::init_optiAttr()
{
// Setting video attribute optimization
const FOptiAttr::TermEnv optiattr_env =
{
TCAP(t_enter_bold_mode),
TCAP(t_exit_bold_mode),
TCAP(t_enter_dim_mode),
TCAP(t_exit_dim_mode),
TCAP(t_enter_italics_mode),
TCAP(t_exit_italics_mode),
TCAP(t_enter_underline_mode),
TCAP(t_exit_underline_mode),
TCAP(t_enter_blink_mode),
TCAP(t_exit_blink_mode),
TCAP(t_enter_reverse_mode),
TCAP(t_exit_reverse_mode),
TCAP(t_enter_standout_mode),
TCAP(t_exit_standout_mode),
TCAP(t_enter_secure_mode),
TCAP(t_exit_secure_mode),
TCAP(t_enter_protected_mode),
TCAP(t_exit_protected_mode),
TCAP(t_enter_crossed_out_mode),
TCAP(t_exit_crossed_out_mode),
TCAP(t_enter_dbl_underline_mode),
TCAP(t_exit_dbl_underline_mode),
TCAP(t_set_attributes),
TCAP(t_exit_attribute_mode),
TCAP(t_enter_alt_charset_mode),
TCAP(t_exit_alt_charset_mode),
TCAP(t_enter_pc_charset_mode),
TCAP(t_exit_pc_charset_mode),
TCAP(t_set_a_foreground),
TCAP(t_set_a_background),
TCAP(t_set_foreground),
TCAP(t_set_background),
TCAP(t_orig_pair),
TCAP(t_orig_pair),
TCAP(t_orig_colors),
FTermcap::max_color,
FTermcap::attr_without_color,
FTermcap::ansi_default_color
};
static auto& opti_attr = FOptiAttr::getInstance();
opti_attr.setTermEnvironment(optiattr_env);
}
//----------------------------------------------------------------------
auto FTerm::init_font() -> bool
{
if ( getStartOptions().vgafont && ! setVGAFont() )
{
setExitMessage("VGAfont is not supported by this terminal");
FApplication::exit(EXIT_FAILURE);
}
if ( getStartOptions().newfont && ! setNewFont() )
{
setExitMessage("Newfont is not supported by this terminal");
FApplication::exit(EXIT_FAILURE);
}
return ! FApplication::isQuit();
}
//----------------------------------------------------------------------
void FTerm::init_locale()
{
// Init current locale
static const auto& data = FTermData::getInstance();
const auto& termtype = data.getTermType();
const char* locale_name = std::setlocale (LC_ALL, "");
std::setlocale (LC_NUMERIC, "");
// Get XTERM_LOCALE
const char* locale_xterm = std::getenv("XTERM_LOCALE");
// set LC_ALL to XTERM_LOCALE
if ( locale_xterm )
locale_name = std::setlocale (LC_ALL, locale_xterm);
// TeraTerm can not show UTF-8 character
if ( data.isTermType(FTermType::tera_term)
&& ! std::strcmp(nl_langinfo(CODESET), "UTF-8") )
locale_name = std::setlocale (LC_ALL, "C");
// Kterm
if ( data.isTermType(FTermType::kterm)
&& ! std::strcmp(nl_langinfo(CODESET), "UTF-8") )
locale_name = std::setlocale (LC_ALL, "C");
// Sun (color) workstation console can't show UTF-8 character
if ( termtype.substr(0, 3) == "sun"
&& ! std::strcmp(nl_langinfo(CODESET), "UTF-8") )
locale_name = std::setlocale (LC_ALL, "C");
// Try to found a meaningful content for locale_name
if ( locale_name )
locale_name = std::setlocale (LC_CTYPE, nullptr);
else
{
locale_name = std::getenv("LC_ALL");
if ( ! locale_name )
{
locale_name = std::getenv("LC_CTYPE");
if ( ! locale_name )
locale_name = std::getenv("LANG");
}
}
// Fallback to C
if ( ! locale_name )
std::setlocale (LC_ALL, "C");
}
//----------------------------------------------------------------------
void FTerm::init_encoding()
{
// detect encoding
bool force_vt100{false}; // VT100 line drawing (G1 character set)
init_encoding_set();
static const auto& data = FTermData::getInstance();
if ( data.isTermType(FTermType::rxvt)
&& ! data.isTermType(FTermType::urxvt) )
force_vt100 = true; // This rxvt terminal does not support utf-8
init_term_encoding();
init_pc_charset();
init_individual_term_encoding();
if ( force_vt100 )
init_force_vt100_encoding();
else
init_utf8_without_alt_charset();
init_tab_quirks();
if ( getStartOptions().encoding != Encoding::Unknown )
{
setEncoding(getStartOptions().encoding);
}
}
//----------------------------------------------------------------------
inline void FTerm::init_encoding_set()
{
// Define the encoding set
static auto& data = FTermData::getInstance();
auto& encoding_list = data.getEncodingList();
encoding_list["UTF8"] = Encoding::UTF8;
encoding_list["UTF-8"] = Encoding::UTF8;
encoding_list["VT100"] = Encoding::VT100; // VT100 line drawing
encoding_list["PC"] = Encoding::PC; // CP-437
encoding_list["ASCII"] = Encoding::ASCII;
}
//----------------------------------------------------------------------
void FTerm::init_term_encoding()
{
const auto& stdout_no = FTermios::getStdOut();
static auto& data = FTermData::getInstance();
const auto& termtype = data.getTermType();
static const auto& fsys = FSystem::getInstance();
if ( fsys->isTTY(stdout_no)
&& ! std::strcmp(nl_langinfo(CODESET), "UTF-8") )
{
data.setUTF8Console(true);
data.setTermEncoding (Encoding::UTF8);
data.setUTF8(true);
setUTF8(true);
static auto& keyboard = FKeyboard::getInstance();
keyboard.enableUTF8();
}
else if ( fsys->isTTY(stdout_no)
&& (termtype.length() > 0)
&& (TCAP(t_exit_alt_charset_mode) != nullptr) )
{
data.setVT100Console (true);
data.setTermEncoding (Encoding::VT100);
}
else
{
data.setASCIIConsole (true);
data.setTermEncoding (Encoding::ASCII);
}
}
//----------------------------------------------------------------------
void FTerm::init_individual_term_encoding()
{
static auto& data = FTermData::getInstance();
const auto is_utf8 = data.isUTF8();
const auto is_putty = data.isTermType(FTermType::putty);
const auto is_teraterm = data.isTermType(FTermType::tera_term);
const auto is_non_utf8_putty = is_putty && ! is_utf8;
const auto is_non_utf8_teraterm = is_teraterm && ! is_utf8;
if ( isNewFont() || is_non_utf8_putty || is_non_utf8_teraterm )
{
data.setTermEncoding (Encoding::PC);
}
}
//----------------------------------------------------------------------
void FTerm::init_force_vt100_encoding()
{
static auto& data = FTermData::getInstance();
data.setVT100Console(true);
data.setTermEncoding (Encoding::VT100);
}
//----------------------------------------------------------------------
void FTerm::init_utf8_without_alt_charset()
{
// Fall back to ascii for utf-8 terminals that
// do not support VT100 line drawings
static auto& data = FTermData::getInstance();
if ( FTermcap::no_utf8_acs_chars && data.isUTF8()
&& data.getTerminalEncoding() == Encoding::VT100 )
{
data.setASCIIConsole(true);
data.setTermEncoding (Encoding::ASCII);
}
}
//----------------------------------------------------------------------
void FTerm::init_tab_quirks()
{
// In some alternative character sets, a tab character prints a '○'
// on the terminal and does not move the cursor to the next tab stop
// position
const auto& enc = FTermData::getInstance().getTerminalEncoding();
if ( enc == Encoding::VT100 || enc == Encoding::PC )
{
const char* empty{nullptr};
static auto& opti_move = FOptiMove::getInstance();
opti_move.set_tabular (empty);
}
}
//----------------------------------------------------------------------
void FTerm::init_captureFontAndTitle()
{
// Save the used xterm font and window title
if ( ! getStartOptions().terminal_data_request )
return;
static auto& data = FTermData::getInstance();
static auto& xterm = FTermXTerminal::getInstance();
xterm.captureFontAndTitle();
const auto& font = xterm.getFont();
const auto& title = xterm.getTitle();
if ( ! font.isEmpty() )
data.setXtermFont(font);
if ( ! title.isEmpty() )
data.setXtermTitle(title);
}
//----------------------------------------------------------------------
inline auto FTerm::hasNoFontSettingOption() -> bool
{
static const auto& data = FTermData::getInstance();
return ( data.isTermType ( FTermType::gnome_terminal
| FTermType::kde_konsole
| FTermType::putty
| FTermType::tera_term
| FTermType::cygwin
| FTermType::mintty ) );
}
//----------------------------------------------------------------------
void FTerm::setInsertCursorStyle()
{
FTermXTerminal::getInstance().setCursorStyle (XTermCursorStyle::BlinkingUnderline);
setKDECursor(KdeKonsoleCursorShape::Underline);
#if defined(__linux__)
static auto& linux_console = FTermLinux::getInstance();
linux_console.setCursorStyle (LinuxConsoleCursorStyle::Underscore);
#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
static auto& freebsd_console = FTermFreeBSD::getInstance();
freebsd_console.setCursorStyle (FreeBSDConsoleCursorStyle::Destructive);
#endif
if ( FTermData::getInstance().isTermType(FTermType::urxvt) )
FTermXTerminal::getInstance().setCursorColor ("rgb:ffff/ffff/ffff");
}
//----------------------------------------------------------------------
void FTerm::setOverwriteCursorStyle()
{
FTermXTerminal::getInstance().setCursorStyle (XTermCursorStyle::SteadyBlock);
setKDECursor(KdeKonsoleCursorShape::Block);
#if defined(__linux__)
static auto& linux_console = FTermLinux::getInstance();
linux_console.setCursorStyle (LinuxConsoleCursorStyle::FullBlock);
#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
static auto& freebsd_console = FTermFreeBSD::getInstance();
freebsd_console.setCursorStyle (FreeBSDConsoleCursorStyle::Normal);
#endif
if ( FTermData::getInstance().isTermType(FTermType::urxvt) )
FTermXTerminal::getInstance().setCursorColor ("rgb:eeee/0000/0000");
}
//----------------------------------------------------------------------
auto FTerm::enableCursorString() -> std::string
{
// Returns the cursor enable string
static constexpr std::string::size_type SIZE{32u};
std::string enable_str{};
enable_str.reserve(SIZE);
static const auto& vs = TCAP(t_cursor_visible);
static const auto& ve = TCAP(t_cursor_normal);
if ( ve )
enable_str = ve;
else if ( vs )
enable_str = vs;
#if defined(__linux__)
if ( FTermData::getInstance().isTermType(FTermType::linux_con) )
{
// Restore the last used Linux console cursor style
static auto& linux_console = FTermLinux::getInstance();
const auto& cstyle = linux_console.getCursorStyleString();
enable_str.append(cstyle);
}
#endif // defined(__linux__)
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
if ( FTermData::getInstance().isTermType(FTermType::freebsd_con) )
{
// Restore the last used FreeBSD console cursor style
static auto& freebsd_console = FTermFreeBSD::getInstance();
freebsd_console.setCursorStyle (freebsd_console.getCursorStyle());
}
#endif // defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
return enable_str;
}
//----------------------------------------------------------------------
auto FTerm::disableCursorString() -> std::string
{
// Returns the cursor disable string
static const auto& vi = TCAP(t_cursor_invisible);
if ( vi )
return vi;
return {};
}
//----------------------------------------------------------------------
void FTerm::enableMouse()
{
// Enable the terminal mouse support
if ( ! getStartOptions().mouse_support )
return;
bool gpm_mouse{false};
bool xterm_mouse{false};
#if defined(__linux__)
if ( FTermData::getInstance().isTermType(FTermType::linux_con)
&& openConsole() == 0 )
{
if ( FTermLinux::isLinuxConsole() )
gpm_mouse = true;
closeConsole();
}
#endif // defined(__linux__)
if ( TCAP(t_key_mouse)
&& ! FTermData::getInstance().isTermType(FTermType::linux_con) )
xterm_mouse = true;
static auto& keyboard = FKeyboard::getInstance();
keyboard.enableMouseSequences();
static auto& mouse = FMouseControl::getInstance();
mouse.setMaxWidth (uInt16(getColumnNumber()));
mouse.setMaxHeight (uInt16(getLineNumber()));
// Enable the linux general purpose mouse (gpm) server
mouse.useGpmMouse (gpm_mouse);
// Enable xterm mouse support
mouse.useXtermMouse (xterm_mouse);
mouse.enable();
}
//----------------------------------------------------------------------
inline void FTerm::disableMouse()
{
// Disable the terminal mouse support
static auto& keyboard = FKeyboard::getInstance();
keyboard.disableMouseSequences();
FMouseControl::getInstance().disable();
}
//----------------------------------------------------------------------
inline void FTerm::enableKeypad()
{
// Enter 'keyboard_transmit' mode
if ( TCAP(t_keypad_xmit) )
{
paddingPrint (TCAP(t_keypad_xmit));
std::fflush(stdout);
}
}
//----------------------------------------------------------------------
inline void FTerm::disableKeypad()
{
// Leave 'keyboard_transmit' mode
if ( TCAP(t_keypad_local) )
{
paddingPrint (TCAP(t_keypad_local));
std::fflush(stdout);
}
}
//----------------------------------------------------------------------
inline void FTerm::enableAlternateCharset()
{
// Enable alternate charset
if ( TCAP(t_enable_acs) )
{
paddingPrint (TCAP(t_enable_acs));
std::fflush(stdout);
}
}
//----------------------------------------------------------------------
inline void FTerm::enableApplicationEscKey()
{
// switch to application escape key mode
if ( FTermData::getInstance().isTermType(FTermType::mintty) )
FTerm::paddingPrint (CSI "?7727h");
}
//----------------------------------------------------------------------
inline void FTerm::disableApplicationEscKey()
{
// Switch to normal escape key mode
if ( FTermData::getInstance().isTermType(FTermType::mintty) )
paddingPrint (CSI "?7727l");
}
//----------------------------------------------------------------------
void FTerm::useAlternateScreenBuffer()
{
// Switch to the alternate screen
if ( ! hasAlternateScreen() )
return;
// Save current cursor position
if ( TCAP(t_save_cursor) )
{
paddingPrint (TCAP(t_save_cursor));
std::fflush(stdout);
}
// Saves the screen and the cursor position
if ( TCAP(t_enter_ca_mode) )
{
paddingPrint (TCAP(t_enter_ca_mode)); // Use alternate screen buffer
paddingPrint (TCAP(t_clear_screen)); // Ensure the display is cleared
std::fflush(stdout);
FTermData::getInstance().setAlternateScreenInUse(true);
}
}
//----------------------------------------------------------------------
void FTerm::useNormalScreenBuffer()
{
// Switch to the normal screen
if ( ! hasAlternateScreen() )
return;
// restores the screen and the cursor position
if ( TCAP(t_exit_ca_mode) )
{
paddingPrint (TCAP(t_exit_ca_mode)); // Use Normal Screen Buffer
std::fflush(stdout);
FTermData::getInstance().setAlternateScreenInUse(false);
}
// restore cursor to position of last save_cursor
if ( TCAP(t_restore_cursor) )
{
paddingPrint (TCAP(t_restore_cursor));
std::fflush(stdout);
}
}
//----------------------------------------------------------------------
void FTerm::init()
{
internal::var::init_term_object = this;
// Initialize global values for all objects
init_global_values();
// Initialize the terminal
if ( ! init_terminal() )
return;
// Set maximum number of colors for detected terminals
init_fixed_max_color();
// Initializes variables for the current terminal
init_termcap();
// Initialize terminal quirks
init_quirks();
// Initialize cursor movement optimization
init_optiMove();
// Initialize video attributes optimization
init_optiAttr();
// Initialize vt100 alternate character set
init_alt_charset();
// Pass the terminal capabilities to the keyboard object
FKeyboard::getInstance().setTermcapMap();
// Initializes locale information
init_locale();
// Detect environment and set encoding
init_encoding();
// Enable the terminal mouse support
enableMouse();
// Activate meta key sends escape + terminal focus event
if ( FTermData::getInstance().isTermType(FTermType::xterm) )
{
FTermXTerminal::getInstance().metaSendsESC(true);
if ( getStartOptions().terminal_focus_events )
FTermXTerminal::getInstance().setFocusSupport(true);
}
// switch to application escape key mode
enableApplicationEscKey();
// Enter 'keyboard_transmit' mode
enableKeypad();
// Switch to the alternate screen
useAlternateScreenBuffer();
// Enable alternate charset
enableAlternateCharset();
// Save the used xterm font and window title
init_captureFontAndTitle();
// KDE terminal cursor and cygwin + teraterm charmap correction
initTermspecifics();
// Reset all terminal attributes
clearTerminalAttributes();
// Set 220 Hz beep (100 ms)
setBeep(220, 100);
// Set FTerm signal handler
setSignalHandler();
if ( ! getStartOptions().cursor_optimisation )
{
FTermData::getInstance().supportCursorOptimisation(false);
}
// Activate the VGA or the new graphic font
// (depending on the initialization values)
if ( ! init_font() )
return;
// Turn off hardware echo
FTermios::unsetHardwareEcho();
// Switch to the raw mode
FTermios::setRawMode();
// The terminal is now initialized
internal::var::term_initialized = true;
}
//----------------------------------------------------------------------
auto FTerm::init_terminal() const -> bool
{
// Initialize termios
FTermios::init();
static const auto& fsys = FSystem::getInstance();
// Check if stdin is a tty
if ( ! fsys->isTTY(FTermios::getStdIn()) )
{
setExitMessage("FTerm: Standard input is not a TTY.");
FApplication::exit(EXIT_FAILURE);
return false;
}
// Get pathname of the terminal device
init_terminal_device_path();
// Initialize Linux or *BSD console
initOSspecifics();
// Save termios settings
try
{
FTermios::storeTTYsettings();
}
catch (const std::system_error& ex)
{
FString msg = "FTerm: " + FString{ex.what()};
setExitMessage(msg);
FApplication::exit(EXIT_FAILURE);
return false;
}
// Get output baud rate
initBaudRate();
// Terminal detection
static auto& term_detection = FTermDetection::getInstance();
term_detection.detect();
const auto& termtype = term_detection.getTermType();
setTermType(termtype.toString());
return true;
}
//----------------------------------------------------------------------
void FTerm::initOSspecifics() const
{
#if defined(__linux__)
static auto& linux_console = FTermLinux::getInstance();
linux_console.init(); // Initialize Linux console
#if DEBUG
static auto& data = FTermData::getInstance();
data.setFramebufferBpp (linux_console.getFramebufferBpp());
#endif
#endif // defined(__linux__)
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
static auto& freebsd_console = FTermFreeBSD::getInstance();
if ( getStartOptions().meta_sends_escape )
freebsd_console.enableMetaSendsEscape();
else
freebsd_console.disableMetaSendsEscape();
if ( getStartOptions().change_cursorstyle )
freebsd_console.enableChangeCursorStyle();
else
freebsd_console.disableChangeCursorStyle();
freebsd_console.init(); // Initialize BSD console
#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(UNIT_TEST)
static auto& openbsd_console = FTermOpenBSD::getInstance();
if ( getStartOptions().meta_sends_escape )
openbsd_console.enableMetaSendsEscape();
else
openbsd_console.disableMetaSendsEscape();
openbsd_console.init(); // Initialize wscons console
#endif
}
//----------------------------------------------------------------------
void FTerm::initTermspecifics() const
{
static const auto& data = FTermData::getInstance();
if ( data.isTermType(FTermType::kde_konsole) )
setKDECursor(KdeKonsoleCursorShape::Underline);
if ( data.isTermType(FTermType::cygwin) )
init_cygwin_charmap();
if ( data.isTermType(FTermType::tera_term) )
init_teraterm_charmap();
}
//----------------------------------------------------------------------
void FTerm::initBaudRate() const
{
const auto& stdout_no = FTermios::getStdOut();
const auto& baud = FTermios::getBaudRate();
FTermData::getInstance().setBaudrate(baud);
static const auto& fsys = FSystem::getInstance();
if ( fsys->isTTY(stdout_no) )
{
static auto& opti_move = FOptiMove::getInstance();
opti_move.setBaudRate(int(baud));
}
}
//----------------------------------------------------------------------
void FTerm::finish() const
{
// Set default signal handler
resetSignalHandler();
static const auto& data = FTermData::getInstance();
static auto& xterm = FTermXTerminal::getInstance();
if ( data.isTermType(FTermType::xterm)
&& ! data.isTermType(FTermType::rxvt) )
xterm.resetTitle();
// Restore the saved termios settings
FTermios::restoreTTYsettings();
// Reset all terminal attributes
clearTerminalAttributes();
// Reset xterm color settings to default values
xterm.resetDefaults();
// Set xterm full block cursor
xterm.setCursorStyle (XTermCursorStyle::SteadyBlock);
// Switch to normal escape key mode
disableApplicationEscKey();
finishOSspecifics();
if ( data.isTermType(FTermType::kde_konsole) )
setKDECursor(KdeKonsoleCursorShape::Block);
resetBeep();
// Disable the terminal mouse support
if ( getStartOptions().mouse_support )
disableMouse();
// Deactivate terminal focus event + meta key sends escape
if ( data.isTermType(FTermType::xterm) )
{
if ( getStartOptions().terminal_focus_events )
xterm.setFocusSupport(false);
xterm.metaSendsESC(false);
}
// Switch to the normal screen
useNormalScreenBuffer();
// leave 'keyboard_transmit' mode
disableKeypad();
finish_encoding();
if ( data.isNewFont() || data.isVGAFont() )
resetFont();
}
//----------------------------------------------------------------------
void FTerm::finishOSspecifics() const
{
#if defined(__linux__)
FTermLinux::getInstance().finish();
#elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(UNIT_TEST)
FTermFreeBSD::getInstance().finish();
#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(UNIT_TEST)
FTermOpenBSD::getInstance().finish();
#endif
}
//----------------------------------------------------------------------
void FTerm::finish_encoding() const
{
#if defined(__linux__)
static const auto& data = FTermData::getInstance();
if ( data.isTermType(FTermType::linux_con)
&& data.hasUTF8Console() )
setUTF8(true);
#endif
}
//----------------------------------------------------------------------
void FTerm::printExitMessage()
{
// Print exit message
auto& exit_message = getExitMessage();
if ( ! exit_message.empty() )
std::cerr << "Exit: " << exit_message << std::endl;
exit_message.clear();
}
//----------------------------------------------------------------------
void FTerm::terminalSizeChange()
{
// Initialize a resize event to the root element
static auto& fterm_data = FTermData::getInstance();
fterm_data.setTermResized(true);
}
//----------------------------------------------------------------------
void FTerm::processTermination (int signum)
{
if ( internal::var::init_term_object )
internal::var::init_term_object->finish();
std::fflush (stderr);
std::fflush (stdout);
FStringStream msg{};
msg << "Program stopped: signal " << signum
<< " (" << strsignal(signum) << ")";
setExitMessage(msg.str());
printExitMessage();
std::terminate();
}
//----------------------------------------------------------------------
void FTerm::setSignalHandler()
{
signal(SIGTERM, FTerm::signal_handler); // Termination signal
signal(SIGQUIT, FTerm::signal_handler); // Quit from keyboard (Ctrl-\)
signal(SIGINT, FTerm::signal_handler); // Keyboard interrupt (Ctrl-C)
signal(SIGABRT, FTerm::signal_handler); // Abort signal from abort(3)
signal(SIGILL, FTerm::signal_handler); // Illegal Instruction
signal(SIGSEGV, FTerm::signal_handler); // Invalid memory reference
signal(SIGWINCH, FTerm::signal_handler); // Window resize signal
}
//----------------------------------------------------------------------
void FTerm::resetSignalHandler()
{
signal(SIGWINCH, SIG_DFL); // Window resize signal
signal(SIGSEGV, SIG_DFL); // Invalid memory reference
signal(SIGILL, SIG_DFL); // Illegal Instruction
signal(SIGABRT, SIG_DFL); // Abort signal from abort(3)
signal(SIGINT, SIG_DFL); // Keyboard interrupt (Ctrl-C)
signal(SIGQUIT, SIG_DFL); // Quit from keyboard (Ctrl-\)
signal(SIGTERM, SIG_DFL); // Termination signal
}
//----------------------------------------------------------------------
void FTerm::signal_handler (int sig_num)
{
switch ( sig_num )
{
case SIGWINCH:
terminalSizeChange();
break;
case SIGTERM:
case SIGQUIT:
case SIGINT:
case SIGABRT:
case SIGILL:
case SIGSEGV:
processTermination(sig_num);
default:
break; // Unknown signal handler number
}
}
} // namespace finalcut
|