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
|
/*=============================================================================
XMOTO
This file is part of XMOTO.
XMOTO is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
XMOTO 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with XMOTO; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
=============================================================================*/
#ifdef WIN32
#include <io.h>
#include <direct.h>
#include <windows.h>
#include <userenv.h>
#include <winbase.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#endif
#include <sys/stat.h>
#include <stdarg.h>
#include "helpers/VExcept.h"
#include "helpers/Log.h"
#include "helpers/Text.h"
#include "VFileIO.h"
#include "helpers/SwapEndian.h"
#include "md5sum/md5file.h"
#include "XMSession_default.h"
#include "UserConfig.h"
#ifdef WIN32
std::string win32_getHomeDir(bool i_asUtf8 = false) {
HANDLE hToken;
HANDLE proc;
std::string v_dest;
DWORD cchPath = 1024;
proc = GetCurrentProcess();
if(!OpenProcessToken(proc, TOKEN_QUERY, &hToken)) {
throw Exception("Can't determine user directory (OpenProcessToken)");
}
if(i_asUtf8) {
WCHAR szProfilePath[1024];
char v_tmp[1024];
if (!GetUserProfileDirectoryW( hToken, szProfilePath, &cchPath ) ) {
throw Exception("Can't determine user directory (GetUserProfileDirectory)");
}
WideCharToMultiByte(CP_UTF8, 0, szProfilePath, -1, v_tmp, 1024, NULL, NULL);
v_dest = v_tmp;
} else {
TCHAR szProfilePath[1024];
if (!GetUserProfileDirectory( hToken, szProfilePath, &cchPath ) ) {
throw Exception("Can't determine user directory (GetUserProfileDirectory)");
}
v_dest = szProfilePath;
}
return v_dest;
}
std::string win32_getPWDDir(bool i_asUtf8 = false) {
std::string v_dest;
int v_len;
if(i_asUtf8) {
WCHAR szProfilePath[1024];
char v_tmp[1024];
v_len = GetCurrentDirectoryW(1024, szProfilePath);
WideCharToMultiByte(CP_UTF8, 0, szProfilePath, -1, v_tmp, 1024, NULL, NULL);
v_dest = v_tmp;
} else {
TCHAR szProfilePath[1024];
v_len = GetCurrentDirectory(1024, szProfilePath);
v_dest = szProfilePath;
}
return v_dest;
}
#endif
std::string getPWDDir(bool i_asUtf8 = false) {
#ifdef WIN32
return win32_getPWDDir(i_asUtf8);
#else
return std::string(getenv("PWD"));
#endif
}
#if !defined(WIN32) && !defined(__MORPHOS__) && !defined(__amigaos4__)
void strlwr(char *pc) {
for(unsigned int i=0; i<strlen(pc); i++) pc[i] = tolower(pc[i]);
}
#endif
bool XMFS::m_isInitialized = false;
#ifndef WIN32
xdgHandle* XMFS::m_xdgHd = NULL;
#endif
bool str_match_wildcard(char *pcMWildcard,char *pcMString, bool CaseSensitive) {
int nPos=0;
bool PrevIsWildcard = false;
char c1[256],c2[256];
char *pcWildcard,*pcString;
if(CaseSensitive) {
pcWildcard=pcMWildcard;
pcString=pcMString;
} else {
strncpy(c1,pcMWildcard,sizeof(c1));
strncpy(c2,pcMString,sizeof(c2));
strlwr(c1); strlwr(c2);
pcWildcard=c1;
pcString=c2;
}
if(pcWildcard[0]=='\0') return true;
for(unsigned i=0; i<strlen(pcWildcard); i++) {
/* If end of string is reached, we have a match */
if(pcString[nPos] == '\0' && pcWildcard[i] == '\0')
return true;
/* Wildcard? */
if(pcWildcard[i] == '?' || pcWildcard[i] == '*')
PrevIsWildcard=true;
else {
/* Nope. What does we accept from the string? */
if(PrevIsWildcard) {
/* Read string until we get the right character */
while(1) {
if(pcString[nPos] == '\0')
return false;
/* Got the char? */
if(pcString[nPos] == pcWildcard[i])
break;
nPos++;
}
i--;
/* Clear wildcard flag */
PrevIsWildcard=false;
}
else {
/* The letter in the string MUST equal the letter in the wildcard */
if(pcWildcard[i] != pcString[nPos])
return false;
nPos++; /* Next */
}
}
}
/* Result of random debugging :) */
if(PrevIsWildcard || pcString[nPos]=='\0') return true;
/* Not a match */
return false;
}
void XMFS::_ThrowFileError(FileHandle *pfh,std::string Description) {
char cBuf[512];
snprintf(cBuf, 512, "%s (%s%s): %s", pfh->Name.c_str(),pfh->bRead?"I":"", pfh->bWrite?"O":"", Description.c_str());
throw Exception(cBuf);
}
std::string XMFS::getSystemDataDir() {
return m_SystemDataDir;
}
std::string XMFS::getUserDir(FileDataType i_fdt) {
switch(i_fdt) {
case FDT_DATA:
return m_UserDataDir;
break;
case FDT_CONFIG:
return m_UserConfigDir;
break;
case FDT_CACHE:
return m_UserCacheDir;
break;
}
return "";
}
std::string XMFS::getUserDirUTF8(FileDataType i_fdt) {
if(i_fdt != FDT_DATA) {
throw Exception("Allow only utf8 from user data directory");
}
return m_UserDataDirUTF8;
}
/*===========================================================================
Code soup :) -- this is largely copy/paste material from an earlier project
FutureRasmus: well, this is probably the crappiest code in the world. Period.
===========================================================================*/
void XMFS::_FindFilesRecursive(const std::string &DirX,const std::string &Wildcard,std::vector<std::string> &List) {
/* Windows? */
#ifdef WIN32
long fh;
struct _finddata_t fd;
std::string Dir = DirX;
if(!DirX.empty() && DirX[DirX.length()-1] == '/') {
Dir = DirX.substr(0,DirX.length()-1);
}
if((fh = _findfirst((Dir + std::string("/") + Wildcard).c_str(),&fd)) != -1L) {
do {
if(strcmp(fd.name,".") && strcmp(fd.name,"..")) {
List.push_back(Dir + std::string("/") + std::string(fd.name));
}
} while(_findnext(fh,&fd)==0);
_findclose(fh);
}
/* Now, recurse into sub-dirs */
if((fh = _findfirst( (Dir + std::string("/*")).c_str(),&fd)) != -1L) {
do {
if(strcmp(fd.name,".") && strcmp(fd.name,"..")) {
std::string F = Dir + std::string("/") + std::string(fd.name);
if(isDir(F)) {
/* Recurse! */
_FindFilesRecursive(F,Wildcard,List);
}
}
} while(_findnext(fh,&fd)==0);
_findclose(fh);
}
#else
std::string Dir = DirX;
struct dirent *dp;
DIR *dirp = opendir(Dir.c_str());
while(dirp) {
if((dp = readdir(dirp)) != NULL) {
std::string F = Dir + std::string(dp->d_name);
if(isDir(F)) {
/* Recurse... */
if(strcmp(dp->d_name,".") && strcmp(dp->d_name,"..")) {
_FindFilesRecursive(F + std::string("/"),Wildcard,List);
}
}
else {
if(str_match_wildcard((char *)Wildcard.c_str(),(char *)dp->d_name,true)) {
/* Match! */
if(strcmp(dp->d_name,".") && strcmp(dp->d_name,"..")) {
List.push_back(F);
}
}
}
}
else {
closedir(dirp);
break;
}
}
#endif
}
std::vector<std::string> XMFS::findPhysFiles(FileDataType i_fdt, std::string Files,bool bRecurse) {
std::vector<std::string> Result;
std::string Wildcard;
std::string DataDirToSearch,AltDirToSearch,UDirToSearch = "";
/* First seperate directory from wildcard */
int n = Files.find_last_of('/');
if(n<0) {
/* No directory specified */
DataDirToSearch = m_SystemDataDir;
AltDirToSearch = "";
Wildcard = Files;
}
else {
/* Seperate dir and wildcard */
DataDirToSearch = m_SystemDataDir + std::string("/") + Files.substr(0,n+1);
UDirToSearch = getUserDir(i_fdt) + std::string("/") + Files.substr(0,n+1);
AltDirToSearch = Files.substr(0,n+1);
Wildcard = Files.substr(n+1);
}
/* 1. find in user dir */
/* 2. find in data dir */
/* 3. find in package */
/* Windows? */
#ifdef WIN32
if(UDirToSearch != "") {
if(bRecurse) {
_FindFilesRecursive(UDirToSearch,Wildcard,Result);
} else {
long fh;
struct _finddata_t fd;
if((fh = _findfirst((UDirToSearch + Wildcard).c_str(),&fd)) != -1L) {
do {
if(strcmp(fd.name,".") && strcmp(fd.name,"..")) {
Result.push_back(UDirToSearch + std::string(fd.name));
}
} while(_findnext(fh,&fd)==0);
_findclose(fh);
}
}
}
if(i_fdt == FDT_DATA) {
if(bRecurse) {
_FindFilesRecursive(DataDirToSearch,Wildcard,Result);
} else {
long fh;
struct _finddata_t fd;
if((fh = _findfirst((DataDirToSearch + Wildcard).c_str(),&fd)) != -1L) {
do {
if(strcmp(fd.name,".") && strcmp(fd.name,"..")) {
Result.push_back(DataDirToSearch + std::string(fd.name));
}
} while(_findnext(fh,&fd)==0);
_findclose(fh);
}
}
}
#else /* Assume linux, unix... yalla yalla... */
if(UDirToSearch != "") {
if(bRecurse) {
_FindFilesRecursive(UDirToSearch,Wildcard,Result);
} else {
struct dirent *dp;
DIR *dirp = opendir(UDirToSearch.c_str());
while(dirp) {
if((dp = readdir(dirp)) != NULL) {
if(str_match_wildcard((char *)Wildcard.c_str(),(char *)dp->d_name,true)) {
/* Match! */
if(strcmp(dp->d_name,".") && strcmp(dp->d_name,"..")) {
Result.push_back(UDirToSearch + std::string(dp->d_name));
}
}
} else {
closedir(dirp);
break;
}
}
}
}
if(AltDirToSearch != UDirToSearch) {
if(bRecurse) {
_FindFilesRecursive(AltDirToSearch,Wildcard,Result);
} else {
struct dirent *dp;
DIR *dirp = opendir(AltDirToSearch.c_str());
while(dirp) {
if((dp = readdir(dirp)) != NULL) {
if(str_match_wildcard((char *)Wildcard.c_str(),(char *)dp->d_name,true)) {
/* Match! */
if(strcmp(dp->d_name,".") && strcmp(dp->d_name,"..")) {
Result.push_back(AltDirToSearch + std::string(dp->d_name));
}
}
} else {
closedir(dirp);
break;
}
}
}
}
if(i_fdt == FDT_DATA) {
if(DataDirToSearch != AltDirToSearch && DataDirToSearch != UDirToSearch) {
if(bRecurse) {
_FindFilesRecursive(DataDirToSearch,Wildcard,Result);
} else {
/* Search directories */
struct dirent *dp;
DIR *dirp = opendir(DataDirToSearch.c_str());
while(dirp) {
if((dp = readdir(dirp)) != NULL) {
if(str_match_wildcard((char *)Wildcard.c_str(),(char *)dp->d_name,true)) {
/* Match! */
if(strcmp(dp->d_name,".") && strcmp(dp->d_name,"..")) {
Result.push_back(DataDirToSearch + std::string(dp->d_name));
}
}
} else {
closedir(dirp);
break;
}
}
}
}
}
#endif
if(i_fdt == FDT_DATA) {
/* Look in package */
for(unsigned int i=0; i<m_PackFiles.size(); i++) {
/* Make sure about the directory... */
int k = Files.find_last_of('/');
std::string Ds1 = Files.substr(0,k+1);
k = m_PackFiles[i].Name.find_last_of('/');
std::string Ds2 = m_PackFiles[i].Name.substr(0,k+1);
if(Ds1.substr(0,2) == "./") Ds1.erase(Ds1.begin(),Ds1.begin()+2);
if(Ds1 == Ds2 && str_match_wildcard((char *)Files.c_str(),(char *)m_PackFiles[i].Name.c_str(),true)) {
/* Match. */
Result.push_back(m_PackFiles[i].Name);
}
}
}
/* Return file listing */
return Result;
}
FileHandle *XMFS::openOFile(FileDataType i_fdt, std::string Path) {
FileHandle *pfh = new FileHandle;
/* Is it an absolute path? */
if(isPathAbsolute(Path)) {
/* Yup, not much to do here then */
mkArborescence(Path);
pfh->fp = fopen(Path.c_str(),"wb");
}
else {
/* Nope, try the user dir */
mkArborescence(getUserDir(i_fdt) + std::string("/") + Path);
pfh->fp = fopen((getUserDir(i_fdt) + std::string("/") + Path).c_str(),"wb");
}
if(pfh->fp != NULL) {
pfh->Type = FHT_STDIO;
pfh->bWrite = true;
pfh->Name = Path;
return pfh;
}
delete pfh;
return NULL;
}
FileHandle *XMFS::openIFile(FileDataType i_fdt, std::string Path, bool i_includeCurrentDir) {
FileHandle *pfh = new FileHandle;
/* Okay. Absolute path? */
if(isPathAbsolute(Path)) {
/* Yes ma'am */
pfh->fp = fopen(Path.c_str(),"rb");
pfh->Type = FHT_STDIO;
} else {
/* user dir ? */
pfh->fp = fopen((getUserDir(i_fdt) + std::string("/") + Path).c_str(),"rb");
/* data dir ? */
if(i_fdt == FDT_DATA) {
if(pfh->fp == NULL) {
if(m_bGotSystemDataDir) {
pfh->fp = fopen((m_SystemDataDir + std::string("/") + Path).c_str(),"rb");
}
/* current working dir ? */
if(pfh->fp == NULL) {
if(i_includeCurrentDir) {
pfh->fp = fopen(Path.c_str(),"rb");
}
}
}
}
/* got something ? */
if(pfh->fp != NULL) {
pfh->Type = FHT_STDIO;
}
}
if(i_fdt == FDT_DATA) {
if(pfh->fp == NULL) {
int v_packsize = m_PackFiles.size();
// remove all ./ of the Path
std::string v_path = Path;
while(v_path.substr(0,2) == "./") {
v_path = v_path.substr(2, v_path.length() -2);
}
/* No luck so far, look in the data package */
for(unsigned int i=0; i<v_packsize; i++) {
if(m_PackFiles[i].Name == v_path) {
/* Found it, yeah. */
pfh->fp = fopen(m_BinDataFile.c_str(),"rb");
if(pfh->fp != NULL) {
fseek(pfh->fp,m_PackFiles[i].nOffset,SEEK_SET);
pfh->Type = FHT_PACKAGE;
pfh->nSize = m_PackFiles[i].nSize;
pfh->nOffset = ftell(pfh->fp);
// printf("OPENED '%s' IN PACKAGE!\n",Path.c_str());
}
else break;
}
}
}
}
if(pfh->fp == NULL) {
delete pfh;
return NULL;
}
pfh->bRead = true;
pfh->Name = Path;
if(pfh->Type == FHT_STDIO) {
fseek(pfh->fp,0,SEEK_END);
pfh->nSize = ftell(pfh->fp);
fseek(pfh->fp,0,SEEK_SET);
}
return pfh;
}
void XMFS::closeFile(FileHandle *pfh) {
if(pfh->Type == FHT_STDIO) {
fclose(pfh->fp);
}
else if(pfh->Type == FHT_PACKAGE) {
fclose(pfh->fp);
}
else _ThrowFileError(pfh,"closeFile -> invalid type");
delete pfh;
}
bool XMFS::readBuf(FileHandle *pfh,char *pcBuf, unsigned int nBufSize) {
if(!pfh->bRead) _ThrowFileError(pfh,"readBuf -> write-only");
if(pfh->Type == FHT_STDIO) {
if(fread(pcBuf,1,nBufSize,pfh->fp) != nBufSize) return false;
}
else if(pfh->Type == FHT_PACKAGE) {
int nRem = pfh->nSize - (ftell(pfh->fp) - pfh->nOffset);
// printf("reading %d bytes. %d left (%d %d %d).\n",nBufSize,nRem,pfh->nSize,ftell(pfh->fp),pfh->nOffset);
if(nBufSize == 0) return true;
if(nRem > 0) {
if(fread(pcBuf,1,nBufSize,pfh->fp) != nBufSize) return false;
}
else return false;
}
else _ThrowFileError(pfh,"readBuf -> invalid type");
return true;
}
bool XMFS::writeBuf(FileHandle *pfh, char *pcBuf, unsigned int nBufSize) {
if(!pfh->bWrite) _ThrowFileError(pfh,"writeBuf -> read-only");
if(pfh->Type == FHT_STDIO) {
if(fwrite(pcBuf,1,nBufSize,pfh->fp) != nBufSize) return false;
}
else _ThrowFileError(pfh,"writeBuf -> invalid type");
return true;
}
bool XMFS::setOffset(FileHandle *pfh,int nOffset) {
if(pfh->Type == FHT_STDIO) {
fseek(pfh->fp,nOffset,SEEK_SET);
}
else if(pfh->Type == FHT_PACKAGE) {
fseek(pfh->fp,nOffset + pfh->nOffset,SEEK_SET);
}
else _ThrowFileError(pfh,"setOffset -> invalid type");
return true; /* blahh, this is not right, but... */
}
bool XMFS::setEnd(FileHandle *pfh) {
if(pfh->Type == FHT_STDIO) {
fseek(pfh->fp,0,SEEK_END);
}
else if(pfh->Type == FHT_PACKAGE) {
fseek(pfh->fp,pfh->nSize + pfh->nOffset,SEEK_SET);
}
else _ThrowFileError(pfh,"setEnd -> invalid type");
return true; /* ... */
}
int XMFS::getOffset(FileHandle *pfh) {
int nOffset=0;
if(pfh->Type == FHT_STDIO) {
nOffset = ftell(pfh->fp);
}
else if(pfh->Type == FHT_PACKAGE) {
nOffset = ftell(pfh->fp) - pfh->nOffset;
}
else _ThrowFileError(pfh,"getOffset -> invalid type");
return nOffset;
}
int XMFS::getLength(FileHandle *pfh) {
return pfh->nSize;
}
bool XMFS::isEnd(FileHandle *pfh) {
bool bEnd = true;
if(pfh->Type == FHT_STDIO) {
if(!feof(pfh->fp)) bEnd = false;
}
else if(pfh->Type == FHT_PACKAGE) {
int nRem = pfh->nSize - (ftell(pfh->fp) - pfh->nOffset);
if(nRem > 0) bEnd = false;
}
else _ThrowFileError(pfh,"isEnd -> invalid type");
return bEnd;
}
std::string XMFS::readFileToEnd(FileHandle *pfh) {
std::string v_res;
char v_buffer[16384+1];
int v_remaining = getLength(pfh);
int v_toread;
v_res = "";
while(v_remaining > 0) {
v_toread = v_remaining > 16384 ? 16384 : v_remaining;
if(readBuf(pfh, v_buffer, v_toread) == false) {
_ThrowFileError(pfh,"readFileToEnd -> read failed");
}
v_buffer[v_toread] = '\0';
v_res += v_buffer;
v_remaining -= v_toread;
}
return v_res;
}
bool XMFS::readNextLine(FileHandle *pfh,std::string &Line) {
int c;
char b[2];
Line = "";
if(peekNextBufferedChar(pfh)==0) return false;
/* Read until the next new-line */
while(1) {
try {
c=readBufferedChar(pfh);
if(c==0) break;
if(c=='\r' || c=='\n') {
/* New-line... -- if \r and the next is \n OR if \n and the next is \r, then skip it
-- in this way we support all imaginable text file formats - almost ;) */
if((c=='\r' && peekNextBufferedChar(pfh)=='\n') ||
(c=='\n' && peekNextBufferedChar(pfh)=='\r')) {
readBufferedChar(pfh);
}
break;
}
/* Append char to line */
b[0] = c; b[1] = '\0'; /* not very c++-ish, i know :( */
Line.append(b);
}
catch(Exception e) {
return false;
}
}
return true;
}
int XMFS::readByte(FileHandle *pfh) {
signed char v;
if(!readBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"readByte -> failed");
return v;
}
int XMFS::readShort(FileHandle *pfh) {
short v;
if(!readBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"readShort -> failed");
return v;
}
int XMFS::readInt(FileHandle *pfh) {
int32_t nv;
if(!readBuf(pfh,(char *)&nv,sizeof(4))) _ThrowFileError(pfh,"readInt -> failed");
return static_cast<int>(nv);
}
float XMFS::readFloat(FileHandle *pfh) {
float v;
if(!readBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"readFloat -> failed");
return v;
}
double XMFS::readDouble(FileHandle *pfh) {
double v;
if(!readBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"readDouble -> failed");
return v;
}
std::string XMFS::readString(FileHandle *pfh) {
unsigned char v;
v=readByte(pfh);
char cBuf[256];
if(!readBuf(pfh,(char *)cBuf,v)) _ThrowFileError(pfh,"readString -> failed");
cBuf[v] = '\0';
return std::string(cBuf);
}
std::string XMFS::readLongString(FileHandle *pfh) {
unsigned short v;
v=readShort_LE(pfh);
char cBuf[65536];
if(!readBuf(pfh,(char *)cBuf,v)) _ThrowFileError(pfh,"readLongString -> failed");
cBuf[v] = '\0';
return std::string(cBuf);
}
// We use one-byte bools
bool XMFS::readBool(FileHandle *pfh) {
return static_cast<bool>(readByte(pfh));
}
void XMFS::writeByte(FileHandle *pfh,unsigned char v) {
if(!writeBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"writeByte -> failed");
}
void XMFS::writeShort(FileHandle *pfh,short v) {
if(!writeBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"writeShort -> failed");
}
void XMFS::writeInt(FileHandle *pfh,int v) {
int32_t nv;
nv = static_cast<int32_t>(v);
if(!writeBuf(pfh,(char *)&nv, 4)) _ThrowFileError(pfh,"writeInt -> failed");
}
void XMFS::writeFloat(FileHandle *pfh,float v) {
if(!writeBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"writeFloat -> failed");
}
void XMFS::writeDouble(FileHandle *pfh,double v) {
if(!writeBuf(pfh,(char *)&v,sizeof(v))) _ThrowFileError(pfh,"writeDouble -> failed");
}
void XMFS::writeString(FileHandle *pfh,std::string v) {
writeByte(pfh,v.length());
if(!writeBuf(pfh,(char *)v.c_str(),v.length())) _ThrowFileError(pfh,"writeString -> failed");
}
void XMFS::writeLongString(FileHandle *pfh,std::string v) {
writeShort_LE(pfh,v.length());
if(!writeBuf(pfh,(char *)v.c_str(),v.length())) _ThrowFileError(pfh,"writeLongString -> failed");
}
void XMFS::writeBool(FileHandle *pfh,bool v) {
writeByte(pfh,static_cast<unsigned char>(v));
}
void XMFS::writeLine(FileHandle *pfh,std::string Line) {
char cBuf[2048];
snprintf(cBuf, 2048, "%s\n", Line.c_str());
if(!writeBuf(pfh,cBuf,strlen(cBuf))) _ThrowFileError(pfh,"writeLine -> failed");
}
void XMFS::writeLineF(FileHandle *pfh,char *pcFmt,...) {
char cBuf[2048],cBuf2[2048];
va_list List;
va_start(List,pcFmt);
vsnprintf(cBuf, 2048, pcFmt, List);
va_end(List);
snprintf(cBuf2, 2048, "%s\n", cBuf);
if(!writeBuf(pfh,cBuf2,strlen(cBuf2))) _ThrowFileError(pfh,"writeLineF -> failed");
}
/* For buffered reading: */
int XMFS::readBufferedChar(FileHandle *pfh) {
/* Need to buffer? */
if(pfh->nWrite==pfh->nRead)
if(fillBuffer(pfh) == 0) return 0; /* end-of-file */
/* Read buffer */
int c=pfh->cBuffer[pfh->nRead];
pfh->nRead++;
if(pfh->nRead >= 256) pfh->nRead=0;
/* Return */
return c;
}
int XMFS::peekNextBufferedChar(FileHandle *pfh) {
/* Need to buffer? */
if(pfh->nWrite==pfh->nRead)
if(fillBuffer(pfh) == 0) return 0; /* end-of-file */
/* Read buffer, but don't increment index */
int c=pfh->cBuffer[pfh->nRead];
/* Return */
return c;
}
int XMFS::fillBuffer(FileHandle *pfh) {
int nRemaining = getLength(pfh) - getOffset(pfh);
int nBytes = nRemaining < 256/2 ? nRemaining : 256/2;
int r = nBytes,t;
/* Fill half of the buffer */
while(r>0) {
t=(256 - pfh->nWrite) > r ? r : (256 - pfh->nWrite);
if(!readBuf(pfh,&pfh->cBuffer[pfh->nWrite],t)) _ThrowFileError(pfh,"fillBuffer -> read failed");
pfh->nWrite+=t;
if(pfh->nWrite==256) pfh->nWrite=0;
r-=t;
}
/* Return number of bytes read */
return nBytes;
}
/*===========================================================================
Extract directory name from path
===========================================================================*/
std::string XMFS::getFileDir(std::string Path) {
int n = Path.find_last_of("/");
if(n<0) n = Path.find_last_of("\\");
if(n<0) {
/* No directory info */
return std::string(".");
}
std::string v_fileDir = Path.substr(0,n);
if(v_fileDir == "") {
v_fileDir = "/";
}
return v_fileDir;
}
/*===========================================================================
Extract file name (with no extension) from path
===========================================================================*/
std::string XMFS::getFileBaseName(std::string Path) {
int n = Path.find_last_of("/");
if(n<0) n = Path.find_last_of("\\");
std::string FName;
if(n>=0) {
FName = Path.substr(n+1,Path.length()-n-1);
}
else {
FName = Path;
}
n = FName.find_last_of(".");
if(n<0) return FName;
return FName.substr(0,n);
}
std::string XMFS::getFileExtension(std::string Path) {
int n;
n = Path.find_last_of(".");
if(n<0) return "";
return Path.substr(n+1, Path.length() - n - 1);
}
/*===========================================================================
Find out how old this file thing is... (physical file system only)
===========================================================================*/
int XMFS::getFileTimeStamp(const std::string &Path) {
struct stat S;
if(stat(Path.c_str(),&S)) {
return 0;
}
return (int)S.st_mtime; /* no we don't care about exact value */
}
/*===========================================================================
Is that a dir or what? - and similar stuffin'
===========================================================================*/
bool XMFS::isDir(std::string Path) {
struct stat S;
if(stat(Path.c_str(),&S)) {
return false;
}
if(S.st_mode & S_IFDIR) return true; /* it is a directory */
return false; /* not a directory */
}
bool XMFS::isPathAbsolute(std::string Path) {
/* Windows? */
#ifdef WIN32
/* Check for drive letter */
if(Path.length() >= 3) {
if(isalpha(Path.at(0)) && Path.at(1)==':' && (Path.at(2)=='\\' || Path.at(2)=='/'))
return true;
}
#endif
/* Otherwise simply look for leading slash/backslash */
if(Path.length() >= 1) {
if(Path.at(0) == '\\' || Path.at(0) == '/') return true;
}
/* Not absolute */
return false;
}
/*===========================================================================
Delete file
===========================================================================*/
void XMFS::deleteFile(FileDataType i_fdt, const std::string &File) {
std::string FullFile;
if(getUserDir(i_fdt) == "") {
throw Exception("Unable to delete the file " + File);
}
/* Absolute file path? */
if(isPathAbsolute(File)) {
/* Yeah, check if file is in user directory - otherwise we won't delete it */
if(File.length() < getUserDir(i_fdt).length() || File.substr(0, getUserDir(i_fdt).length()) != getUserDir(i_fdt)) {
throw Exception("Unable to delete the file " + File);
}
FullFile = File;
} else {
/* We can only delete user files */
FullFile = getUserDir(i_fdt) + std::string("/") + File;
}
if(remove(FullFile.c_str())) {
throw Exception("Unable to delete the file " + File);
}
}
/*===========================================================================
Copy file
===========================================================================*/
bool XMFS::copyFile(FileDataType i_fdt, const std::string &From,const std::string &To, std::string &To_really_done) {
/* All file copying must happen inside the user directory... */
if(getUserDir(i_fdt) == "") {
LogWarning("No user directory, can't copy file '%s' to '%s'",From.c_str(),To.c_str());
return false;
}
std::string FullFrom = getUserDir(i_fdt) + std::string("/") + From;
std::string FullTo = getUserDir(i_fdt) + std::string("/") + To;
/* Does the destination file already exist? */
FILE *fp = fopen(FullTo.c_str(),"rb");
if(fp != NULL) {
fclose(fp);
/* Yup, modify its name - strip extension */
int k = FullTo.find_last_of(".");
std::string FullToExt,FullToBaseName;
if(k>=0) {
FullToBaseName = FullTo.substr(0,k);
FullToExt = FullTo.substr(k);
}
else {
FullToBaseName = FullTo;
FullToExt = "";
}
int i = 1;
while(1) {
char cTemp[1024];
snprintf(cTemp, 1024, "%s (%d)%s", FullToBaseName.c_str(), i, FullToExt.c_str());
/* What about this file then? */
fp = fopen(cTemp,"rb");
if(fp == NULL) {
/* Good one */
FullTo = cTemp;
break;
} else {
fclose(fp);
i++;
}
/* Next */
}
}
/* Open files and copy */
FILE *in = fopen(FullFrom.c_str(),"rb");
if(in != NULL) {
FILE *out = fopen(FullTo.c_str(),"wb");
if(out != NULL) {
To_really_done = FullTo;
/* Get input file size */
fseek(in,0,SEEK_END);
int nFileSize = ftell(in);
fseek(in,0,SEEK_SET);
int nTotalWritten = 0;
/* Good, start copying */
while(!feof(in)) {
char cBuf[8192];
int nRead = fread(cBuf,1,sizeof(cBuf),in);
if(nRead > 0) {
int nWritten = fwrite(cBuf,1,nRead,out);
if(nWritten > 0) {
nTotalWritten += nWritten;
}
}
else break;
}
/* Did we copy everything? */
if(nTotalWritten != nFileSize) {
/* Nope, clean up the mess and bail out */
fclose(in);
fclose(out);
remove(FullTo.c_str());
LogWarning("Failed to copy all of '%s' to '%s'",FullFrom.c_str(),FullTo.c_str());
return false;
}
fclose(out);
}
else {
fclose(in);
LogWarning("Failed to open file for output: %s",FullTo.c_str());
return false;
}
fclose(in);
}
else {
LogWarning("Failed to open file for input: %s",FullFrom.c_str());
return false;
}
/* OK */
return true;
}
bool XMFS::renameUserFile(const std::string &From,const std::string &To) {
return rename(From.c_str(), To.c_str()) == 0;
}
/*===========================================================================
Initialize file system fun
===========================================================================*/
std::string XMFS::m_UserDataDir ="";
std::string XMFS::m_UserConfigDir ="";
std::string XMFS::m_UserCacheDir ="";
std::string XMFS::m_UserDataDirUTF8 ="";
std::string XMFS::m_SystemDataDir = ""; /* Globals */
bool XMFS::m_bGotSystemDataDir;
std::string XMFS::m_BinDataFile = "";
std::string XMFS::m_binCheckSum = "";
std::vector<PackFile> XMFS::m_PackFiles;
void XMFS::init(const std::string& AppDir, const std::string& i_binFile, const std::string& i_logFile, bool i_graphics, const std::string& i_userCustomDirPath) {
m_bGotSystemDataDir = false;
m_UserDataDir = "";
m_UserConfigDir = "";
m_UserCacheDir = "";
m_UserDataDirUTF8 = "";
m_SystemDataDir = "";
std::string v_mod_userCustomDirPath = i_userCustomDirPath;
std::string v_mod_userCustomDirPathUtf8 = i_userCustomDirPath; // the argument must be utf8 -- so it can not work on windows for example
// make v_mod_userCustomDirPath absolute
if(v_mod_userCustomDirPath != "") {
if(isPathAbsolute(v_mod_userCustomDirPath) == false) {
v_mod_userCustomDirPath = getPWDDir() + "/" + v_mod_userCustomDirPath;
v_mod_userCustomDirPathUtf8 = getPWDDir(true) + "/" + v_mod_userCustomDirPathUtf8;
if(isPathAbsolute(v_mod_userCustomDirPath) == false) {
throw Exception("Custom directory must be absolute");
}
}
}
#ifndef WIN32
// xdg
if( (m_xdgHd = (xdgHandle*) malloc(sizeof(xdgHandle))) == NULL) {
throw Exception("xdgbasedir allocation failed");
}
if( (xdgInitHandle(m_xdgHd)) == 0) {
throw Exception("xdgbasedir initialisation failed");
}
#endif
#if defined(WIN32) /* Windoze... */
char cModulePath[256];
int i=GetModuleFileName(GetModuleHandle(NULL),cModulePath,sizeof(cModulePath)-1);
cModulePath[i]='\0';
for(i=strlen(cModulePath)-1;i>=0;i--) {
if(cModulePath[i] == '/' || cModulePath[i] == '\\') {
cModulePath[i] = '\0';
break;
}
}
/* Valid path? */
if(isDir(cModulePath)) {
/* Alright, use this dir */
if(v_mod_userCustomDirPath != "") {
m_UserDataDir = v_mod_userCustomDirPath;
m_UserDataDirUTF8 = v_mod_userCustomDirPathUtf8;
m_UserConfigDir = v_mod_userCustomDirPath;
m_UserCacheDir = v_mod_userCustomDirPath;
} else {
/* not used even if it works because i'm not sure it returns utf-8 chars, required for sqlite_open
//m_UserDataDir = xdgDataHome(m_xdgHd) + std::string("/") + AppDir;
//m_UserConfigDir = xdgConfigHome(m_xdgHd) + std::string("/") + AppDir;
//m_UserCacheDir = xdgCacheHome(m_xdgHd) + std::string("/") + AppDir;
*/
m_UserDataDir = win32_getHomeDir() + std::string("/.local/share/") + AppDir;
m_UserConfigDir = win32_getHomeDir() + std::string("/.config/") + AppDir;
m_UserCacheDir = win32_getHomeDir() + std::string("/.cache/") + AppDir;
m_UserDataDirUTF8 = win32_getHomeDir(true) + std::string("/.local/share/") + AppDir;
}
m_SystemDataDir = cModulePath;
m_bGotSystemDataDir = true;
}
else throw Exception("invalid process directory");
#elif defined(__MORPHOS__) || defined(__amigaos4__)
if(v_mod_userCustomDirPath != "") {
m_UserDataDir = v_mod_userCustomDirPath;
m_UserDataDirUTF8 = v_mod_userCustomDirPathUtf8;
m_UserConfigDir = v_mod_userCustomDirPath;
m_UserCacheDir = v_mod_userCustomDirPath;
} else {
m_UserDataDir = "PROGDIR:userdata"; /*getenv("HOME");*/
if(!isDir(m_UserDataDir))
throw Exception("invalid user home directory");
m_UserConfigDir = m_UserDataDir;
m_UserCacheDir = m_UserDataDir;
m_UserDataDirUTF8 = m_UserDataDir;
}
/* And the data dir? */
m_SystemDataDir = std::string("PROGDIR:data");
if(isDir(m_SystemDataDir)) {
/* Got a system-wide installation to fall back to! */
m_bGotSystemDataDir = true;
}
#else /* Assume unix-like */
/* Determine users home dir, so we can find out where to get/save user
files */
if(v_mod_userCustomDirPath != "") {
m_UserDataDir = v_mod_userCustomDirPath;
m_UserDataDirUTF8 = v_mod_userCustomDirPathUtf8;
m_UserConfigDir = v_mod_userCustomDirPath;
m_UserCacheDir = v_mod_userCustomDirPath;
} else {
m_UserDataDir = xdgDataHome(m_xdgHd) + std::string("/") + AppDir;
m_UserConfigDir = xdgConfigHome(m_xdgHd) + std::string("/") + AppDir;
m_UserCacheDir = xdgCacheHome(m_xdgHd) + std::string("/") + AppDir;
m_UserDataDirUTF8 = m_UserDataDir;
}
/* And the data dir? */
m_SystemDataDir = std::string(GAMEDATADIR);
if(isDir(m_SystemDataDir)) {
/* Got a system-wide installation to fall back to! */
m_bGotSystemDataDir = true;
}
#endif
bool v_requireMigration = false;
/* If user-dir isn't there, try making it */
if(isDir(m_UserDataDir) == false) {
mkArborescenceDir(m_UserDataDir);
/*
if the user data directory, it's the first time it is used, try to migrate old data
*/
v_requireMigration = true;
}
if(isDir(m_UserConfigDir) == false) {
mkArborescenceDir(m_UserConfigDir);
}
if(isDir(m_UserCacheDir) == false) {
mkArborescenceDir(m_UserCacheDir);
}
/* Delete old log */
remove( (m_UserCacheDir + "/" + i_logFile).c_str() );
/* Info */
if(m_bGotSystemDataDir) {
m_BinDataFile = m_SystemDataDir + "/" + i_binFile;
}
/* Initialize binary data package if any */
FILE *fp = fopen(m_BinDataFile.c_str(),"rb");
if(fp == NULL) {
throw Exception("Package " + i_binFile + " not found !");
}
char cBuf[256];
char md5sum[256];
fread(cBuf,4,1,fp);
if(!strncmp(cBuf,"XBI3",4)) {
int nNameLen;
int md5sumLen;
PackFile v_packFile;
size_t v_extension_place;
std::string v_extension;
/* get bin checksum of the package.list */
md5sumLen = fgetc(fp);
fread(md5sum,md5sumLen,1,fp);
md5sum[md5sumLen] = '\0';
m_binCheckSum = md5sum;
while((nNameLen=fgetc(fp)) >= 0) {
// printf("%d \n",nNameLen);
/* Read file name */
fread(cBuf,nNameLen,1,fp);
cBuf[nNameLen] = '\0';
md5sumLen = fgetc(fp);
fread(md5sum,md5sumLen,1,fp);
md5sum[md5sumLen] = '\0';
// printf(" %s\n",cBuf);
/* Read file size */
int nSize;
/* Patch by Michel Daenzer (applied 2005-10-25) */
unsigned char nSizeBuf[4];
fread(nSizeBuf,4,1,fp);
nSize = nSizeBuf[0] | nSizeBuf[1] << 8 | nSizeBuf[2] << 16 | nSizeBuf[3] << 24;
v_packFile.Name = cBuf;
v_extension = "";
v_extension_place = v_packFile.Name.rfind(".");
if(v_extension_place != std::string::npos) {
v_extension = v_packFile.Name.substr(v_extension_place+1);
}
// don't add unusefull graphics files
if(i_graphics ||
(
v_extension != "png" && // picture
v_extension != "jpg" && // picture
v_extension != "frag" && // graphical card files
v_extension != "vert" && // graphical card files
v_extension != "ogg" && // music
v_extension != "wav" // sound
)) {
v_packFile.md5sum = md5sum;
v_packFile.nOffset = ftell(fp);
v_packFile.nSize = nSize;
m_PackFiles.push_back(v_packFile);
}
fseek(fp,nSize,SEEK_CUR);
}
} else {
throw Exception("Invalid binary data package format");
}
fclose(fp);
m_isInitialized = true;
/* migrate old files if required */
if(v_requireMigration) {
/*
migrating from $HOME/.xmoto to xdg directories if necessary
*/
migrateFSToXdgBaseDirIfRequired(AppDir);
}
/* create base directories if missing -- do it after migration of old files while on windows, you cannot do the move without removing the directory */
if(isDir(getUserReplaysDir()) == false) {
mkArborescenceDir(getUserReplaysDir());
}
if(isDir(m_UserCacheDir + std::string("/LCache")) == false) {
mkArborescenceDir(m_UserCacheDir + std::string("/LCache"));
}
if(isDir(getUserLevelsDir()) == false) {
mkArborescenceDir(getUserLevelsDir());
}
}
void XMFS::uninit() {
#ifndef WIN32
if(m_xdgHd != NULL) {
xdgWipeHandle(m_xdgHd);
free(m_xdgHd);
}
#endif
m_isInitialized = false;
}
bool XMFS::isInitialized() {
return m_isInitialized;
}
/*===========================================================================
Hmm, for some reason I have to do this. Don't ask me why.
===========================================================================*/
int XMFS::mkDir(const char *pcPath) {
#if defined(WIN32)
return _mkdir(pcPath);
#else
return mkdir(pcPath,S_IRUSR|S_IWUSR|S_IRWXU);
#endif
}
std::string XMFS::binCheckSum() {
return XMFS::m_binCheckSum;
}
/*===========================================================================
Endian-safe I/O helpers
===========================================================================*/
void XMFS::writeShort_LE(FileHandle *pfh,short v) {
writeShort(pfh, SwapEndian::LittleShort(v));
}
void XMFS::writeInt_LE(FileHandle *pfh,int v) {
writeInt(pfh, SwapEndian::LittleLong(v));
}
void XMFS::writeFloat_LE(FileHandle *pfh,float v) {
writeFloat(pfh, SwapEndian::LittleFloat(v));
}
int XMFS::readShort_LE(FileHandle *pfh) {
short v = readShort(pfh);
return SwapEndian::LittleShort(v);
}
int XMFS::readInt_LE(FileHandle *pfh) {
int v = readInt(pfh);
return SwapEndian::LittleLong(v);
}
float XMFS::readFloat_LE(FileHandle *pfh) {
float v = readFloat(pfh);
return SwapEndian::LittleFloat(v);
}
int XMFS::readShort_MaybeLE(FileHandle *pfh, bool big) {
short v = readShort(pfh);
return big ? SwapEndian::BigShort(v) : SwapEndian::LittleShort(v);
}
int XMFS::readInt_MaybeLE(FileHandle *pfh, bool big) {
int v = readInt(pfh);
return big ? SwapEndian::BigLong(v) : SwapEndian::LittleLong(v);
}
float XMFS::readFloat_MaybeLE(FileHandle *pfh, bool big) {
float v = readFloat(pfh);
return big ? SwapEndian::BigFloat(v) : SwapEndian::LittleFloat(v);
}
bool XMFS::isFileInDir(std::string p_dirpath, std::string p_filepath) {
std::string v_fileDir;
v_fileDir = getFileDir(p_filepath);
if(p_dirpath.length() > v_fileDir.length()) {
return false;
}
return v_fileDir.substr(0, p_dirpath.length()) == p_dirpath;
}
bool XMFS::isInUserDir(FileDataType i_fdt, std::string p_filepath) {
return isFileInDir(getUserDir(i_fdt), p_filepath);
}
bool XMFS::doesRealFileOrDirectoryExists(std::string p_path) {
struct stat S;
return stat(p_path.c_str(), &S) == 0;
}
bool XMFS::isFileReadable(FileDataType i_fdt, std::string p_filename) {
FileHandle *fh = openIFile(i_fdt, p_filename);
if(fh == NULL) {
return false;
}
closeFile(fh);
return true;
}
bool XMFS::fileExists(FileDataType i_fdt, std::string p_filename) {
return isFileReadable(i_fdt, p_filename);
}
void XMFS::mkArborescence(std::string v_filepath) {
std::string v_parentDir = getFileDir(v_filepath);
if(doesRealFileOrDirectoryExists(v_parentDir)) {
return;
}
mkArborescence(v_parentDir);
if(XMFS::mkDir(v_parentDir.c_str()) != 0) {
throw Exception("Can't create directory " + v_parentDir);
}
}
void XMFS::mkArborescenceDir(std::string v_dirpath) {
mkArborescence(v_dirpath + "/file.tmp");
}
std::string XMFS::md5sum(FileDataType i_fdt, std::string i_filePath) {
i_filePath = FullPath(i_fdt, i_filePath);
/* is it a file from the pack or a real file ? */
if(XMFS::isFileReal(i_filePath)) {
return md5file(i_filePath);
}
if(i_fdt == FDT_DATA) {
/* package */
for(unsigned int i=0; i<m_PackFiles.size(); i++) {
if(m_PackFiles[i].Name == i_filePath ||
(std::string("./") + m_PackFiles[i].Name) == i_filePath) {
/* Found it, yeah. */
//printf("md5sum(%s) = %s\n", m_PackFiles[i].Name.c_str(), m_PackFiles[i].md5sum.c_str());
return m_PackFiles[i].md5sum;
}
}
}
return "";
}
bool XMFS::isFileReal(std::string i_filePath) {
FILE *fp;
fp = fopen(i_filePath.c_str(), "rb");
if(fp == NULL) {
return false;
}
fclose(fp);
return true;
}
std::string XMFS::FullPath(FileDataType i_fdt, const std::string& i_relative_path) {
if(fileExists(i_fdt, getUserDir(i_fdt) + std::string("/") + i_relative_path)) {
return getUserDir(i_fdt) + std::string("/") + i_relative_path;
}
if(i_fdt == FDT_DATA) {
if(fileExists(i_fdt, m_SystemDataDir + std::string("/") + i_relative_path)) {
return m_SystemDataDir + std::string("/") + i_relative_path;
}
}
return i_relative_path;
}
bool XMFS::areSamePath(const std::string& i_path1, const std::string& i_path2) {
#ifdef WIN32
return txtToLower(i_path1) == txtToLower(i_path2);
#else
return i_path1 == i_path2;
#endif
}
void XMFS::migrateFSToXdgBaseDirFile(const std::string& i_src, const std::string& i_dest) {
if(doesRealFileOrDirectoryExists(i_src) == false) {
return;
}
// write in log information about the migration
printf("Migrate file '%s' to '%s'\n", i_src.c_str(), i_dest.c_str());
// create the directory if required
mkArborescence(i_dest);
// move the file
if(renameUserFile(i_src, i_dest) == false) {
throw Exception("Unable to migrate the file " + i_src + " to " + i_dest);
}
}
void XMFS::migrateFSToXdgBaseDirIfRequired(const std::string& AppDir) {
std::string v_oldUserDir;
#ifndef WIN32
v_oldUserDir = getenv("HOME") + std::string("/.") + AppDir;
#else
v_oldUserDir = win32_getHomeDir() + std::string("/.") + AppDir;
#endif
if(isDir(v_oldUserDir) == false) {
// no need to do the conversion
return;
}
try {
migrateFSToXdgBaseDirFile(v_oldUserDir + "/xm.db", DATABASE_FILE);
migrateFSToXdgBaseDirFile(v_oldUserDir + "/config.dat", XMFS::getUserDir(FDT_CONFIG) + "/" + std::string(XM_CONFIGFILE));
migrateFSToXdgBaseDirFile(v_oldUserDir + "/players.bin", XMFS::getUserDir(FDT_DATA) + "/players.bin");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/favoriteLevels.xml", XMFS::getUserDir(FDT_DATA) + "/favoriteLevels.xml");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/stats.xml", XMFS::getUserDir(FDT_DATA) + "/stats.xml");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/LCache", XMFS::getUserDir(FDT_CACHE) + "/LCache");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/Levels", XMFS::getUserDir(FDT_DATA) + "/Levels");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/Replays", XMFS::getUserDir(FDT_DATA) + "/Replays");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/Screenshots", XMFS::getUserDir(FDT_DATA) + "/Screenshots");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/Textures", XMFS::getUserDir(FDT_DATA) + "/Textures");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/Themes", XMFS::getUserDir(FDT_DATA) + "/Themes");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/Physics", XMFS::getUserDir(FDT_DATA) + "/Physics");
migrateFSToXdgBaseDirFile(v_oldUserDir + "/Shaders", XMFS::getUserDir(FDT_DATA) + "/Shaders");
} catch(Exception &e) {
throw Exception("Unable move files for migration : " + e.getMsg());
}
}
void XMFS::deleteFile(const std::string& i_filepath) {
if(remove(i_filepath.c_str()) != 0) {
throw Exception("cannot remove file " + i_filepath);
}
}
|