Common.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "TextsCore.h"
  8. #include "Interface.h"
  9. #include <StrUtils.hpp>
  10. #include <DateUtils.hpp>
  11. #include <math.h>
  12. #include <shlobj.h>
  13. //---------------------------------------------------------------------------
  14. #pragma package(smart_init)
  15. //---------------------------------------------------------------------------
  16. //---------------------------------------------------------------------------
  17. // TGuard
  18. //---------------------------------------------------------------------------
  19. __fastcall TGuard::TGuard(TCriticalSection * ACriticalSection) :
  20. FCriticalSection(ACriticalSection)
  21. {
  22. assert(ACriticalSection != NULL);
  23. FCriticalSection->Enter();
  24. }
  25. //---------------------------------------------------------------------------
  26. __fastcall TGuard::~TGuard()
  27. {
  28. FCriticalSection->Leave();
  29. }
  30. //---------------------------------------------------------------------------
  31. // TUnguard
  32. //---------------------------------------------------------------------------
  33. __fastcall TUnguard::TUnguard(TCriticalSection * ACriticalSection) :
  34. FCriticalSection(ACriticalSection)
  35. {
  36. assert(ACriticalSection != NULL);
  37. FCriticalSection->Leave();
  38. }
  39. //---------------------------------------------------------------------------
  40. __fastcall TUnguard::~TUnguard()
  41. {
  42. FCriticalSection->Enter();
  43. }
  44. //---------------------------------------------------------------------------
  45. //---------------------------------------------------------------------------
  46. const wchar_t EngShortMonthNames[12][4] =
  47. {L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
  48. L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"};
  49. const char Bom[3] = "\xEF\xBB\xBF";
  50. const wchar_t TokenPrefix = L'%';
  51. const wchar_t NoReplacement = wchar_t(false);
  52. const wchar_t TokenReplacement = wchar_t(true);
  53. const UnicodeString LocalInvalidChars = L"/\\:*?\"<>|";
  54. //---------------------------------------------------------------------------
  55. UnicodeString ReplaceChar(UnicodeString Str, wchar_t A, wchar_t B)
  56. {
  57. for (Integer Index = 0; Index < Str.Length(); Index++)
  58. if (Str[Index+1] == A) Str[Index+1] = B;
  59. return Str;
  60. }
  61. //---------------------------------------------------------------------------
  62. UnicodeString DeleteChar(UnicodeString Str, wchar_t C)
  63. {
  64. int P;
  65. while ((P = Str.Pos(C)) > 0)
  66. {
  67. Str.Delete(P, 1);
  68. }
  69. return Str;
  70. }
  71. //---------------------------------------------------------------------------
  72. void PackStr(UnicodeString &Str)
  73. {
  74. // Following will free unnecessary bytes
  75. Str = Str.c_str();
  76. }
  77. //---------------------------------------------------------------------------
  78. void PackStr(RawByteString &Str)
  79. {
  80. // Following will free unnecessary bytes
  81. Str = Str.c_str();
  82. }
  83. //---------------------------------------------------------------------------
  84. void __fastcall Shred(UnicodeString & Str)
  85. {
  86. if (!Str.IsEmpty())
  87. {
  88. Str.Unique();
  89. memset(Str.c_str(), 0, Str.Length() * sizeof(*Str.c_str()));
  90. Str = L"";
  91. }
  92. }
  93. //---------------------------------------------------------------------------
  94. UnicodeString MakeValidFileName(UnicodeString FileName)
  95. {
  96. UnicodeString IllegalChars = L":;,=+<>|\"[] \\/?*";
  97. for (int Index = 0; Index < IllegalChars.Length(); Index++)
  98. {
  99. FileName = ReplaceChar(FileName, IllegalChars[Index+1], L'-');
  100. }
  101. return FileName;
  102. }
  103. //---------------------------------------------------------------------------
  104. UnicodeString RootKeyToStr(HKEY RootKey)
  105. {
  106. if (RootKey == HKEY_USERS) return L"HKEY_USERS";
  107. else
  108. if (RootKey == HKEY_LOCAL_MACHINE) return L"HKEY_LOCAL_MACHINE";
  109. else
  110. if (RootKey == HKEY_CURRENT_USER) return L"HKEY_CURRENT_USER";
  111. else
  112. if (RootKey == HKEY_CLASSES_ROOT) return L"HKEY_CLASSES_ROOT";
  113. else
  114. if (RootKey == HKEY_CURRENT_CONFIG) return L"HKEY_CURRENT_CONFIG";
  115. else
  116. if (RootKey == HKEY_DYN_DATA) return L"HKEY_DYN_DATA";
  117. else
  118. { Abort(); return L""; };
  119. }
  120. //---------------------------------------------------------------------------
  121. UnicodeString BooleanToEngStr(bool B)
  122. {
  123. if (B)
  124. {
  125. return L"Yes";
  126. }
  127. else
  128. {
  129. return L"No";
  130. }
  131. }
  132. //---------------------------------------------------------------------------
  133. UnicodeString BooleanToStr(bool B)
  134. {
  135. if (B)
  136. {
  137. return LoadStr(YES_STR);
  138. }
  139. else
  140. {
  141. return LoadStr(NO_STR);
  142. }
  143. }
  144. //---------------------------------------------------------------------------
  145. UnicodeString DefaultStr(const UnicodeString & Str, const UnicodeString & Default)
  146. {
  147. if (!Str.IsEmpty())
  148. {
  149. return Str;
  150. }
  151. else
  152. {
  153. return Default;
  154. }
  155. }
  156. //---------------------------------------------------------------------------
  157. UnicodeString CutToChar(UnicodeString &Str, wchar_t Ch, bool Trim)
  158. {
  159. Integer P = Str.Pos(Ch);
  160. UnicodeString Result;
  161. if (P)
  162. {
  163. Result = Str.SubString(1, P-1);
  164. Str.Delete(1, P);
  165. }
  166. else
  167. {
  168. Result = Str;
  169. Str = L"";
  170. }
  171. if (Trim)
  172. {
  173. Result = Result.TrimRight();
  174. Str = Str.TrimLeft();
  175. }
  176. return Result;
  177. }
  178. //---------------------------------------------------------------------------
  179. UnicodeString CopyToChars(const UnicodeString & Str, int & From, UnicodeString Chs, bool Trim,
  180. wchar_t * Delimiter, bool DoubleDelimiterEscapes)
  181. {
  182. UnicodeString Result;
  183. int P;
  184. for (P = From; P <= Str.Length(); P++)
  185. {
  186. if (IsDelimiter(Chs, Str, P))
  187. {
  188. if (DoubleDelimiterEscapes &&
  189. (P < Str.Length()) &&
  190. IsDelimiter(Chs, Str, P + 1))
  191. {
  192. Result += Str[P];
  193. P++;
  194. }
  195. else
  196. {
  197. break;
  198. }
  199. }
  200. else
  201. {
  202. Result += Str[P];
  203. }
  204. }
  205. if (P <= Str.Length())
  206. {
  207. if (Delimiter != NULL)
  208. {
  209. *Delimiter = Str[P];
  210. }
  211. }
  212. else
  213. {
  214. if (Delimiter != NULL)
  215. {
  216. *Delimiter = L'\0';
  217. }
  218. }
  219. // even if we reached the end, return index, as if there were the delimiter,
  220. // so caller can easily find index of the end of the piece by subtracting
  221. // 2 from From (as long as he did not asked for trimming)
  222. From = P+1;
  223. if (Trim)
  224. {
  225. Result = Result.TrimRight();
  226. while ((From <= Str.Length()) && (Str[From] == L' '))
  227. {
  228. From++;
  229. }
  230. }
  231. return Result;
  232. }
  233. //---------------------------------------------------------------------------
  234. UnicodeString DelimitStr(UnicodeString Str, UnicodeString Chars)
  235. {
  236. for (int i = 1; i <= Str.Length(); i++)
  237. {
  238. if (Str.IsDelimiter(Chars, i))
  239. {
  240. Str.Insert(L"\\", i);
  241. i++;
  242. }
  243. }
  244. return Str;
  245. }
  246. //---------------------------------------------------------------------------
  247. UnicodeString ShellDelimitStr(UnicodeString Str, wchar_t Quote)
  248. {
  249. UnicodeString Chars = L"$\\";
  250. if (Quote == L'"')
  251. {
  252. Chars += L"`\"";
  253. }
  254. return DelimitStr(Str, Chars);
  255. }
  256. //---------------------------------------------------------------------------
  257. UnicodeString ExceptionLogString(Exception *E)
  258. {
  259. assert(E);
  260. if (E->InheritsFrom(__classid(Exception)))
  261. {
  262. UnicodeString Msg;
  263. Msg = FORMAT(L"(%s) %s", (E->ClassName(), E->Message));
  264. if (E->InheritsFrom(__classid(ExtException)))
  265. {
  266. TStrings * MoreMessages = ((ExtException*)E)->MoreMessages;
  267. if (MoreMessages)
  268. {
  269. Msg += L"\n" +
  270. StringReplace(MoreMessages->Text, L"\r", L"", TReplaceFlags() << rfReplaceAll);
  271. }
  272. }
  273. return Msg;
  274. }
  275. else
  276. {
  277. wchar_t Buffer[1024];
  278. ExceptionErrorMessage(ExceptObject(), ExceptAddr(), Buffer, LENOF(Buffer));
  279. return UnicodeString(Buffer);
  280. }
  281. }
  282. //---------------------------------------------------------------------------
  283. bool IsNumber(const UnicodeString Str)
  284. {
  285. int Value;
  286. return TryStrToInt(Str, Value);
  287. }
  288. //---------------------------------------------------------------------------
  289. UnicodeString __fastcall SystemTemporaryDirectory()
  290. {
  291. UnicodeString TempDir;
  292. TempDir.SetLength(MAX_PATH);
  293. TempDir.SetLength(GetTempPath(MAX_PATH, TempDir.c_str()));
  294. return TempDir;
  295. }
  296. //---------------------------------------------------------------------------
  297. UnicodeString __fastcall GetShellFolderPath(int CSIdl)
  298. {
  299. UnicodeString Result;
  300. wchar_t Path[2 * MAX_PATH + 10] = L"\0";
  301. if (SUCCEEDED(SHGetFolderPath(NULL, CSIdl, NULL, SHGFP_TYPE_CURRENT, Path)))
  302. {
  303. Result = Path;
  304. }
  305. return Result;
  306. }
  307. //---------------------------------------------------------------------------
  308. UnicodeString __fastcall StripPathQuotes(const UnicodeString Path)
  309. {
  310. if ((Path.Length() >= 2) &&
  311. (Path[1] == L'\"') && (Path[Path.Length()] == L'\"'))
  312. {
  313. return Path.SubString(2, Path.Length() - 2);
  314. }
  315. else
  316. {
  317. return Path;
  318. }
  319. }
  320. //---------------------------------------------------------------------------
  321. UnicodeString __fastcall AddPathQuotes(UnicodeString Path)
  322. {
  323. Path = StripPathQuotes(Path);
  324. if (Path.Pos(L" "))
  325. {
  326. Path = L"\"" + Path + L"\"";
  327. }
  328. return Path;
  329. }
  330. //---------------------------------------------------------------------------
  331. static wchar_t * __fastcall ReplaceChar(
  332. UnicodeString & FileName, wchar_t * InvalidChar, wchar_t InvalidCharsReplacement)
  333. {
  334. int Index = InvalidChar - FileName.c_str() + 1;
  335. if (InvalidCharsReplacement == TokenReplacement)
  336. {
  337. // currently we do not support unicode chars replacement
  338. if (FileName[Index] > 0xFF)
  339. {
  340. EXCEPTION;
  341. }
  342. FileName.Insert(ByteToHex(static_cast<unsigned char>(FileName[Index])), Index + 1);
  343. FileName[Index] = TokenPrefix;
  344. InvalidChar = FileName.c_str() + Index + 2;
  345. }
  346. else
  347. {
  348. FileName[Index] = InvalidCharsReplacement;
  349. InvalidChar = FileName.c_str() + Index;
  350. }
  351. return InvalidChar;
  352. }
  353. //---------------------------------------------------------------------------
  354. UnicodeString __fastcall ValidLocalFileName(UnicodeString FileName)
  355. {
  356. return ValidLocalFileName(FileName, L'_', L"", LocalInvalidChars);
  357. }
  358. //---------------------------------------------------------------------------
  359. UnicodeString __fastcall ValidLocalFileName(
  360. UnicodeString FileName, wchar_t InvalidCharsReplacement,
  361. const UnicodeString & TokenizibleChars, const UnicodeString & LocalInvalidChars)
  362. {
  363. if (InvalidCharsReplacement != NoReplacement)
  364. {
  365. bool ATokenReplacement = (InvalidCharsReplacement == TokenReplacement);
  366. const wchar_t * Chars =
  367. (ATokenReplacement ? TokenizibleChars : LocalInvalidChars).c_str();
  368. wchar_t * InvalidChar = FileName.c_str();
  369. while ((InvalidChar = wcspbrk(InvalidChar, Chars)) != NULL)
  370. {
  371. int Pos = (InvalidChar - FileName.c_str() + 1);
  372. wchar_t Char;
  373. if (ATokenReplacement &&
  374. (*InvalidChar == TokenPrefix) &&
  375. (((FileName.Length() - Pos) <= 1) ||
  376. (((Char = static_cast<wchar_t>(HexToByte(FileName.SubString(Pos + 1, 2)))) == L'\0') ||
  377. (TokenizibleChars.Pos(Char) == 0))))
  378. {
  379. InvalidChar++;
  380. }
  381. else
  382. {
  383. InvalidChar = ReplaceChar(FileName, InvalidChar, InvalidCharsReplacement);
  384. }
  385. }
  386. // Windows trim trailing space or dot, hence we must encode it to preserve it
  387. if (!FileName.IsEmpty() &&
  388. ((FileName[FileName.Length()] == L' ') ||
  389. (FileName[FileName.Length()] == L'.')))
  390. {
  391. ReplaceChar(FileName, FileName.c_str() + FileName.Length() - 1, InvalidCharsReplacement);
  392. }
  393. if (IsReservedName(FileName))
  394. {
  395. int P = FileName.Pos(".");
  396. if (P == 0)
  397. {
  398. P = FileName.Length() + 1;
  399. }
  400. FileName.Insert(L"%00", P);
  401. }
  402. }
  403. return FileName;
  404. }
  405. //---------------------------------------------------------------------------
  406. void __fastcall SplitCommand(UnicodeString Command, UnicodeString &Program,
  407. UnicodeString & Params, UnicodeString & Dir)
  408. {
  409. Command = Command.Trim();
  410. Params = L"";
  411. Dir = L"";
  412. if (!Command.IsEmpty() && (Command[1] == L'\"'))
  413. {
  414. Command.Delete(1, 1);
  415. int P = Command.Pos(L'"');
  416. if (P)
  417. {
  418. Program = Command.SubString(1, P-1).Trim();
  419. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  420. }
  421. else
  422. {
  423. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, (L"\"" + Command)));
  424. }
  425. }
  426. else
  427. {
  428. int P = Command.Pos(L" ");
  429. if (P)
  430. {
  431. Program = Command.SubString(1, P).Trim();
  432. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  433. }
  434. else
  435. {
  436. Program = Command;
  437. }
  438. }
  439. int B = Program.LastDelimiter(L"\\/");
  440. if (B)
  441. {
  442. Dir = Program.SubString(1, B).Trim();
  443. }
  444. }
  445. //---------------------------------------------------------------------------
  446. UnicodeString __fastcall ExtractProgram(UnicodeString Command)
  447. {
  448. UnicodeString Program;
  449. UnicodeString Params;
  450. UnicodeString Dir;
  451. SplitCommand(Command, Program, Params, Dir);
  452. return Program;
  453. }
  454. //---------------------------------------------------------------------------
  455. UnicodeString __fastcall FormatCommand(UnicodeString Program, UnicodeString Params)
  456. {
  457. Program = Program.Trim();
  458. Params = Params.Trim();
  459. if (!Params.IsEmpty()) Params = L" " + Params;
  460. if (Program.Pos(L" ")) Program = L"\"" + Program + L"\"";
  461. return Program + Params;
  462. }
  463. //---------------------------------------------------------------------------
  464. const wchar_t ShellCommandFileNamePattern[] = L"!.!";
  465. //---------------------------------------------------------------------------
  466. void __fastcall ReformatFileNameCommand(UnicodeString & Command)
  467. {
  468. if (!Command.IsEmpty())
  469. {
  470. UnicodeString Program, Params, Dir;
  471. SplitCommand(Command, Program, Params, Dir);
  472. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  473. {
  474. Params = Params + (Params.IsEmpty() ? L"" : L" ") + ShellCommandFileNamePattern;
  475. }
  476. Command = FormatCommand(Program, Params);
  477. }
  478. }
  479. //---------------------------------------------------------------------------
  480. UnicodeString __fastcall ExpandFileNameCommand(const UnicodeString Command,
  481. const UnicodeString FileName)
  482. {
  483. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  484. AddPathQuotes(FileName));
  485. }
  486. //---------------------------------------------------------------------------
  487. UnicodeString __fastcall EscapePuttyCommandParam(UnicodeString Param)
  488. {
  489. bool Space = false;
  490. for (int i = 1; i <= Param.Length(); i++)
  491. {
  492. switch (Param[i])
  493. {
  494. case L'"':
  495. Param.Insert(L"\\", i);
  496. i++;
  497. break;
  498. case L' ':
  499. Space = true;
  500. break;
  501. case L'\\':
  502. int i2 = i;
  503. while ((i2 <= Param.Length()) && (Param[i2] == L'\\'))
  504. {
  505. i2++;
  506. }
  507. if ((i2 <= Param.Length()) && (Param[i2] == L'"'))
  508. {
  509. while (Param[i] == L'\\')
  510. {
  511. Param.Insert(L"\\", i);
  512. i += 2;
  513. }
  514. i--;
  515. }
  516. break;
  517. }
  518. }
  519. if (Space)
  520. {
  521. Param = L"\"" + Param + L'"';
  522. }
  523. return Param;
  524. }
  525. //---------------------------------------------------------------------------
  526. UnicodeString __fastcall ExpandEnvironmentVariables(const UnicodeString & Str)
  527. {
  528. UnicodeString Buf;
  529. unsigned int Size = 1024;
  530. Buf.SetLength(Size);
  531. Buf.Unique();
  532. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  533. if (Len > Size)
  534. {
  535. Buf.SetLength(Len);
  536. Buf.Unique();
  537. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  538. }
  539. PackStr(Buf);
  540. return Buf;
  541. }
  542. //---------------------------------------------------------------------------
  543. bool __fastcall CompareFileName(const UnicodeString & Path1, const UnicodeString & Path2)
  544. {
  545. UnicodeString ShortPath1 = ExtractShortPathName(Path1);
  546. UnicodeString ShortPath2 = ExtractShortPathName(Path2);
  547. bool Result;
  548. // ExtractShortPathName returns empty string if file does not exist
  549. if (ShortPath1.IsEmpty() || ShortPath2.IsEmpty())
  550. {
  551. Result = AnsiSameText(Path1, Path2);
  552. }
  553. else
  554. {
  555. Result = AnsiSameText(ShortPath1, ShortPath2);
  556. }
  557. return Result;
  558. }
  559. //---------------------------------------------------------------------------
  560. bool __fastcall ComparePaths(const UnicodeString & Path1, const UnicodeString & Path2)
  561. {
  562. // TODO: ExpandUNCFileName
  563. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  564. }
  565. //---------------------------------------------------------------------------
  566. bool __fastcall IsReservedName(UnicodeString FileName)
  567. {
  568. int P = FileName.Pos(L".");
  569. int Len = (P > 0) ? P - 1 : FileName.Length();
  570. if ((Len == 3) || (Len == 4))
  571. {
  572. if (P > 0)
  573. {
  574. FileName.SetLength(P - 1);
  575. }
  576. static UnicodeString Reserved[] = {
  577. L"CON", L"PRN", L"AUX", L"NUL",
  578. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  579. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  580. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  581. {
  582. if (SameText(FileName, Reserved[Index]))
  583. {
  584. return true;
  585. }
  586. }
  587. }
  588. return false;
  589. }
  590. //---------------------------------------------------------------------------
  591. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  592. {
  593. bool Displayable = true;
  594. int Index = 1;
  595. while ((Index <= Str.Length()) && Displayable)
  596. {
  597. if (((Str[Index] < '\x20') || (static_cast<unsigned char>(Str[Index]) >= static_cast<unsigned char>('\x80'))) &&
  598. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  599. {
  600. Displayable = false;
  601. }
  602. Index++;
  603. }
  604. UnicodeString Result;
  605. if (Displayable)
  606. {
  607. Result = L"\"";
  608. for (int Index = 1; Index <= Str.Length(); Index++)
  609. {
  610. switch (Str[Index])
  611. {
  612. case '\n':
  613. Result += L"\\n";
  614. break;
  615. case '\r':
  616. Result += L"\\r";
  617. break;
  618. case '\t':
  619. Result += L"\\t";
  620. break;
  621. case '\b':
  622. Result += L"\\b";
  623. break;
  624. case '\\':
  625. Result += L"\\\\";
  626. break;
  627. case '"':
  628. Result += L"\\\"";
  629. break;
  630. default:
  631. Result += wchar_t(Str[Index]);
  632. break;
  633. }
  634. }
  635. Result += L"\"";
  636. }
  637. else
  638. {
  639. Result = L"0x" + BytesToHex(Str);
  640. }
  641. return Result;
  642. }
  643. //---------------------------------------------------------------------------
  644. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  645. {
  646. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  647. static wchar_t LowerDigits[] = L"0123456789abcdef";
  648. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  649. UnicodeString Result;
  650. Result.SetLength(2);
  651. Result[1] = Digits[(B & 0xF0) >> 4];
  652. Result[2] = Digits[(B & 0x0F) >> 0];
  653. return Result;
  654. }
  655. //---------------------------------------------------------------------------
  656. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  657. {
  658. UnicodeString Result;
  659. for (size_t i = 0; i < Length; i++)
  660. {
  661. Result += ByteToHex(B[i], UpperCase);
  662. if ((Separator != L'\0') && (i < Length - 1))
  663. {
  664. Result += Separator;
  665. }
  666. }
  667. return Result;
  668. }
  669. //---------------------------------------------------------------------------
  670. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  671. {
  672. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  673. }
  674. //---------------------------------------------------------------------------
  675. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  676. {
  677. return BytesToHex(reinterpret_cast<const unsigned char *>(&Ch), sizeof(Ch), UpperCase);
  678. }
  679. //---------------------------------------------------------------------------
  680. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  681. {
  682. static UnicodeString Digits = L"0123456789ABCDEF";
  683. RawByteString Result;
  684. int L, P1, P2;
  685. L = Hex.Length();
  686. if (L % 2 == 0)
  687. {
  688. for (int i = 1; i <= Hex.Length(); i += 2)
  689. {
  690. P1 = Digits.Pos((wchar_t)toupper(Hex[i]));
  691. P2 = Digits.Pos((wchar_t)toupper(Hex[i + 1]));
  692. if (P1 <= 0 || P2 <= 0)
  693. {
  694. Result = L"";
  695. break;
  696. }
  697. else
  698. {
  699. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  700. }
  701. }
  702. }
  703. return Result;
  704. }
  705. //---------------------------------------------------------------------------
  706. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  707. {
  708. static UnicodeString Digits = L"0123456789ABCDEF";
  709. assert(Hex.Length() == 2);
  710. int P1 = Digits.Pos((wchar_t)toupper(Hex[1]));
  711. int P2 = Digits.Pos((wchar_t)toupper(Hex[2]));
  712. return
  713. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  714. }
  715. //---------------------------------------------------------------------------
  716. int __fastcall FindCheck(int Result)
  717. {
  718. if ((Result != ERROR_SUCCESS) &&
  719. (Result != ERROR_FILE_NOT_FOUND) &&
  720. (Result != ERROR_NO_MORE_FILES))
  721. {
  722. RaiseLastOSError(Result);
  723. }
  724. return Result;
  725. }
  726. //---------------------------------------------------------------------------
  727. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRec & F)
  728. {
  729. return FindCheck(FindFirst(Path, Attr, F));
  730. }
  731. //---------------------------------------------------------------------------
  732. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  733. // I.e. even if we do not care that FindFirst failed, if FindNext
  734. // failes after successfull FindFirst, it mean some terrible problem
  735. int __fastcall FindNextChecked(TSearchRec & F)
  736. {
  737. return FindCheck(FindNext(F));
  738. }
  739. //---------------------------------------------------------------------------
  740. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  741. {
  742. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  743. bool Result = (FindFirst(FileName, FindAttrs, Rec) == 0);
  744. if (Result)
  745. {
  746. FindClose(Rec);
  747. }
  748. return Result;
  749. }
  750. //---------------------------------------------------------------------------
  751. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  752. TProcessLocalFileEvent CallBackFunc, void * Param,
  753. int FindAttrs)
  754. {
  755. assert(CallBackFunc);
  756. if (FindAttrs < 0)
  757. {
  758. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  759. }
  760. TSearchRec SearchRec;
  761. DirName = IncludeTrailingBackslash(DirName);
  762. if (FindFirstChecked(DirName + L"*.*", FindAttrs, SearchRec) == 0)
  763. {
  764. try
  765. {
  766. do
  767. {
  768. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  769. {
  770. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  771. }
  772. } while (FindNextChecked(SearchRec) == 0);
  773. }
  774. __finally
  775. {
  776. FindClose(SearchRec);
  777. }
  778. }
  779. }
  780. //---------------------------------------------------------------------------
  781. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  782. {
  783. try
  784. {
  785. TDateTime DateTime = EncodeDate(Year, Month, Day);
  786. return DateTime;
  787. }
  788. catch (EConvertError & E)
  789. {
  790. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  791. }
  792. }
  793. //---------------------------------------------------------------------------
  794. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  795. {
  796. try
  797. {
  798. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  799. return DateTime;
  800. }
  801. catch (EConvertError & E)
  802. {
  803. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  804. }
  805. }
  806. //---------------------------------------------------------------------------
  807. struct TDateTimeParams
  808. {
  809. TDateTime UnixEpoch;
  810. double BaseDifference;
  811. long BaseDifferenceSec;
  812. // All Current* are actually global, not per-year
  813. double CurrentDaylightDifference;
  814. long CurrentDaylightDifferenceSec;
  815. double CurrentDifference;
  816. long CurrentDifferenceSec;
  817. double StandardDifference;
  818. long StandardDifferenceSec;
  819. double DaylightDifference;
  820. long DaylightDifferenceSec;
  821. SYSTEMTIME SystemStandardDate;
  822. SYSTEMTIME SystemDaylightDate;
  823. TDateTime StandardDate;
  824. TDateTime DaylightDate;
  825. bool SummerDST;
  826. // This is actually global, not per-year
  827. bool DaylightHack;
  828. };
  829. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  830. static TYearlyDateTimeParams YearlyDateTimeParams;
  831. static std::auto_ptr<TCriticalSection> DateTimeParamsSection(new TCriticalSection());
  832. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  833. TDateTime & Result);
  834. //---------------------------------------------------------------------------
  835. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  836. {
  837. unsigned short Year, Month, Day;
  838. DecodeDate(DateTime, Year, Month, Day);
  839. return Year;
  840. }
  841. //---------------------------------------------------------------------------
  842. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  843. {
  844. TGuard Guard(DateTimeParamsSection.get());
  845. TDateTimeParams * Result;
  846. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  847. if (i != YearlyDateTimeParams.end())
  848. {
  849. Result = &(*i).second;
  850. }
  851. else
  852. {
  853. // creates new entry as a side effect
  854. Result = &YearlyDateTimeParams[Year];
  855. TIME_ZONE_INFORMATION TZI;
  856. unsigned long GTZI;
  857. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  858. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  859. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  860. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  861. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  862. {
  863. GTZI = GetTimeZoneInformation(&TZI);
  864. }
  865. else
  866. {
  867. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  868. GTZI = TIME_ZONE_ID_UNKNOWN;
  869. }
  870. switch (GTZI)
  871. {
  872. case TIME_ZONE_ID_UNKNOWN:
  873. Result->CurrentDaylightDifferenceSec = 0;
  874. break;
  875. case TIME_ZONE_ID_STANDARD:
  876. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  877. break;
  878. case TIME_ZONE_ID_DAYLIGHT:
  879. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  880. break;
  881. case TIME_ZONE_ID_INVALID:
  882. default:
  883. throw Exception(TIMEZONE_ERROR);
  884. }
  885. Result->BaseDifferenceSec = TZI.Bias;
  886. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  887. Result->BaseDifferenceSec *= SecsPerMin;
  888. Result->CurrentDifferenceSec = TZI.Bias +
  889. Result->CurrentDaylightDifferenceSec;
  890. Result->CurrentDifference =
  891. double(Result->CurrentDifferenceSec) / MinsPerDay;
  892. Result->CurrentDifferenceSec *= SecsPerMin;
  893. Result->CurrentDaylightDifference =
  894. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  895. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  896. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  897. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  898. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  899. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  900. Result->SystemStandardDate = TZI.StandardDate;
  901. Result->SystemDaylightDate = TZI.DaylightDate;
  902. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  903. if (Result->SystemStandardDate.wMonth != 0)
  904. {
  905. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  906. }
  907. if (Result->SystemDaylightDate.wMonth != 0)
  908. {
  909. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  910. }
  911. Result->SummerDST = (Result->DaylightDate < Result->StandardDate);
  912. Result->DaylightHack = !IsWin7() || IsExactly2008R2();
  913. }
  914. return Result;
  915. }
  916. //---------------------------------------------------------------------------
  917. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  918. TDateTime & Result)
  919. {
  920. if (Date.wYear == 0)
  921. {
  922. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  923. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  924. (7 * (Date.wDay - 1));
  925. if (Date.wDay == 5)
  926. {
  927. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  928. if (Month > 12)
  929. {
  930. Month = static_cast<unsigned short>(Month - 12);
  931. Year++;
  932. }
  933. if (Result >= EncodeDateVerbose(Year, Month, 1))
  934. {
  935. Result -= 7;
  936. }
  937. }
  938. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  939. Date.wMilliseconds);
  940. }
  941. else
  942. {
  943. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  944. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  945. }
  946. }
  947. //---------------------------------------------------------------------------
  948. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  949. {
  950. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  951. bool Result;
  952. // On some systems it occurs that StandardDate is unset, while
  953. // DaylightDate is set. MSDN states that this is invalid and
  954. // should be treated as if there is no daylight saving.
  955. // So check both.
  956. if ((Params->SystemStandardDate.wMonth == 0) ||
  957. (Params->SystemDaylightDate.wMonth == 0))
  958. {
  959. Result = false;
  960. }
  961. else
  962. {
  963. if (Params->SummerDST)
  964. {
  965. Result =
  966. (DateTime >= Params->DaylightDate) &&
  967. (DateTime < Params->StandardDate);
  968. }
  969. else
  970. {
  971. Result =
  972. (DateTime < Params->StandardDate) ||
  973. (DateTime >= Params->DaylightDate);
  974. }
  975. }
  976. return Result;
  977. }
  978. //---------------------------------------------------------------------------
  979. bool __fastcall UsesDaylightHack()
  980. {
  981. return GetDateTimeParams(0)->DaylightHack;
  982. }
  983. //---------------------------------------------------------------------------
  984. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  985. {
  986. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  987. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  988. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  989. if (Params->DaylightHack)
  990. {
  991. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  992. {
  993. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  994. Result -= CurrentParams->CurrentDifference;
  995. }
  996. else if (DSTMode == dstmKeep)
  997. {
  998. Result -= Params->BaseDifference;
  999. }
  1000. }
  1001. else
  1002. {
  1003. Result -= Params->BaseDifference;
  1004. }
  1005. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1006. {
  1007. Result -= (IsDateInDST(Result) ?
  1008. Params->DaylightDifference : Params->StandardDifference);
  1009. }
  1010. return Result;
  1011. }
  1012. //---------------------------------------------------------------------------
  1013. __int64 __fastcall Round(double Number)
  1014. {
  1015. double Floor = floor(Number);
  1016. double Ceil = ceil(Number);
  1017. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime)
  1021. {
  1022. S = S.Trim();
  1023. int Index = 1;
  1024. while ((Index <= S.Length()) && (S[Index] >= '0') && (S[Index] <= '9'))
  1025. {
  1026. Index++;
  1027. }
  1028. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1029. int Number;
  1030. bool Result = TryStrToInt(NumberStr, Number);
  1031. if (Result)
  1032. {
  1033. S.Delete(1, Index - 1);
  1034. S = S.Trim().UpperCase();
  1035. DateTime = Now();
  1036. // These may not overlap with ParseSize (K, M and G)
  1037. if (S == "S")
  1038. {
  1039. DateTime = IncSecond(DateTime, -Number);
  1040. }
  1041. else if (S == "N")
  1042. {
  1043. DateTime = IncMinute(DateTime, -Number);
  1044. }
  1045. else if (S == "H")
  1046. {
  1047. DateTime = IncHour(DateTime, -Number);
  1048. }
  1049. else if (S == "D")
  1050. {
  1051. DateTime = IncDay(DateTime, -Number);
  1052. }
  1053. else if (S == "Y")
  1054. {
  1055. DateTime = IncYear(DateTime, -Number);
  1056. }
  1057. else
  1058. {
  1059. Result = false;
  1060. }
  1061. }
  1062. return Result;
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1066. {
  1067. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1068. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1069. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1070. CurrentParams->CurrentDifferenceSec;
  1071. }
  1072. //---------------------------------------------------------------------------
  1073. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1074. TDSTMode /*DSTMode*/)
  1075. {
  1076. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1077. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1078. if (!Params->DaylightHack)
  1079. {
  1080. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1081. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1082. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1083. UnixTimeStamp -= CurrentParams->CurrentDaylightDifferenceSec;
  1084. }
  1085. FILETIME Result;
  1086. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1087. return Result;
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1091. {
  1092. // duplicated in DirView.pas
  1093. SYSTEMTIME SysTime;
  1094. if (!UsesDaylightHack())
  1095. {
  1096. SYSTEMTIME UniverzalSysTime;
  1097. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1098. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1099. }
  1100. else
  1101. {
  1102. FILETIME LocalFileTime;
  1103. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1104. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1105. }
  1106. TDateTime Result = SystemTimeToDateTime(SysTime);
  1107. return Result;
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1111. TDSTMode DSTMode)
  1112. {
  1113. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1114. if (UsesDaylightHack())
  1115. {
  1116. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1117. {
  1118. FILETIME LocalFileTime;
  1119. SYSTEMTIME SystemTime;
  1120. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1121. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1122. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1123. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1124. Result += (IsDateInDST(DateTime) ?
  1125. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1126. if (DSTMode == dstmKeep)
  1127. {
  1128. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1129. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1130. }
  1131. }
  1132. }
  1133. else
  1134. {
  1135. if (DSTMode == dstmWin)
  1136. {
  1137. FILETIME LocalFileTime;
  1138. SYSTEMTIME SystemTime;
  1139. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1140. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1141. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1142. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1143. Result -= (IsDateInDST(DateTime) ?
  1144. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1145. }
  1146. }
  1147. return Result;
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1151. {
  1152. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1153. DateTime +=
  1154. (IsDateInDST(DateTime) ?
  1155. Params->DaylightDifference : Params->StandardDifference);
  1156. DateTime += Params->BaseDifference;
  1157. if (Params->DaylightHack)
  1158. {
  1159. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1160. DateTime += CurrentParams->CurrentDaylightDifference;
  1161. }
  1162. return DateTime;
  1163. }
  1164. //---------------------------------------------------------------------------
  1165. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1166. {
  1167. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1168. DateTime -=
  1169. (IsDateInDST(DateTime) ?
  1170. Params->DaylightDifference : Params->StandardDifference);
  1171. DateTime -= Params->BaseDifference;
  1172. if (Params->DaylightHack)
  1173. {
  1174. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1175. DateTime -= CurrentParams->CurrentDaylightDifference;
  1176. }
  1177. return DateTime;
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1181. TDSTMode DSTMode)
  1182. {
  1183. __int64 Result;
  1184. if ((FileTime.dwLowDateTime == 0) &&
  1185. (FileTime.dwHighDateTime == 0))
  1186. {
  1187. Result = ::DateTimeToUnix(Now());
  1188. }
  1189. else
  1190. {
  1191. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1192. }
  1193. return Result;
  1194. }
  1195. //---------------------------------------------------------------------------
  1196. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1197. {
  1198. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1199. if (Params->DaylightHack)
  1200. {
  1201. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1202. {
  1203. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1204. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  1205. }
  1206. if (!IsDateInDST(DateTime))
  1207. {
  1208. if (DSTMode == dstmWin)
  1209. {
  1210. DateTime = DateTime - Params->DaylightDifference;
  1211. }
  1212. }
  1213. else
  1214. {
  1215. DateTime = DateTime - Params->StandardDifference;
  1216. }
  1217. }
  1218. else
  1219. {
  1220. if (DSTMode == dstmWin)
  1221. {
  1222. if (IsDateInDST(DateTime))
  1223. {
  1224. DateTime = DateTime + Params->DaylightDifference;
  1225. }
  1226. else
  1227. {
  1228. DateTime = DateTime + Params->StandardDifference;
  1229. }
  1230. }
  1231. }
  1232. return DateTime;
  1233. }
  1234. //---------------------------------------------------------------------------
  1235. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  1236. {
  1237. UnicodeString Result = Format;
  1238. bool AsIs = false;
  1239. int Index = 1;
  1240. while (Index <= Result.Length())
  1241. {
  1242. wchar_t F = Result[Index];
  1243. if ((F == L'\'') || (F == L'\"'))
  1244. {
  1245. AsIs = !AsIs;
  1246. Index++;
  1247. }
  1248. else if (!AsIs && ((F == L'a') || (F == L'A')))
  1249. {
  1250. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  1251. {
  1252. Index += 5;
  1253. }
  1254. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  1255. {
  1256. Index += 3;
  1257. }
  1258. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  1259. {
  1260. Index += 4;
  1261. }
  1262. else
  1263. {
  1264. Index++;
  1265. }
  1266. }
  1267. else
  1268. {
  1269. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  1270. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1271. {
  1272. Result.Insert(F, Index);
  1273. }
  1274. while ((Index <= Result.Length()) && (F == Result[Index]))
  1275. {
  1276. Index++;
  1277. }
  1278. }
  1279. }
  1280. return Result;
  1281. }
  1282. //---------------------------------------------------------------------------
  1283. static UnicodeString __fastcall FormatTimeZone(long Sec)
  1284. {
  1285. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  1286. UnicodeString Str;
  1287. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  1288. {
  1289. Str = FORMAT(L"%d", (-Span.Hours));
  1290. }
  1291. else if (Span.Seconds == 0)
  1292. {
  1293. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  1294. }
  1295. else
  1296. {
  1297. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  1298. }
  1299. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  1300. return Str;
  1301. }
  1302. //---------------------------------------------------------------------------
  1303. UnicodeString __fastcall GetTimeZoneLogString()
  1304. {
  1305. const TDateTimeParams * Params = GetDateTimeParams(0);
  1306. UnicodeString Result =
  1307. FORMAT("Current: GMT%s, Standard: GMT%s, DST: GMT%s, DST Start: %s, DST End: %s",
  1308. (FormatTimeZone(Params->CurrentDifferenceSec),
  1309. FormatTimeZone(Params->BaseDifferenceSec + Params->StandardDifferenceSec),
  1310. FormatTimeZone(Params->BaseDifferenceSec + Params->DaylightDifferenceSec),
  1311. Params->DaylightDate.DateString(),
  1312. Params->StandardDate.DateString()));
  1313. return Result;
  1314. }
  1315. //---------------------------------------------------------------------------
  1316. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  1317. {
  1318. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  1319. }
  1320. //---------------------------------------------------------------------------
  1321. UnicodeString __fastcall StandardTimestamp()
  1322. {
  1323. return StandardTimestamp(Now());
  1324. }
  1325. //---------------------------------------------------------------------------
  1326. static TDateTime TwoSeconds(0, 0, 2, 0);
  1327. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1328. {
  1329. // "FAT" time precision
  1330. // (when one time is seconds-precision and other is millisecond-precision,
  1331. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1332. // be treated the same)
  1333. int Result;
  1334. if (T1 == T2)
  1335. {
  1336. // just optimization
  1337. Result = 0;
  1338. }
  1339. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1340. {
  1341. Result = -1;
  1342. }
  1343. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1344. {
  1345. Result = 1;
  1346. }
  1347. else
  1348. {
  1349. Result = 0;
  1350. }
  1351. return Result;
  1352. }
  1353. //---------------------------------------------------------------------------
  1354. int __fastcall TimeToMSec(TDateTime T)
  1355. {
  1356. return int(Round(double(T) * double(MSecsPerDay)));
  1357. }
  1358. //---------------------------------------------------------------------------
  1359. int __fastcall TimeToMinutes(TDateTime T)
  1360. {
  1361. return TimeToMSec(T) / MSecsPerSec / SecsPerMin;
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. bool __fastcall RecursiveDeleteFile(const UnicodeString FileName, bool ToRecycleBin)
  1365. {
  1366. SHFILEOPSTRUCT Data;
  1367. memset(&Data, 0, sizeof(Data));
  1368. Data.hwnd = NULL;
  1369. Data.wFunc = FO_DELETE;
  1370. UnicodeString FileList(FileName);
  1371. FileList.SetLength(FileList.Length() + 2);
  1372. FileList[FileList.Length() - 1] = L'\0';
  1373. FileList[FileList.Length()] = L'\0';
  1374. Data.pFrom = FileList.c_str();
  1375. Data.pTo = L"";
  1376. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1377. FOF_NOERRORUI | FOF_SILENT;
  1378. if (ToRecycleBin)
  1379. {
  1380. Data.fFlags |= FOF_ALLOWUNDO;
  1381. }
  1382. int ErrorCode = SHFileOperation(&Data);
  1383. bool Result = (ErrorCode == 0);
  1384. if (!Result)
  1385. {
  1386. // according to MSDN, SHFileOperation may return following non-Win32
  1387. // error codes
  1388. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  1389. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  1390. (ErrorCode == 0x10074))
  1391. {
  1392. ErrorCode = 0;
  1393. }
  1394. SetLastError(ErrorCode);
  1395. }
  1396. return Result;
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  1400. {
  1401. unsigned int Result;
  1402. if ((Answers & qaCancel) != 0)
  1403. {
  1404. Result = qaCancel;
  1405. }
  1406. else if ((Answers & qaNo) != 0)
  1407. {
  1408. Result = qaNo;
  1409. }
  1410. else if ((Answers & qaAbort) != 0)
  1411. {
  1412. Result = qaAbort;
  1413. }
  1414. else if ((Answers & qaOK) != 0)
  1415. {
  1416. Result = qaOK;
  1417. }
  1418. else
  1419. {
  1420. assert(false);
  1421. Result = qaCancel;
  1422. }
  1423. return Result;
  1424. }
  1425. //---------------------------------------------------------------------------
  1426. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  1427. {
  1428. unsigned int Result;
  1429. if (FLAGSET(Answers, qaAbort))
  1430. {
  1431. Result = qaAbort;
  1432. }
  1433. else
  1434. {
  1435. Result = CancelAnswer(Answers);
  1436. }
  1437. return Result;
  1438. }
  1439. //---------------------------------------------------------------------------
  1440. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  1441. {
  1442. unsigned int Result;
  1443. if (FLAGSET(Answers, qaSkip))
  1444. {
  1445. Result = qaSkip;
  1446. }
  1447. else if (FLAGSET(Answers, qaIgnore))
  1448. {
  1449. Result = qaIgnore;
  1450. }
  1451. else if (FLAGSET(Answers, qaYes))
  1452. {
  1453. Result = qaYes;
  1454. }
  1455. else if (FLAGSET(Answers, qaOK))
  1456. {
  1457. Result = qaOK;
  1458. }
  1459. else if (FLAGSET(Answers, qaRetry))
  1460. {
  1461. Result = qaRetry;
  1462. }
  1463. else
  1464. {
  1465. Result = CancelAnswer(Answers);
  1466. }
  1467. return Result;
  1468. }
  1469. //---------------------------------------------------------------------------
  1470. TLibModule * __fastcall FindModule(void * Instance)
  1471. {
  1472. TLibModule * CurModule;
  1473. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  1474. while (CurModule)
  1475. {
  1476. if (CurModule->Instance == (unsigned)Instance)
  1477. {
  1478. break;
  1479. }
  1480. else
  1481. {
  1482. CurModule = CurModule->Next;
  1483. }
  1484. }
  1485. return CurModule;
  1486. }
  1487. //---------------------------------------------------------------------------
  1488. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  1489. {
  1490. TLibModule * MainModule = FindModule(HInstance);
  1491. assert(MainModule != NULL);
  1492. UnicodeString Result;
  1493. Result.SetLength(MaxLength);
  1494. int Length = LoadString((HINSTANCE)MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  1495. Result.SetLength(Length);
  1496. return Result;
  1497. }
  1498. //---------------------------------------------------------------------------
  1499. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  1500. {
  1501. UnicodeString Result;
  1502. UnicodeString Str = LoadStr(Ident);
  1503. while (Part > 0)
  1504. {
  1505. Result = CutToChar(Str, L'|', false);
  1506. Part--;
  1507. }
  1508. return Result;
  1509. }
  1510. //---------------------------------------------------------------------------
  1511. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  1512. {
  1513. int i = 1;
  1514. while (i <= S.Length())
  1515. {
  1516. switch (S[i])
  1517. {
  1518. case L'+':
  1519. S[i] = ' ';
  1520. break;
  1521. case L'%':
  1522. if (i <= S.Length() - 2)
  1523. {
  1524. unsigned char B = HexToByte(S.SubString(i + 1, 2));
  1525. if (B > 0)
  1526. {
  1527. S[i] = (wchar_t)B;
  1528. S.Delete(i + 1, 2);
  1529. }
  1530. }
  1531. break;
  1532. }
  1533. i++;
  1534. }
  1535. return S;
  1536. }
  1537. //---------------------------------------------------------------------------
  1538. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, UnicodeString Chars)
  1539. {
  1540. int i = 1;
  1541. while (i <= S.Length())
  1542. {
  1543. if (Chars.Pos(S[i]) > 0)
  1544. {
  1545. UnicodeString H = ByteToHex(AnsiString(UnicodeString(S[i]))[1]);
  1546. S.Insert(H, i + 1);
  1547. S[i] = '%';
  1548. i += H.Length();
  1549. }
  1550. i++;
  1551. }
  1552. return S;
  1553. }
  1554. //---------------------------------------------------------------------------
  1555. UnicodeString __fastcall EncodeUrlChars(UnicodeString S, UnicodeString Ignore)
  1556. {
  1557. UnicodeString Chars;
  1558. if (Ignore.Pos(L' ') == 0)
  1559. {
  1560. Chars += L' ';
  1561. }
  1562. if (Ignore.Pos(L'/') == 0)
  1563. {
  1564. Chars += L'/';
  1565. }
  1566. return DoEncodeUrl(S, Chars);
  1567. }
  1568. //---------------------------------------------------------------------------
  1569. UnicodeString __fastcall NonUrlChars()
  1570. {
  1571. UnicodeString S;
  1572. for (unsigned int I = 0; I <= 127; I++)
  1573. {
  1574. wchar_t C = static_cast<wchar_t>(I);
  1575. if (((C >= L'a') && (C <= L'z')) ||
  1576. ((C >= L'A') && (C <= L'Z')) ||
  1577. ((C >= L'0') && (C <= L'9')) ||
  1578. (C == L'_') || (C == L'-') || (C == L'.'))
  1579. {
  1580. // noop
  1581. }
  1582. else
  1583. {
  1584. S += C;
  1585. }
  1586. }
  1587. return S;
  1588. }
  1589. //---------------------------------------------------------------------------
  1590. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  1591. {
  1592. return DoEncodeUrl(S, NonUrlChars());
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  1596. {
  1597. return StringReplace(Caption, L"&", L"&&", TReplaceFlags() << rfReplaceAll);
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. // duplicated in console's Main.cpp
  1601. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  1602. UnicodeString * RawToken)
  1603. {
  1604. bool Result;
  1605. Token = L"";
  1606. // inspired by Putty's sftp_getcmd() from PSFTP.C
  1607. int Index = 1;
  1608. while ((Index <= Str.Length()) &&
  1609. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  1610. {
  1611. Index++;
  1612. }
  1613. if (Index <= Str.Length())
  1614. {
  1615. bool Quoting = false;
  1616. while (Index <= Str.Length())
  1617. {
  1618. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  1619. {
  1620. break;
  1621. }
  1622. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  1623. (Str[Index + 1] == L'"'))
  1624. {
  1625. Index += 2;
  1626. Token += L'"';
  1627. }
  1628. else if (Str[Index] == L'"')
  1629. {
  1630. Index++;
  1631. Quoting = !Quoting;
  1632. }
  1633. else
  1634. {
  1635. Token += Str[Index];
  1636. Index++;
  1637. }
  1638. }
  1639. if (RawToken != NULL)
  1640. {
  1641. (*RawToken) = Str.SubString(1, Index - 1);
  1642. }
  1643. if (Index <= Str.Length())
  1644. {
  1645. Index++;
  1646. }
  1647. Str = Str.SubString(Index, Str.Length());
  1648. Result = true;
  1649. }
  1650. else
  1651. {
  1652. Result = false;
  1653. Str = L"";
  1654. }
  1655. return Result;
  1656. }
  1657. //---------------------------------------------------------------------------
  1658. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  1659. {
  1660. if (!Value.IsEmpty())
  1661. {
  1662. if (!List.IsEmpty() &&
  1663. ((List.Length() < Delimiter.Length()) ||
  1664. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  1665. {
  1666. List += Delimiter;
  1667. }
  1668. List += Value;
  1669. }
  1670. }
  1671. //---------------------------------------------------------------------------
  1672. bool __fastcall Is2000()
  1673. {
  1674. return (Win32MajorVersion >= 5);
  1675. }
  1676. //---------------------------------------------------------------------------
  1677. bool __fastcall IsWin7()
  1678. {
  1679. return
  1680. (Win32MajorVersion > 6) ||
  1681. ((Win32MajorVersion == 6) && (Win32MinorVersion >= 1));
  1682. }
  1683. //---------------------------------------------------------------------------
  1684. bool __fastcall IsExactly2008R2()
  1685. {
  1686. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1687. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  1688. TGetProductInfo GetProductInfo =
  1689. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  1690. bool Result;
  1691. if (GetProductInfo == NULL)
  1692. {
  1693. Result = false;
  1694. }
  1695. else
  1696. {
  1697. DWORD Type;
  1698. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  1699. switch (Type)
  1700. {
  1701. case 0x0008 /*PRODUCT_DATACENTER_SERVER*/:
  1702. case 0x000C /*PRODUCT_DATACENTER_SERVER_CORE}*/:
  1703. case 0x0027 /*PRODUCT_DATACENTER_SERVER_CORE_V*/:
  1704. case 0x0025 /*PRODUCT_DATACENTER_SERVER_V*/:
  1705. case 0x000A /*PRODUCT_ENTERPRISE_SERVE*/:
  1706. case 0x000E /*PRODUCT_ENTERPRISE_SERVER_COR*/:
  1707. case 0x0029 /*PRODUCT_ENTERPRISE_SERVER_CORE_*/:
  1708. case 0x000F /*PRODUCT_ENTERPRISE_SERVER_IA6*/:
  1709. case 0x0026 /*PRODUCT_ENTERPRISE_SERVER_*/:
  1710. case 0x002A /*PRODUCT_HYPER*/:
  1711. case 0x001E /*PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMEN*/:
  1712. case 0x0020 /*PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGIN*/:
  1713. case 0x001F /*PRODUCT_MEDIUMBUSINESS_SERVER_SECURIT*/:
  1714. case 0x0018 /*PRODUCT_SERVER_FOR_SMALLBUSINES*/:
  1715. case 0x0023 /*PRODUCT_SERVER_FOR_SMALLBUSINESS_*/:
  1716. case 0x0021 /*PRODUCT_SERVER_FOUNDATIO*/:
  1717. case 0x0009 /*PRODUCT_SMALLBUSINESS_SERVE*/:
  1718. case 0x0038 /*PRODUCT_SOLUTION_EMBEDDEDSERVE*/:
  1719. case 0x0007 /*PRODUCT_STANDARD_SERVE*/:
  1720. case 0x000D /*PRODUCT_STANDARD_SERVER_COR*/:
  1721. case 0x0028 /*PRODUCT_STANDARD_SERVER_CORE_*/:
  1722. case 0x0024 /*PRODUCT_STANDARD_SERVER_*/:
  1723. case 0x0017 /*PRODUCT_STORAGE_ENTERPRISE_SERVE*/:
  1724. case 0x0014 /*PRODUCT_STORAGE_EXPRESS_SERVE*/:
  1725. case 0x0015 /*PRODUCT_STORAGE_STANDARD_SERVE*/:
  1726. case 0x0016 /*PRODUCT_STORAGE_WORKGROUP_SERVE*/:
  1727. case 0x0011 /*PRODUCT_WEB_SERVE*/:
  1728. case 0x001D /*PRODUCT_WEB_SERVER_COR*/:
  1729. Result = true;
  1730. break;
  1731. default:
  1732. Result = false;
  1733. break;
  1734. }
  1735. }
  1736. return Result;
  1737. }
  1738. //---------------------------------------------------------------------------
  1739. LCID __fastcall GetDefaultLCID()
  1740. {
  1741. return Is2000() ? GetUserDefaultLCID() : GetThreadLocale();
  1742. }
  1743. //---------------------------------------------------------------------------
  1744. static UnicodeString ADefaultEncodingName;
  1745. UnicodeString __fastcall DefaultEncodingName()
  1746. {
  1747. if (ADefaultEncodingName.IsEmpty())
  1748. {
  1749. CPINFOEX Info;
  1750. GetCPInfoEx(CP_ACP, 0, &Info);
  1751. ADefaultEncodingName = Info.CodePageName;
  1752. }
  1753. return ADefaultEncodingName;
  1754. }
  1755. //---------------------------------------------------------------------------
  1756. UnicodeString __fastcall WindowsProductName()
  1757. {
  1758. UnicodeString Result;
  1759. TRegistry * Registry = new TRegistry(KEY_READ);
  1760. try
  1761. {
  1762. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1763. if (Registry->OpenKey("SOFTWARE", false) &&
  1764. Registry->OpenKey("Microsoft", false) &&
  1765. Registry->OpenKey("Windows NT", false) &&
  1766. Registry->OpenKey("CurrentVersion", false))
  1767. {
  1768. Result = Registry->ReadString("ProductName");
  1769. }
  1770. delete Registry;
  1771. }
  1772. catch(...)
  1773. {
  1774. }
  1775. return Result;
  1776. }
  1777. //---------------------------------------------------------------------------
  1778. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  1779. {
  1780. UnicodeString FileName =
  1781. IncludeTrailingPathDelimiter(Path) +
  1782. FORMAT("wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  1783. HANDLE Handle = CreateFile(FileName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  1784. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  1785. bool Result = (Handle != INVALID_HANDLE_VALUE);
  1786. if (Result)
  1787. {
  1788. CloseHandle(Handle);
  1789. }
  1790. return Result;
  1791. }
  1792. //---------------------------------------------------------------------------
  1793. UnicodeString __fastcall FormatNumber(__int64 Number)
  1794. {
  1795. return FormatFloat(L"#,##0", Number);
  1796. }
  1797. //---------------------------------------------------------------------------
  1798. // simple alternative to FormatBytes
  1799. UnicodeString __fastcall FormatSize(__int64 Size)
  1800. {
  1801. return FormatNumber(Size);
  1802. }
  1803. //---------------------------------------------------------------------------
  1804. // Suppress warning about unused constants in DateUtils.hpp
  1805. #pragma warn -8080