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
|
/*
* This file is part of the Code::Blocks IDE and licensed under the GNU Lesser General Public License, version 3
* http://www.gnu.org/licenses/lgpl-3.0.html
*
* $Revision: 13575 $
* $Id: configmanager.cpp 13575 2024-09-30 06:50:24Z ollydbg $
* $HeadURL: https://svn.code.sf.net/p/codeblocks/code/branches/release-25.03/src/sdk/configmanager.cpp $
*/
#include "sdk_precomp.h"
#ifndef CB_PRECOMP
#include "configmanager.h"
#include "globals.h"
#include "personalitymanager.h"
#include "cbexception.h"
#include "logmanager.h"
#include <wx/file.h>
#include <wx/dir.h>
#include <wx/log.h> // for wxSafeShowMessage()
#endif
#include "crc32.h"
#include <wx/url.h>
#include <wx/stream.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#ifdef __WXMSW__
#include <shlobj.h>
#endif
#include "annoyingdialog.h"
#if defined(__APPLE__) && defined(__MACH__)
#include <sys/param.h>
#include <mach-o/dyld.h>
#endif
#ifdef __WXMAC__
#include "wx/osx/core/cfstring.h"
#include "wx/intl.h"
#include <CoreFoundation/CFBundle.h>
#include <CoreFoundation/CFURL.h>
#endif
#include "tinywxuni.h"
#include <stdlib.h>
#ifdef __linux__
#include <glib.h>
#endif // __linux__
template<> CfgMgrBldr* DLLIMPORT Mgr<CfgMgrBldr>::instance = nullptr;
template<> bool DLLIMPORT Mgr<CfgMgrBldr>::isShutdown = false;
wxString ConfigManager::alternate_user_data_path;
bool ConfigManager::has_alternate_user_data_path=false;
wxString ConfigManager::config_folder;
wxString ConfigManager::home_folder;
wxString ConfigManager::data_path_user;
wxString ConfigManager::data_path_global;
#ifdef CB_AUTOCONF
wxString ConfigManager::plugin_path_global;
#endif
wxString ConfigManager::app_path;
wxString ConfigManager::temp_folder;
namespace CfgMgrConsts
{
const wxString app_path(_T("app_path"));
const wxString data_path(_T("data_path"));
const wxString dotDot(_T(".."));
const int version = 1;
}
namespace
{
wxString DetermineExecutablePath()
{
#ifdef __WXMSW__
wxChar name[MAX_PATH];
GetModuleFileName(0L, name, MAX_PATH);
wxFileName fname(name);
return fname.GetPath(wxPATH_GET_VOLUME);
#else
#ifdef __linux__
char c[PATH_MAX+1];
char *p = realpath("/proc/self/exe", &c[0]);
if (p == nullptr)
return _T(".");
wxFileName fname(cbC2U(p));
return fname.GetPath(wxPATH_GET_VOLUME);
#elif defined(sun) || defined(__sun)
wxFileName fname(cbC2U(getexecname()));
return fname.GetPath(wxPATH_GET_VOLUME);
#elif defined(__APPLE__) && defined(__MACH__)
char path[MAXPATHLEN+1];
uint32_t path_len = MAXPATHLEN;
// SPI first appeared in Mac OS X 10.2
_NSGetExecutablePath(path, &path_len);
wxFileName fname(wxString(path, wxConvUTF8));
return fname.GetPath(wxPATH_GET_VOLUME);
#else
return _T(".");
#endif
#endif
}
wxString DetermineResourcesPath()
{
#if defined(__WXMAC__)
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
CFURLRef absoluteURL = CFURLCopyAbsoluteURL(resourcesURL); // relative -> absolute
CFRelease(resourcesURL);
CFStringRef cfStrPath = CFURLCopyFileSystemPath(absoluteURL,kCFURLPOSIXPathStyle);
CFRelease(absoluteURL);
wxString str = wxCFStringRef(cfStrPath).AsString(wxLocale::GetSystemEncoding());
if (!str.Contains(wxString(_T("/Resources"))))
return ::DetermineExecutablePath() + _T("/.."); // not a bundle, use relative path
return str;
#else
return _T(".");
#endif
}
}
inline void ConfigManager::Collapse(wxString& str) const
{
const wxChar *src = str.c_str();
wxChar *dst = (wxChar*) src;
wxChar c;
size_t len = 0;
while ((c = *src))
{
++src;
*dst = c;
++dst;
++len;
if (c == _T('/'))
while (*src == _T('/'))
++src;
}
str.Truncate(len);
}
ISerializable::ISerializable()
{}
ISerializable::~ISerializable()
{}
/* ------------------------------------------------------------------------------------------------------------------
* "Builder pattern" class for ConfigManager
* Do not use this class - Manager::Get()->GetConfigManager() is a lot friendlier
*/
CfgMgrBldr::CfgMgrBldr() : doc(nullptr), volatile_doc(nullptr), r(false)
{
ConfigManager::MigrateFolders();
TiXmlBase::SetCondenseWhiteSpace(false);
wxString personality(Manager::Get()->GetPersonalityManager()->GetPersonality());
if (personality.StartsWith(_T("http://")))
{
SwitchToR(personality);
return;
}
cfg = FindConfigFile(personality + _T(".conf"));
if (cfg.IsEmpty())
{
cfg = ConfigManager::GetConfigFolder() + wxFILE_SEP_PATH + personality + _T(".conf");
doc = new TiXmlDocument();
doc->InsertEndChild(TiXmlDeclaration("1.0", "UTF-8", "yes"));
doc->InsertEndChild(TiXmlElement("CodeBlocksConfig"));
doc->FirstChildElement("CodeBlocksConfig")->SetAttribute("version", CfgMgrConsts::version);
return;
}
SwitchTo(cfg);
}
wxString CfgMgrBldr::FindConfigFile(const wxString& filename)
{
wxString u(ConfigManager::GetUserDataFolder() + wxFILE_SEP_PATH + filename);
wxString exePath(::DetermineExecutablePath());
wxString e(exePath + wxFILE_SEP_PATH + filename);
if (!ConfigManager::has_alternate_user_data_path && ::wxFileExists(e))
{
ConfigManager::SetUserDataFolder(exePath);
return e;
}
if (::wxFileExists(u))
{
return u;
}
return wxEmptyString;
}
/// Print error message and allow the user to either discard the old config or close the application.
/// Call this function when you've detected an error while reading the config.
static void handleConfigError(TiXmlDocument &doc, const wxString &fileName, const wxString &additionalMessage)
{
wxString message;
if (doc.ErrorId())
{
message = wxString::Format(_("TinyXML error: %s\nIn file: %s\nAt row %d, column: %d.\n\n"),
cbC2U(doc.ErrorDesc()).c_str(), fileName.wx_str(),
doc.ErrorRow(), doc.ErrorCol());
}
message += additionalMessage;
// Show a message box and ask the user to either abort or discard the old config.
wxMessageDialog dlg(Manager::Get()->GetAppWindow(),
message + _("\n\nDiscard old config file?"), _("Config file read error"),
wxSTAY_ON_TOP|wxCENTRE|wxYES|wxNO|wxNO_DEFAULT|wxICON_ERROR);
dlg.SetYesNoLabels(_("&Discard"), _("&Close"));
if (dlg.ShowModal() != wxID_YES)
cbThrow(message);
doc.ClearError();
doc.InsertEndChild(TiXmlDeclaration("1.0", "UTF-8", "yes"));
doc.InsertEndChild(TiXmlElement("CodeBlocksConfig"));
doc.FirstChildElement("CodeBlocksConfig")->SetAttribute("version", CfgMgrConsts::version);
}
void CfgMgrBldr::SwitchTo(const wxString& fileName)
{
doc = new TiXmlDocument();
if (!TinyXML::LoadDocument(fileName, doc))
{
const wxString message = wxString::Format(_("Error reading config file: %s"),
fileName.wx_str());
handleConfigError(*doc, fileName, message);
}
TiXmlElement* docroot = doc->FirstChildElement("CodeBlocksConfig");
if (!docroot)
{
const wxString message = wxString::Format(_("Cannot find docroot in config file '%s'"), fileName);
handleConfigError(*doc, fileName, message);
docroot = doc->FirstChildElement("CodeBlocksConfig");
if (!docroot)
cbThrow(_("Something really bad happened while reading the config file. Aborting!"));
}
const char *vers = docroot->Attribute("version");
if (!vers || atoi(vers) != 1)
cbMessageBox(_("ConfigManager encountered an unknown config file version. Continuing happily."), _("Warning"), wxICON_WARNING);
doc->ClearError();
wxString info;
info.Printf(_T(" application info:\n"
"\t svn_revision:\t%u\n"
"\t build_date:\t%s, %s\n"), ConfigManager::GetRevisionNumber(), wxT(BUILD_DATE), wxT(BUILD_TIME));
#if defined(__clang__)
info += wxString::Format(wxT("\t compiler_version:\tclang %d.%d.%d\n"), __clang_major__,
__clang_minor__, __clang_patchlevel__);
#elif defined(__GNUC__)
info += wxString::Format(wxT("\t compiler_version:\tgcc %d.%d.%d\n"), __GNUC__, __GNUC_MINOR__,
__GNUC_PATCHLEVEL__);
#endif
if (platform::windows)
info.append(_T("\t Windows "));
else if (platform::Linux)
info.append(_T("\t Linux "));
else if (platform::macosx)
info.append(_T("\t Mac OS X "));
else if (platform::Unix)
info.append(_T("\t Unix "));
info.append(platform::unicode ? _T("Unicode") : _T("ANSI"));
info.append(wxT("\n"));
TiXmlComment c;
c.SetValue((const char*) info.mb_str());
TiXmlNode *firstchild = docroot->FirstChild();
if (firstchild && firstchild->ToComment())
{
docroot->RemoveChild(firstchild);
firstchild = docroot->FirstChild();
}
if (firstchild)
docroot->InsertBeforeChild(firstchild, c);
else
docroot->InsertEndChild(c);
}
void CfgMgrBldr::SwitchToR(const wxString& absFileName)
{
if (doc)
delete doc;
doc = new TiXmlDocument();
doc->ClearError();
cfg = absFileName;
wxURL url(absFileName);
url.SetProxy(ConfigManager::GetProxy());
if (url.GetError() == wxURL_NOERR)
{
wxInputStream *is = url.GetInputStream();
if (is && is->IsOk())
{
size_t size = is->GetSize();
wxString str;
wxChar* c = wxStringBuffer(str, size);
is->Read(c, size);
doc = new TiXmlDocument();
if (doc->Parse(cbU2C(str)))
{
doc->ClearError();
delete is;
return;
}
if (Manager::Get()->GetLogManager())
{
Manager::Get()->GetLogManager()->DebugLog(_("##### Error loading or parsing remote config file"));
Manager::Get()->GetLogManager()->DebugLog(cbC2U(doc->ErrorDesc()));
doc->ClearError();
}
}
delete is;
}
cfg.Empty();
SwitchTo(wxEmptyString); // fall back
}
CfgMgrBldr::~CfgMgrBldr()
{
NamespaceMap::iterator it;
for ( it = namespaces.begin(); it != namespaces.end(); ++it )
delete it->second;
namespaces.clear();
Close();
delete volatile_doc;
}
void CfgMgrBldr::Flush()
{
if (doc)
{
if (!cfg.StartsWith(_T("http://")))
{
bool done = false;
do
{
if (TinyXML::SaveDocument(cfg, doc))
done = true;
else
{
AnnoyingDialog dlg(_("Error"),
wxString::Format(_("Could not save config file '%s'!"), cfg),
wxART_ERROR, AnnoyingDialog::TWO_BUTTONS,
AnnoyingDialog::rtTWO, _("&Retry"), _("&Close"));
switch (dlg.ShowModal())
{
case AnnoyingDialog::rtONE:
done = false;
break;
case AnnoyingDialog::rtTWO:
default:
done = true;
}
}
} while (!done);
}
else
{
// implement WebDAV another time
}
}
}
void CfgMgrBldr::Close()
{
Flush();
if (doc)
delete doc;
doc = nullptr;
}
ConfigManager* CfgMgrBldr::GetConfigManager(const wxString& name_space)
{
return Get()->Build(name_space);
}
ConfigManager* CfgMgrBldr::Build(const wxString& name_space)
{
if (name_space.IsEmpty())
cbThrow(_("You attempted to get a ConfigManager instance without providing a namespace."));
wxCriticalSectionLocker locker(cs);
NamespaceMap::iterator it = namespaces.find(name_space);
if (it != namespaces.end())
return it->second;
TiXmlElement* docroot;
if (name_space.StartsWith(_T("volatile:")))
{
if (!volatile_doc)
{
volatile_doc = new TiXmlDocument();
volatile_doc->InsertEndChild(TiXmlElement("CodeBlocksConfig"));
volatile_doc->SetCondenseWhiteSpace(false);
}
docroot = volatile_doc->FirstChildElement("CodeBlocksConfig");
}
else
{
docroot = doc->FirstChildElement("CodeBlocksConfig");
if (!docroot)
{
wxString err(_("Fatal error parsing supplied configuration file.\nParser error message:\n"));
err << wxString::Format(_("%s\nAt row %d, column %d."), cbC2U(doc->ErrorDesc()), doc->ErrorRow(), doc->ErrorCol());
cbThrow(err);
}
}
TiXmlElement* root = docroot->FirstChildElement(cbU2C(name_space));
if (!root) // namespace does not exist
{
docroot->InsertEndChild(TiXmlElement(cbU2C(name_space)));
root = docroot->FirstChildElement(cbU2C(name_space));
}
if (!root) // now what!
cbThrow(_("Unable to create namespace in document tree (actually not possible..?)"));
ConfigManager *c = new ConfigManager(root);
namespaces[name_space] = c;
return c;
}
wxString CfgMgrBldr::GetConfigFile() const
{
return cfg;
}
/*
* Hack to enable Turkish language. wxString::Upper will convert lowercase 'i' to \u0130 instead of \u0069 in Turkish locale,
* which will break the config file when used in a tag
*/
inline void to_upper(wxString& s)
{
wxStringCharType *p = const_cast<wxStringCharType*>(s.wx_str());
wxStringCharType q;
size_t len = s.length()+1;
for (;--len;++p)
{
q = *p;
if (q >= 'a' && q <= 'z')
*p = q - 32;
}
}
inline void to_lower(wxString& s)
{
wxStringCharType *p = const_cast<wxStringCharType*>(s.wx_str());
wxStringCharType q;
size_t len = s.length()+1;
for (;--len;++p)
{
q = *p;
if (q >= 'A' && q <= 'Z')
*p = q + 32;
}
}
/* ------------------------------------------------------------------------------------------------------------------
* Functions to retrieve system paths and locate data files in a defined, consistent way.
* Please note that the application determines app_path and data_path at runtime and passes the results
* to ConfigManager. GetExecutableFolder() and GetDataFolder() are therefore under normal conditions
* simply more efficient shortcuts for Read("app_path") and Read("data_path").
*/
wxString ConfigManager::GetProxy()
{
return Manager::Get()->GetConfigManager(_T("app"))->Read(_T("network_proxy"));
}
wxString ConfigManager::GetFolder(SearchDirs dir)
{
static bool once = 1;
if (once)
{
InitPaths();
once = false;
}
switch (dir)
{
case sdHome:
return ConfigManager::home_folder;
case sdBase:
return ConfigManager::app_path;
case sdTemp:
return ConfigManager::temp_folder;
case sdConfig:
return ConfigManager::config_folder;
case sdCurrent:
return ::wxGetCwd();
case sdPluginsGlobal:
#ifndef CB_AUTOCONF
return ConfigManager::data_path_global + wxFILE_SEP_PATH + _T("plugins");
#else
return ConfigManager::plugin_path_global;
#endif
case sdPluginsUser:
return ConfigManager::data_path_user + wxFILE_SEP_PATH + _T("plugins");
case sdScriptsGlobal:
return ConfigManager::data_path_global + wxFILE_SEP_PATH + _T("scripts");
case sdScriptsUser:
return ConfigManager::data_path_user + wxFILE_SEP_PATH + _T("scripts");
case sdDataGlobal:
return ConfigManager::data_path_global;
case sdDataUser:
return ConfigManager::data_path_user;
case sdPath:
case sdAllUser:
case sdAllGlobal:
case sdAllKnown:
default:
return wxEmptyString;
}
}
inline wxString ConfigManager::GetUserDataFolder()
{
if (has_alternate_user_data_path)
return alternate_user_data_path;
#ifdef __WINDOWS__
TCHAR buffer[MAX_PATH];
if (!ConfigManager::has_alternate_user_data_path && ::GetEnvironmentVariable(_T("APPDATA"), buffer, MAX_PATH))
return wxString::Format(_T("%s\\CodeBlocks"), buffer);
else
return wxStandardPathsBase::Get().GetUserDataDir();
#else
#ifdef __linux__
gchar *filename = g_build_filename(g_get_user_config_dir(), "codeblocks", nullptr);
wxString result=wxString::FromUTF8(filename);
g_free(filename);
return result;
#else
return wxStandardPathsBase::Get().GetUserDataDir();
#endif // __linux__
#endif // __WINDOWS__
}
bool ConfigManager::SetUserDataFolder(const wxString &user_data_path)
{
wxString udp = wxFileName::DirName(user_data_path).GetFullPath();
if (!CreateDirRecursively(udp))
{
cbMessageBox(wxString::Format(_("The --user-data-dir directory %s does not exist and could not be created. Please check the path and try again"),
user_data_path.c_str()), _("Command Line Error"));
return false;
}
has_alternate_user_data_path = true;
ConfigManager::alternate_user_data_path = udp;
return true;
}
wxString ConfigManager::LocateDataFile(const wxString& filename, int search_dirs)
{
wxPathList searchPaths;
// user dirs have precedence
if (search_dirs & sdPluginsUser)
searchPaths.Add(GetPluginsFolder(false));
if (search_dirs & sdScriptsUser)
searchPaths.Add(GetScriptsFolder(false));
if (search_dirs & sdDataUser)
searchPaths.Add(GetDataFolder(false));
// then we have global dirs
if (search_dirs & sdPluginsGlobal)
searchPaths.Add(GetPluginsFolder(true));
if (search_dirs & sdScriptsGlobal)
searchPaths.Add(GetScriptsFolder(true));
if (search_dirs & sdDataGlobal)
searchPaths.Add(GetDataFolder(true));
// rest of the dirs
if (search_dirs & sdCurrent)
searchPaths.Add(::wxGetCwd());
if (search_dirs & sdConfig)
searchPaths.Add(GetConfigFolder());
if (search_dirs & sdHome)
searchPaths.Add(GetHomeFolder());
if (search_dirs & sdBase)
searchPaths.Add(GetExecutableFolder());
if (search_dirs & sdTemp)
searchPaths.Add(GetTempFolder());
// PATH env. var
if (search_dirs & sdPath)
searchPaths.AddEnvList(_T("PATH"));
return searchPaths.FindValidPath(filename);
}
/* ------------------------------------------------------------------------------------------------------------------
* ConfigManager
*/
ConfigManager::ConfigManager(TiXmlElement* r) : doc(r->GetDocument()), root(r), pathNode(r)
{
}
/* ------------------------------------------------------------------------------------------------------------------
* Configuration path handling
* Note that due to namespaces, you do no longer need to care about saving/restoring the current path in the normal case.
* Mostly, there will be only one module working with one namespace, and every namespace keeps track of its own path.
* Also, please note that GetPath() is more expensive than it seems (not a mere accessor to a member variable!), while
* SetPath() not only sets the current path, but also creates the respective nodes in the XML document if these don't exist.
*/
wxString ConfigManager::GetPath() const
{
TiXmlElement *e = pathNode;
wxString ret;
ret.Alloc(64);
ret = cbC2U(e->Value());
while ((e = e->Parent()->ToElement()) && e != root)
{
ret.Prepend(_T('/'));
ret.Prepend(cbC2U(e->Value()));
}
ret.Prepend(_T('/'));
return ret;
}
void ConfigManager::SetPath(const wxString& path)
{
wxString p(path + _T('/'));
pathNode = AssertPath(p);
}
wxString ConfigManager::InvalidNameMessage(const wxString& what, const wxString& sub, TiXmlElement *localPath) const
{
wxString s;
s.Printf(_("The %s %s (child of node \"%s\" in namespace \"%s\") does not meet the standard for path naming (must start with a letter)."),
what,
sub,
cbC2U(localPath->Value()).c_str(),
cbC2U(root->Value()).c_str());
return s;
}
TiXmlElement* ConfigManager::AssertPath(wxString& path)
{
Collapse(path);
wxString illegal(_T(" -:.\"\'$&()[]<>+#"));
size_t i = 0;
while ((i = path.find_first_of(illegal, i)) != wxString::npos)
path[i] = _T('_');
TiXmlElement *localPath = pathNode ? pathNode : root;
if (path.GetChar(0) == '/') // absolute path
{
localPath = root;
path = path.Mid(1);
}
if (path.find(_T('/')) != wxString::npos) // need for path walking
to_lower(path);
wxString sub;
while (path.find(_T('/')) != wxString::npos)
{
sub = path.BeforeFirst(_T('/'));
path = path.AfterFirst(_T('/'));
if (localPath != root && sub.IsSameAs(CfgMgrConsts::dotDot))
localPath = localPath->Parent()->ToElement();
else if (sub.GetChar(0) < _T('a') || sub.GetChar(0) > _T('z'))
{
cbThrow(InvalidNameMessage(_T("subpath"), sub, localPath));
}
else
{
TiXmlElement* n = localPath->FirstChildElement(cbU2C(sub));
if (n)
localPath = n;
else
localPath = (TiXmlElement*) localPath->InsertEndChild(TiXmlElement(cbU2C(sub)));
}
}
to_upper(path);
if (!path.IsEmpty() && (path.GetChar(0) < _T('A') || path.GetChar(0) > _T('Z')))
cbThrow(InvalidNameMessage(_T("key"), path, localPath));
return localPath;
}
/* -----------------------------------------------------------------------------------------------------
* Clear all nodes from your namespace or delete the namespace alltogether (removing it from the config file).
* After Delete() returns, the pointer to your instance is invalid.
*/
void ConfigManager::Clear()
{
root->Clear();
}
void ConfigManager::Delete()
{
CfgMgrBldr * bld = CfgMgrBldr::Get();
const wxString ns(cbC2U(root->Value()));
root->Clear();
doc->RootElement()->RemoveChild(root);
wxCriticalSectionLocker(bld->cs);
NamespaceMap::iterator it = bld->namespaces.find(ns);
if (it != bld->namespaces.end())
bld->namespaces.erase(it);
delete this;
}
void ConfigManager::DeleteAll()
{
CfgMgrBldr * bld = CfgMgrBldr::Get();
const wxString ns(cbC2U(root->Value()));
if (!ns.IsSameAs(_T("app")))
cbThrow(_("Illegal attempt to invoke DeleteAll()."));
wxCriticalSectionLocker(bld->cs);
doc->RootElement()->Clear();
for (NamespaceMap::iterator it = bld->namespaces.begin(); it != bld->namespaces.end(); ++it)
delete it->second;
bld->namespaces.clear();
}
void ConfigManager::Flush()
{
CfgMgrBldr * bld = CfgMgrBldr::Get();
wxCriticalSectionLocker(bld->cs);
bld->Flush();
}
/* ------------------------------------------------------------------------------------------------------------------
* Utility functions for writing nodes
*/
TiXmlElement* ConfigManager::GetUniqElement(TiXmlElement* p, const wxString& q)
{
TiXmlElement* r;
if ((r = p->FirstChildElement(cbU2C(q))))
return r;
return (TiXmlElement*)(p->InsertEndChild(TiXmlElement(cbU2C(q))));
}
void ConfigManager::SetNodeText(TiXmlElement* n, const TiXmlText& t)
{
TiXmlNode *c = n->FirstChild();
if (c)
n->ReplaceChild(c, t);
else
n->InsertEndChild(t);
}
/* ------------------------------------------------------------------------------------------------------------------
* Write and read values
* Regardless of namespaces, the string keys app_path and data_path always refer to the location of the application's executable
* and the data path, respectively. These values are never saved to the configuration, but kept in static variables.
* The application makes use of this by "writing" to the configuration file after determining these values at runtime.
*/
void ConfigManager::Write(const wxString& name, const wxString& value, bool ignoreEmpty)
{
if (name.IsSameAs(CfgMgrConsts::app_path))
{
return;
}
else if (name.IsSameAs(CfgMgrConsts::data_path))
{
data_path_global = value;
return;
}
if (ignoreEmpty && value.IsEmpty())
{
UnSet(name);
return;
}
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *str = GetUniqElement(e, key);
TiXmlElement *s = GetUniqElement(str, _T("str"));
TiXmlText t(value.mb_str(wxConvUTF8));
t.SetCDATA(true);
SetNodeText(s, t);
}
void ConfigManager::Write(const wxString& key, const char* str)
{
/* NOTE (mandrav#1#): Do *not* remove 'false' from the call because in ANSI builds,
it matches this very function and overflows the stack... */
Write(key, cbC2U(str), false);
}
wxString ConfigManager::Read(const wxString& name, const wxString& defaultVal)
{
if (name.IsSameAs(CfgMgrConsts::app_path))
return app_path;
else if (name.IsSameAs(CfgMgrConsts::data_path))
return data_path_global;
wxString ret;
if (Read(name, &ret))
return ret;
else
return defaultVal;
}
bool ConfigManager::Read(const wxString& name, wxString* str)
{
if (name.IsSameAs(CfgMgrConsts::app_path))
{
str->assign(app_path);
return true;
}
else if (name.IsSameAs(CfgMgrConsts::data_path))
{
str->assign(data_path_global);
return true;
}
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlText *t = (TiXmlText *) parentHandle.FirstChild(cbU2C(key)).FirstChild("str").FirstChild().Node();
if (t)
{
str->assign(cbC2U(t->Value()));
return true;
}
return false;
}
void ConfigManager::Write(const wxString& name, const wxColour& c)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
TiXmlElement *s = GetUniqElement(leaf, _T("colour"));
if (c == wxNullColour)
{
s->SetAttribute("null", "true");
s->SetAttribute("r", 0);
s->SetAttribute("g", 0);
s->SetAttribute("b", 0);
}
else
{
s->SetAttribute("r", c.Red());
s->SetAttribute("g", c.Green());
s->SetAttribute("b", c.Blue());
}
}
wxColour ConfigManager::ReadColour(const wxString& name, const wxColour& defaultVal)
{
wxColour ret;
if (Read(name, &ret))
return ret;
else
return defaultVal;
}
bool ConfigManager::Read(const wxString& name, wxColour* ret)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlElement *c = (TiXmlElement *) parentHandle.FirstChild(cbU2C(key)).FirstChild("colour").Element();
if (c)
{
const char *isNull = c->Attribute("null");
if (isNull && strcmp(isNull, "true") == 0)
{
*ret = wxNullColour;
return true;
}
else
{
int r, g, b;
if (c->QueryIntAttribute("r", &r) == TIXML_SUCCESS
&& c->QueryIntAttribute("g", &g) == TIXML_SUCCESS
&& c->QueryIntAttribute("b", &b) == TIXML_SUCCESS)
{
ret->Set(r, g, b);
return true;
}
}
}
*ret = wxNullColour;
return false;
}
void ConfigManager::Write(const wxString& name, int value)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
leaf->SetAttribute("int", value);
}
int ConfigManager::ReadInt(const wxString& name, int defaultVal)
{
int ret;
if (Read(name, &ret))
return ret;
else
return defaultVal;
}
bool ConfigManager::Read(const wxString& name, int* value)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlElement *leaf = parentHandle.FirstChild(cbU2C(key)).Element();
if (leaf)
return leaf->QueryIntAttribute("int", value) == TIXML_SUCCESS;
return false;
}
void ConfigManager::Write(const wxString& name, bool value)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
leaf->SetAttribute("bool", value ? "1" : "0");
}
bool ConfigManager::ReadBool(const wxString& name, bool defaultVal)
{
bool ret;
if (Read(name, &ret))
return ret;
else
return defaultVal;
}
bool ConfigManager::Read(const wxString& name, bool* value)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlElement *leaf = parentHandle.FirstChild(cbU2C(key)).Element();
if (leaf && leaf->Attribute("bool"))
{
*value = leaf->Attribute("bool")[0] == '1';
return true;
}
return false;
}
void ConfigManager::Write(const wxString& name, double value)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
leaf->SetDoubleAttribute("double", value);
}
double ConfigManager::ReadDouble(const wxString& name, double defaultVal)
{
double ret;
if (Read(name, &ret))
return ret;
else
return defaultVal;
}
bool ConfigManager::Read(const wxString& name, double* value)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlElement *leaf = parentHandle.FirstChild(cbU2C(key)).Element();
if (leaf)
return leaf->QueryDoubleAttribute("double", value) == TIXML_SUCCESS;
return false;
}
void ConfigManager::Set(const wxString& name)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
GetUniqElement(e, key);
}
void ConfigManager::UnSet(const wxString& name)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlNode *leaf = GetUniqElement(e, key);
e->RemoveChild(leaf);
}
bool ConfigManager::Exists(const wxString& name)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlElement *leaf = parentHandle.FirstChild(cbU2C(key)).Element();
return leaf;
}
void ConfigManager::Write(const wxString& name, const wxArrayString& arrayString)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
TiXmlElement *as;
as = GetUniqElement(leaf, _T("astr"));
leaf->RemoveChild(as);
as = GetUniqElement(leaf, _T("astr"));
for (unsigned int i = 0; i < arrayString.GetCount(); ++i)
{
TiXmlElement s("s");
TiXmlText t(arrayString[i].mb_str(wxConvUTF8));
t.SetCDATA(true);
s.InsertEndChild(t);
as->InsertEndChild(s);
}
}
void ConfigManager::Read(const wxString& name, wxArrayString *arrayString)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlNode *asNode = parentHandle.FirstChild(cbU2C(key)).FirstChild("astr").Node();
TiXmlNode *curr = nullptr;
if (asNode)
{
while ((curr = asNode->IterateChildren("s", curr)))
arrayString->Add(cbC2U(curr->FirstChild()->ToText()->Value()));
}
}
wxArrayString ConfigManager::ReadArrayString(const wxString& name)
{
wxArrayString as;
Read(name, &as);
return as;
}
void ConfigManager::WriteBinary(const wxString& name, const wxString& source)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *str = GetUniqElement(e, key);
TiXmlElement *s = GetUniqElement(str, _T("bin"));
s->SetAttribute("crc", wxCrc32::FromString(source));
SetNodeText(s, TiXmlText(wxBase64::Encode(source).mb_str(wxConvUTF8)));
}
void ConfigManager::WriteBinary(const wxString& name, void* ptr, size_t len)
{
wxString s((wxChar*)ptr, len);
WriteBinary(name, s);
}
wxString ConfigManager::ReadBinary(const wxString& name)
{
wxString str;
wxString key(name);
TiXmlElement* e = AssertPath(key);
unsigned int crc = 0;
TiXmlHandle parentHandle(e);
TiXmlElement* bin = parentHandle.FirstChild(cbU2C(key)).FirstChild("bin").Element();
if (!bin)
return wxEmptyString;
if (bin->QueryIntAttribute("crc", (int*)&crc) != TIXML_SUCCESS)
return wxEmptyString;
if (const TiXmlText* t = bin->FirstChild()->ToText())
{
str.assign(cbC2U(t->Value()));
str = wxBase64::Decode(str);
if (crc == wxCrc32::FromString(str))
return str;
}
return wxEmptyString;
}
wxArrayString ConfigManager::EnumerateSubPaths(const wxString& path)
{
wxString key(path + _T('/')); // the trailing slash hack is required because AssertPath expects a key name
TiXmlNode* e = AssertPath(key);
wxArrayString ret;
TiXmlElement *curr = nullptr;
if (e)
{
while (e->IterateChildren(curr) && (curr = e->IterateChildren(curr)->ToElement()))
{
wxUniChar c = cbC2U(curr->Value())[0];
if (c < _T('A') || c > _T('Z')) // first char must be a letter, uppercase letters are key names
ret.Add(cbC2U(curr->Value()));
}
}
return ret;
}
void ConfigManager::DeleteSubPath(const wxString& thePath)
{
if (doc->ErrorId())
{
cbMessageBox(wxString(_T("### TinyXML error:\n")) << cbC2U(doc->ErrorDesc()));
doc->ClearError();
}
wxString path(thePath);
to_lower(path);
Collapse(path);
wxString illegal(_T(" :.,;!\"\'$%&()[]<>{}?*+-|#"));
size_t i;
while ((i = path.find_first_of(illegal)) != wxString::npos)
path[i] = _T('_');
if (path.Last() == _T('/'))
path.RemoveLast();
if (path.IsSameAs(_T("/"))) // this function will refuse to remove root!
return;
TiXmlElement* parent = pathNode ? pathNode : root;
if (path.find(_T('/')) != wxString::npos)
{
wxString sub;
do
{
sub = path.BeforeFirst(_T('/'));
path = path.AfterFirst(_T('/'));
if (sub.IsEmpty())
parent = root;
else if (sub.IsSameAs(_T(".")))
;
else if (parent != root && sub.IsSameAs(_T("..")))
parent = parent->Parent()->ToElement();
else
{
TiXmlElement* n = parent->FirstChildElement(cbU2C(sub));
if (n)
parent = n;
else
return;
}
}
while (path.find(_T('/')) != wxString::npos);
}
if (!path.IsEmpty())
{
if (TiXmlNode *toRemove = parent->FirstChild(cbU2C(path)))
{
toRemove->Clear();
parent->RemoveChild(toRemove);
}
}
}
wxArrayString ConfigManager::EnumerateKeys(const wxString& path)
{
wxString key(path + _T('/')); // the trailing slash hack is required because AssertPath expects a key name
TiXmlNode* e = AssertPath(key);
wxArrayString ret;
TiXmlElement *curr = nullptr;
if (e)
{
while (e->IterateChildren(curr) && (curr = e->IterateChildren(curr)->ToElement()))
{
wxUniChar c = cbC2U(curr->Value())[0];
if (c >= _T('A') && c <= _T('Z')) // opposite of the above
ret.Add(cbC2U(curr->Value()));
}
}
return ret;
}
void ConfigManager::Write(const wxString& name, const ISerializable& object)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *obj = GetUniqElement(e, key);
TiXmlElement *s = GetUniqElement(obj, _T("obj"));
SetNodeText(s, TiXmlText(cbU2C(wxBase64::Encode(object.SerializeOut()))));
}
bool ConfigManager::Read(const wxString& name, ISerializable* object)
{
wxString str;
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlText *t = (TiXmlText *) parentHandle.FirstChild(cbU2C(key)).FirstChild("obj").FirstChild().Node();
if (t)
{
str.assign(cbC2U(t->Value()));
object->SerializeIn(wxBase64::Decode(str));
}
return wxEmptyString;
}
void ConfigManager::Write(const wxString& name, const ConfigManagerContainer::StringToStringMap& map)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
TiXmlElement *mNode;
mNode = GetUniqElement(leaf, _T("ssmap"));
leaf->RemoveChild(mNode);
mNode = GetUniqElement(leaf, _T("ssmap"));
for (ConfigManagerContainer::StringToStringMap::const_iterator it = map.begin(); it != map.end(); ++it)
{
TiXmlElement s(cbU2C(it->first));
TiXmlText t(cbU2C(it->second));
t.SetCDATA(true);
s.InsertEndChild(t);
mNode->InsertEndChild(s);
}
}
void ConfigManager::Read(const wxString& name, ConfigManagerContainer::StringToStringMap* map)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlNode *mNode = parentHandle.FirstChild(cbU2C(key)).FirstChild("ssmap").Node();
TiXmlNode *curr = nullptr;
if (mNode)
{
while ((curr = mNode->IterateChildren(curr)))
(*map)[cbC2U(curr->Value())] = cbC2U(curr->FirstChild()->ToText()->Value());
}
}
ConfigManagerContainer::StringToStringMap ConfigManager::ReadSSMap(const wxString& name)
{
ConfigManagerContainer::StringToStringMap ret;
Read(name, &ret);
return ret;
}
void ConfigManager::Write(const wxString& name, const ConfigManagerContainer::IntToStringMap& map)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
TiXmlElement *mNode;
mNode = GetUniqElement(leaf, _T("ismap"));
leaf->RemoveChild(mNode);
mNode = GetUniqElement(leaf, _T("ismap"));
wxString tmp;
for (ConfigManagerContainer::IntToStringMap::const_iterator it = map.begin(); it != map.end(); ++it)
{
tmp.Printf(_T("x%d"), (int) it->first);
TiXmlElement s(tmp.mb_str());
TiXmlText t(cbU2C(it->second));
t.SetCDATA(true);
s.InsertEndChild(t);
mNode->InsertEndChild(s);
}
}
void ConfigManager::Read(const wxString& name, ConfigManagerContainer::IntToStringMap* map)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlNode *mNode = parentHandle.FirstChild(cbU2C(key)).FirstChild("ismap").Node();
TiXmlNode *curr = nullptr;
long tmp;
if (mNode)
{
while ((curr = mNode->IterateChildren(curr)))
{
cbC2U(curr->Value()).Mid(1).ToLong(&tmp);
(*map)[tmp] = cbC2U(curr->FirstChild()->ToText()->Value());
}
}
}
ConfigManagerContainer::IntToStringMap ConfigManager::ReadISMap(const wxString& name)
{
ConfigManagerContainer::IntToStringMap ret;
Read(name, &ret);
return ret;
}
void ConfigManager::Write(const wxString& name, const ConfigManagerContainer::StringSet& set)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
TiXmlElement *mNode;
mNode = GetUniqElement(leaf, _T("sset"));
leaf->RemoveChild(mNode);
mNode = GetUniqElement(leaf, _T("sset"));
for (ConfigManagerContainer::StringSet::const_iterator it = set.begin(); it != set.end(); ++it)
{
TiXmlElement s("s");
TiXmlText t(cbU2C(*it));
t.SetCDATA(true);
s.InsertEndChild(t);
mNode->InsertEndChild(s);
}
}
void ConfigManager::Read(const wxString& name, ConfigManagerContainer::StringSet* set)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlHandle parentHandle(e);
TiXmlNode *mNode = parentHandle.FirstChild(cbU2C(key)).FirstChild("sset").Node();
TiXmlNode *curr = nullptr;
if (mNode)
{
while ((curr = mNode->IterateChildren(curr)))
set->insert(cbC2U(curr->FirstChild()->ToText()->Value()));
}
}
ConfigManagerContainer::StringSet ConfigManager::ReadSSet(const wxString& name)
{
ConfigManagerContainer::StringSet ret;
Read(name, &ret);
return ret;
}
void ConfigManager::Write(const wxString& name, const ConfigManagerContainer::SerializableObjectMap* map)
{
wxString key(name);
TiXmlElement* e = AssertPath(key);
TiXmlElement *leaf = GetUniqElement(e, key);
TiXmlElement *mNode;
mNode = GetUniqElement(leaf, _T("objmap"));
leaf->RemoveChild(mNode);
mNode = GetUniqElement(leaf, _T("objmap"));
for (ConfigManagerContainer::SerializableObjectMap::const_iterator it = map->begin(); it != map->end(); ++it)
{
TiXmlElement s(cbU2C(it->first));
s.InsertEndChild(TiXmlText(cbU2C(wxBase64::Encode(it->second->SerializeOut()))));
mNode->InsertEndChild(s);
}
}
void ConfigManager::InitPaths()
{
ConfigManager::config_folder = ConfigManager::GetUserDataFolder();
ConfigManager::home_folder = wxStandardPathsBase::Get().GetUserConfigDir();
ConfigManager::app_path = ::DetermineExecutablePath();
wxString res_path = ::DetermineResourcesPath();
// if non-empty, the app has overriden it (e.g. "--prefix" was passed in the command line)
if (data_path_global.IsEmpty())
{
if (platform::windows)
#ifdef CB_AUTOCONF
ConfigManager::data_path_global = app_path + _T("/../share/codeblocks");
#else
ConfigManager::data_path_global = app_path + _T("\\share\\codeblocks");
#endif
else if (platform::macosx)
ConfigManager::data_path_global = res_path + _T("/share/codeblocks");
else
ConfigManager::data_path_global = wxStandardPathsBase::Get().GetDataDir();
}
else
ConfigManager::data_path_global = UnixFilename(data_path_global);
#ifdef CB_AUTOCONF
if (plugin_path_global.IsEmpty())
{
if (platform::windows)
ConfigManager::plugin_path_global = app_path + _T("\\..\\lib\\codeblocks\\plugins");
else if (platform::macosx)
ConfigManager::plugin_path_global = data_path_global + _T("/plugins");
else
{
#ifdef __WXGTK__
// It seems we can not longer rely on wxStandardPathsBase::Get().GetPluginsDir(),
// because its behaviour has changed on some systems (at least Fedora 14 64-bit).
// So we create the pathname manually
ConfigManager::plugin_path_global = ((const wxStandardPaths&)wxStandardPaths::Get()).GetInstallPrefix() + _T("/lib/codeblocks/plugins");
// first assume, we use standard-paths
if (!wxDirExists(ConfigManager::plugin_path_global) && wxIsPlatform64Bit())
{
// if standard-path does not exist and we are on 64-bit system, use lib64 instead
ConfigManager::plugin_path_global = ((const wxStandardPaths&)wxStandardPaths::Get()).GetInstallPrefix() + _T("/lib64/codeblocks/plugins");
}
#endif // __WXGTK__
}
}
#endif
wxString dataPathUser = ConfigManager::config_folder + wxFILE_SEP_PATH + _T("share");
#ifdef __linux__
if (!has_alternate_user_data_path)
{
gchar *filename = g_build_filename(g_get_user_data_dir(), nullptr);
dataPathUser = wxString::FromUTF8(filename);
g_free(filename);
}
#endif // __linux__
ConfigManager::data_path_user = dataPathUser + wxFILE_SEP_PATH + _T("codeblocks");
// if user- and global-datapath are the same (can happen in portable mode) we run in conflicts
// so we extend the user-datapath with the users name
if (wxFileName(ConfigManager::data_path_user) == wxFileName(ConfigManager::data_path_global))
ConfigManager::data_path_user.append("." + wxGetUserId());
CreateDirRecursively(ConfigManager::config_folder);
CreateDirRecursively(ConfigManager::data_path_user + _T("/plugins/"));
CreateDir(ConfigManager::data_path_user + _T("/scripts/"));
ConfigManager::temp_folder = wxStandardPathsBase::Get().GetTempDir();
}
void ConfigManager::MigrateFolders()
{
#ifdef __linux__
// if the old config-folder (~/.codeblocks) does not exist, we have nothing to do.
if (!wxDirExists(wxStandardPaths::Get().GetUserDataDir()))
return;
// ConfigManager::config_folder might be the portable-path but we want to migrate the standard-conform folder,
// but only if it not already exists
wxString newConfigFolder = wxString::FromUTF8(g_build_filename (g_get_user_config_dir(), "codeblocks", nullptr));
// if the new config folder already exist, we step out immediately
if (wxDirExists(newConfigFolder))
return;
wxString oldConfigFolder = wxStandardPaths::Get().GetUserDataDir();
wxString oldDataFolder = oldConfigFolder + wxFILE_SEP_PATH + _T("share") + wxFILE_SEP_PATH + _T("codeblocks");
wxString newDataFolder = wxString::FromUTF8(g_build_filename (g_get_user_data_dir(), nullptr)) + wxFILE_SEP_PATH + _T("codeblocks");
wxString msg;
msg = F(_("The places where the configuration files and user-data files are stored\n"
"have been changed to be more standard-conform.\n"
"\n"
"Now moving \"%s\"\n"
"to \"%s\"\n"
"and \"%s\"\n"
"to \"%s\".\n"),
oldDataFolder.wx_str(),
newDataFolder.wx_str(),
oldConfigFolder.wx_str(),
newConfigFolder.wx_str());
cbMessageBox(msg, _("Try to migrate config-folder ..."), wxICON_INFORMATION);
bool success = true;
if (wxDirExists(oldDataFolder))
{
// make sure the target-folder exists
CreateDirRecursively(newDataFolder);
success = wxRenameFile(oldDataFolder, newDataFolder);
wxRmdir(oldConfigFolder + wxFILE_SEP_PATH + _T("share"));
}
if (success)
{
// make sure the target-folder exists
CreateDirRecursively(newConfigFolder);
success = wxRenameFile(oldConfigFolder, newConfigFolder);
}
if (!success)
{
msg = F(_("Error moving \"%s\"\n"
"to \"%s\"\n"
"or \"%s\"\n"
"to \"%s\".\n\n"
"Please check the folders manually (access rights?) !\n"
"A new configuration will be created from scratch!"),
oldDataFolder.wx_str(),
newDataFolder.wx_str(),
oldConfigFolder.wx_str(),
newConfigFolder.wx_str());
cbMessageBox(msg, _("Error migrating config-folder ..."), wxICON_ERROR);
}
#endif // __linux__
}
void ConfigManagerWrapper::Write(const wxString& name, const wxString& value, bool ignoreEmpty)
{
if (m_namespace.empty())
return;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
c->Write(m_basepath + name, value, ignoreEmpty);
}
wxString ConfigManagerWrapper::Read(const wxString& key, const wxString& defaultVal)
{
if (m_namespace.empty())
return defaultVal;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->Read(m_basepath + key, defaultVal);
}
bool ConfigManagerWrapper::Read(const wxString& key, wxString* str)
{
if (m_namespace.empty())
return false;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->Read(key, str);
}
void ConfigManagerWrapper::Write(const wxString& key, const char* str)
{
if (m_namespace.empty())
return;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
c->Write(key, str);
}
void ConfigManagerWrapper::Write(const wxString& name, int value)
{
if (m_namespace.empty())
return;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
c->Write(m_basepath + name, value);
}
bool ConfigManagerWrapper::Read(const wxString& name, int* value)
{
if (m_namespace.empty())
return false;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->Read(m_basepath + name, value);
}
int ConfigManagerWrapper::ReadInt(const wxString& name, int defaultVal)
{
if (m_namespace.empty())
return defaultVal;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->ReadInt(m_basepath + name, defaultVal);
}
void ConfigManagerWrapper::Write(const wxString& name, bool value)
{
if (m_namespace.empty())
return;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
c->Write(m_basepath + name, value);
}
bool ConfigManagerWrapper::Read(const wxString& name, bool* value)
{
if (m_namespace.empty())
return false;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->Read(m_basepath + name, value);
}
bool ConfigManagerWrapper::ReadBool(const wxString& name, bool defaultVal)
{
if (m_namespace.empty())
return defaultVal;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->ReadBool(m_basepath + name, defaultVal);
}
void ConfigManagerWrapper::Write(const wxString& name, double value)
{
if (m_namespace.empty())
return;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
c->Write(m_basepath + name, value);
}
bool ConfigManagerWrapper::Read(const wxString& name, double* value)
{
if (m_namespace.empty())
return false;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->Read(m_basepath + name, value);
}
double ConfigManagerWrapper::ReadDouble(const wxString& name, double defaultVal)
{
if (m_namespace.empty())
return defaultVal;
ConfigManager *c = Manager::Get()->GetConfigManager(m_namespace);
return c->ReadDouble(m_basepath + name, defaultVal);
}
static wxString getCompilerPluginFilename()
{
if (platform::windows)
#ifdef CB_AUTOCONF
return wxT("libcompiler.dll");
#else
return wxT("compiler.dll");
#endif
else if (platform::darwin || platform::macosx)
return wxT("libcompiler.dylib");
else
return wxT("libcompiler.so");
}
wxArrayString cbReadBatchBuildPlugins()
{
ConfigManager *bbcfg = Manager::Get()->GetConfigManager(_T("plugins"));
wxArrayString bbplugins = bbcfg->ReadArrayString(_T("/batch_build_plugins"));
if (!bbplugins.GetCount())
bbplugins.Add(getCompilerPluginFilename());
return bbplugins;
}
void cbWriteBatchBuildPlugins(wxArrayString bbplugins, wxWindow *messageBoxParent)
{
const wxString &compiler = getCompilerPluginFilename();
if (bbplugins.Index(compiler) == wxNOT_FOUND)
{
bbplugins.Add(compiler);
cbMessageBox(_("The compiler plugin must always be loaded for batch builds!\n"
"Automatically re-enabled."),
_("Warning"), wxICON_WARNING, messageBoxParent);
}
ConfigManager *bbcfg = Manager::Get()->GetConfigManager(_T("plugins"));
bbcfg->Write(_T("/batch_build_plugins"), bbplugins);
}
|