Common.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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. ReplaceStr(MoreMessages->Text, L"\r", L"");
  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. bool __fastcall IsDigit(wchar_t Ch)
  717. {
  718. return (Ch >= '0') && (Ch <= '9');
  719. }
  720. //---------------------------------------------------------------------------
  721. bool __fastcall IsHex(wchar_t Ch)
  722. {
  723. return
  724. IsDigit(Ch) ||
  725. ((Ch >= 'A') && (Ch <= 'F')) ||
  726. ((Ch >= 'a') && (Ch <= 'f'));
  727. }
  728. //---------------------------------------------------------------------------
  729. int __fastcall FindCheck(int Result)
  730. {
  731. if ((Result != ERROR_SUCCESS) &&
  732. (Result != ERROR_FILE_NOT_FOUND) &&
  733. (Result != ERROR_NO_MORE_FILES))
  734. {
  735. RaiseLastOSError(Result);
  736. }
  737. return Result;
  738. }
  739. //---------------------------------------------------------------------------
  740. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRec & F)
  741. {
  742. return FindCheck(FindFirst(Path, Attr, F));
  743. }
  744. //---------------------------------------------------------------------------
  745. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  746. // I.e. even if we do not care that FindFirst failed, if FindNext
  747. // failes after successfull FindFirst, it mean some terrible problem
  748. int __fastcall FindNextChecked(TSearchRec & F)
  749. {
  750. return FindCheck(FindNext(F));
  751. }
  752. //---------------------------------------------------------------------------
  753. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  754. {
  755. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  756. bool Result = (FindFirst(FileName, FindAttrs, Rec) == 0);
  757. if (Result)
  758. {
  759. FindClose(Rec);
  760. }
  761. return Result;
  762. }
  763. //---------------------------------------------------------------------------
  764. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  765. TProcessLocalFileEvent CallBackFunc, void * Param,
  766. int FindAttrs)
  767. {
  768. assert(CallBackFunc);
  769. if (FindAttrs < 0)
  770. {
  771. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  772. }
  773. TSearchRec SearchRec;
  774. DirName = IncludeTrailingBackslash(DirName);
  775. if (FindFirstChecked(DirName + L"*.*", FindAttrs, SearchRec) == 0)
  776. {
  777. try
  778. {
  779. do
  780. {
  781. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  782. {
  783. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  784. }
  785. } while (FindNextChecked(SearchRec) == 0);
  786. }
  787. __finally
  788. {
  789. FindClose(SearchRec);
  790. }
  791. }
  792. }
  793. //---------------------------------------------------------------------------
  794. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  795. {
  796. try
  797. {
  798. TDateTime DateTime = EncodeDate(Year, Month, Day);
  799. return DateTime;
  800. }
  801. catch (EConvertError & E)
  802. {
  803. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  804. }
  805. }
  806. //---------------------------------------------------------------------------
  807. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  808. {
  809. try
  810. {
  811. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  812. return DateTime;
  813. }
  814. catch (EConvertError & E)
  815. {
  816. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  817. }
  818. }
  819. //---------------------------------------------------------------------------
  820. struct TDateTimeParams
  821. {
  822. TDateTime UnixEpoch;
  823. double BaseDifference;
  824. long BaseDifferenceSec;
  825. // All Current* are actually global, not per-year
  826. double CurrentDaylightDifference;
  827. long CurrentDaylightDifferenceSec;
  828. double CurrentDifference;
  829. long CurrentDifferenceSec;
  830. double StandardDifference;
  831. long StandardDifferenceSec;
  832. double DaylightDifference;
  833. long DaylightDifferenceSec;
  834. SYSTEMTIME SystemStandardDate;
  835. SYSTEMTIME SystemDaylightDate;
  836. TDateTime StandardDate;
  837. TDateTime DaylightDate;
  838. bool SummerDST;
  839. // This is actually global, not per-year
  840. bool DaylightHack;
  841. };
  842. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  843. static TYearlyDateTimeParams YearlyDateTimeParams;
  844. static std::auto_ptr<TCriticalSection> DateTimeParamsSection(new TCriticalSection());
  845. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  846. TDateTime & Result);
  847. //---------------------------------------------------------------------------
  848. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  849. {
  850. unsigned short Year, Month, Day;
  851. DecodeDate(DateTime, Year, Month, Day);
  852. return Year;
  853. }
  854. //---------------------------------------------------------------------------
  855. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  856. {
  857. TGuard Guard(DateTimeParamsSection.get());
  858. TDateTimeParams * Result;
  859. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  860. if (i != YearlyDateTimeParams.end())
  861. {
  862. Result = &(*i).second;
  863. }
  864. else
  865. {
  866. // creates new entry as a side effect
  867. Result = &YearlyDateTimeParams[Year];
  868. TIME_ZONE_INFORMATION TZI;
  869. unsigned long GTZI;
  870. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  871. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  872. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  873. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  874. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  875. {
  876. GTZI = GetTimeZoneInformation(&TZI);
  877. }
  878. else
  879. {
  880. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  881. GTZI = TIME_ZONE_ID_UNKNOWN;
  882. }
  883. switch (GTZI)
  884. {
  885. case TIME_ZONE_ID_UNKNOWN:
  886. Result->CurrentDaylightDifferenceSec = 0;
  887. break;
  888. case TIME_ZONE_ID_STANDARD:
  889. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  890. break;
  891. case TIME_ZONE_ID_DAYLIGHT:
  892. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  893. break;
  894. case TIME_ZONE_ID_INVALID:
  895. default:
  896. throw Exception(TIMEZONE_ERROR);
  897. }
  898. Result->BaseDifferenceSec = TZI.Bias;
  899. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  900. Result->BaseDifferenceSec *= SecsPerMin;
  901. Result->CurrentDifferenceSec = TZI.Bias +
  902. Result->CurrentDaylightDifferenceSec;
  903. Result->CurrentDifference =
  904. double(Result->CurrentDifferenceSec) / MinsPerDay;
  905. Result->CurrentDifferenceSec *= SecsPerMin;
  906. Result->CurrentDaylightDifference =
  907. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  908. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  909. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  910. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  911. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  912. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  913. Result->SystemStandardDate = TZI.StandardDate;
  914. Result->SystemDaylightDate = TZI.DaylightDate;
  915. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  916. if (Result->SystemStandardDate.wMonth != 0)
  917. {
  918. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  919. }
  920. if (Result->SystemDaylightDate.wMonth != 0)
  921. {
  922. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  923. }
  924. Result->SummerDST = (Result->DaylightDate < Result->StandardDate);
  925. Result->DaylightHack = !IsWin7() || IsExactly2008R2();
  926. }
  927. return Result;
  928. }
  929. //---------------------------------------------------------------------------
  930. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  931. TDateTime & Result)
  932. {
  933. if (Date.wYear == 0)
  934. {
  935. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  936. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  937. (7 * (Date.wDay - 1));
  938. if (Date.wDay == 5)
  939. {
  940. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  941. if (Month > 12)
  942. {
  943. Month = static_cast<unsigned short>(Month - 12);
  944. Year++;
  945. }
  946. if (Result >= EncodeDateVerbose(Year, Month, 1))
  947. {
  948. Result -= 7;
  949. }
  950. }
  951. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  952. Date.wMilliseconds);
  953. }
  954. else
  955. {
  956. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  957. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  958. }
  959. }
  960. //---------------------------------------------------------------------------
  961. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  962. {
  963. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  964. bool Result;
  965. // On some systems it occurs that StandardDate is unset, while
  966. // DaylightDate is set. MSDN states that this is invalid and
  967. // should be treated as if there is no daylight saving.
  968. // So check both.
  969. if ((Params->SystemStandardDate.wMonth == 0) ||
  970. (Params->SystemDaylightDate.wMonth == 0))
  971. {
  972. Result = false;
  973. }
  974. else
  975. {
  976. if (Params->SummerDST)
  977. {
  978. Result =
  979. (DateTime >= Params->DaylightDate) &&
  980. (DateTime < Params->StandardDate);
  981. }
  982. else
  983. {
  984. Result =
  985. (DateTime < Params->StandardDate) ||
  986. (DateTime >= Params->DaylightDate);
  987. }
  988. }
  989. return Result;
  990. }
  991. //---------------------------------------------------------------------------
  992. bool __fastcall UsesDaylightHack()
  993. {
  994. return GetDateTimeParams(0)->DaylightHack;
  995. }
  996. //---------------------------------------------------------------------------
  997. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  998. {
  999. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1000. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1001. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1002. if (Params->DaylightHack)
  1003. {
  1004. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1005. {
  1006. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1007. Result -= CurrentParams->CurrentDifference;
  1008. }
  1009. else if (DSTMode == dstmKeep)
  1010. {
  1011. Result -= Params->BaseDifference;
  1012. }
  1013. }
  1014. else
  1015. {
  1016. Result -= Params->BaseDifference;
  1017. }
  1018. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1019. {
  1020. Result -= (IsDateInDST(Result) ?
  1021. Params->DaylightDifference : Params->StandardDifference);
  1022. }
  1023. return Result;
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. __int64 __fastcall Round(double Number)
  1027. {
  1028. double Floor = floor(Number);
  1029. double Ceil = ceil(Number);
  1030. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1031. }
  1032. //---------------------------------------------------------------------------
  1033. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime)
  1034. {
  1035. S = S.Trim();
  1036. int Index = 1;
  1037. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1038. {
  1039. Index++;
  1040. }
  1041. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1042. int Number;
  1043. bool Result = TryStrToInt(NumberStr, Number);
  1044. if (Result)
  1045. {
  1046. S.Delete(1, Index - 1);
  1047. S = S.Trim().UpperCase();
  1048. DateTime = Now();
  1049. // These may not overlap with ParseSize (K, M and G)
  1050. if (S == "S")
  1051. {
  1052. DateTime = IncSecond(DateTime, -Number);
  1053. }
  1054. else if (S == "N")
  1055. {
  1056. DateTime = IncMinute(DateTime, -Number);
  1057. }
  1058. else if (S == "H")
  1059. {
  1060. DateTime = IncHour(DateTime, -Number);
  1061. }
  1062. else if (S == "D")
  1063. {
  1064. DateTime = IncDay(DateTime, -Number);
  1065. }
  1066. else if (S == "Y")
  1067. {
  1068. DateTime = IncYear(DateTime, -Number);
  1069. }
  1070. else
  1071. {
  1072. Result = false;
  1073. }
  1074. }
  1075. return Result;
  1076. }
  1077. //---------------------------------------------------------------------------
  1078. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1079. {
  1080. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1081. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1082. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1083. CurrentParams->CurrentDifferenceSec;
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1087. TDSTMode /*DSTMode*/)
  1088. {
  1089. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1090. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1091. if (!Params->DaylightHack)
  1092. {
  1093. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1094. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1095. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1096. UnixTimeStamp -= CurrentParams->CurrentDaylightDifferenceSec;
  1097. }
  1098. FILETIME Result;
  1099. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1100. return Result;
  1101. }
  1102. //---------------------------------------------------------------------------
  1103. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1104. {
  1105. // duplicated in DirView.pas
  1106. SYSTEMTIME SysTime;
  1107. if (!UsesDaylightHack())
  1108. {
  1109. SYSTEMTIME UniverzalSysTime;
  1110. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1111. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1112. }
  1113. else
  1114. {
  1115. FILETIME LocalFileTime;
  1116. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1117. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1118. }
  1119. TDateTime Result = SystemTimeToDateTime(SysTime);
  1120. return Result;
  1121. }
  1122. //---------------------------------------------------------------------------
  1123. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1124. TDSTMode DSTMode)
  1125. {
  1126. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1127. if (UsesDaylightHack())
  1128. {
  1129. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1130. {
  1131. FILETIME LocalFileTime;
  1132. SYSTEMTIME SystemTime;
  1133. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1134. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1135. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1136. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1137. Result += (IsDateInDST(DateTime) ?
  1138. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1139. if (DSTMode == dstmKeep)
  1140. {
  1141. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1142. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1143. }
  1144. }
  1145. }
  1146. else
  1147. {
  1148. if (DSTMode == dstmWin)
  1149. {
  1150. FILETIME LocalFileTime;
  1151. SYSTEMTIME SystemTime;
  1152. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1153. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1154. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1155. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1156. Result -= (IsDateInDST(DateTime) ?
  1157. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1158. }
  1159. }
  1160. return Result;
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1164. {
  1165. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1166. DateTime +=
  1167. (IsDateInDST(DateTime) ?
  1168. Params->DaylightDifference : Params->StandardDifference);
  1169. DateTime += Params->BaseDifference;
  1170. if (Params->DaylightHack)
  1171. {
  1172. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1173. DateTime += CurrentParams->CurrentDaylightDifference;
  1174. }
  1175. return DateTime;
  1176. }
  1177. //---------------------------------------------------------------------------
  1178. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1179. {
  1180. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1181. DateTime -=
  1182. (IsDateInDST(DateTime) ?
  1183. Params->DaylightDifference : Params->StandardDifference);
  1184. DateTime -= Params->BaseDifference;
  1185. if (Params->DaylightHack)
  1186. {
  1187. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1188. DateTime -= CurrentParams->CurrentDaylightDifference;
  1189. }
  1190. return DateTime;
  1191. }
  1192. //---------------------------------------------------------------------------
  1193. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1194. TDSTMode DSTMode)
  1195. {
  1196. __int64 Result;
  1197. if ((FileTime.dwLowDateTime == 0) &&
  1198. (FileTime.dwHighDateTime == 0))
  1199. {
  1200. Result = ::DateTimeToUnix(Now());
  1201. }
  1202. else
  1203. {
  1204. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1205. }
  1206. return Result;
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1210. {
  1211. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1212. if (Params->DaylightHack)
  1213. {
  1214. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1215. {
  1216. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1217. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  1218. }
  1219. if (!IsDateInDST(DateTime))
  1220. {
  1221. if (DSTMode == dstmWin)
  1222. {
  1223. DateTime = DateTime - Params->DaylightDifference;
  1224. }
  1225. }
  1226. else
  1227. {
  1228. DateTime = DateTime - Params->StandardDifference;
  1229. }
  1230. }
  1231. else
  1232. {
  1233. if (DSTMode == dstmWin)
  1234. {
  1235. if (IsDateInDST(DateTime))
  1236. {
  1237. DateTime = DateTime + Params->DaylightDifference;
  1238. }
  1239. else
  1240. {
  1241. DateTime = DateTime + Params->StandardDifference;
  1242. }
  1243. }
  1244. }
  1245. return DateTime;
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  1249. {
  1250. UnicodeString Result = Format;
  1251. bool AsIs = false;
  1252. int Index = 1;
  1253. while (Index <= Result.Length())
  1254. {
  1255. wchar_t F = Result[Index];
  1256. if ((F == L'\'') || (F == L'\"'))
  1257. {
  1258. AsIs = !AsIs;
  1259. Index++;
  1260. }
  1261. else if (!AsIs && ((F == L'a') || (F == L'A')))
  1262. {
  1263. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  1264. {
  1265. Index += 5;
  1266. }
  1267. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  1268. {
  1269. Index += 3;
  1270. }
  1271. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  1272. {
  1273. Index += 4;
  1274. }
  1275. else
  1276. {
  1277. Index++;
  1278. }
  1279. }
  1280. else
  1281. {
  1282. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  1283. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1284. {
  1285. Result.Insert(F, Index);
  1286. }
  1287. while ((Index <= Result.Length()) && (F == Result[Index]))
  1288. {
  1289. Index++;
  1290. }
  1291. }
  1292. }
  1293. return Result;
  1294. }
  1295. //---------------------------------------------------------------------------
  1296. static UnicodeString __fastcall FormatTimeZone(long Sec)
  1297. {
  1298. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  1299. UnicodeString Str;
  1300. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  1301. {
  1302. Str = FORMAT(L"%d", (-Span.Hours));
  1303. }
  1304. else if (Span.Seconds == 0)
  1305. {
  1306. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  1307. }
  1308. else
  1309. {
  1310. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  1311. }
  1312. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  1313. return Str;
  1314. }
  1315. //---------------------------------------------------------------------------
  1316. UnicodeString __fastcall GetTimeZoneLogString()
  1317. {
  1318. const TDateTimeParams * Params = GetDateTimeParams(0);
  1319. UnicodeString Result =
  1320. FORMAT("Current: GMT%s, Standard: GMT%s, DST: GMT%s, DST Start: %s, DST End: %s",
  1321. (FormatTimeZone(Params->CurrentDifferenceSec),
  1322. FormatTimeZone(Params->BaseDifferenceSec + Params->StandardDifferenceSec),
  1323. FormatTimeZone(Params->BaseDifferenceSec + Params->DaylightDifferenceSec),
  1324. Params->DaylightDate.DateString(),
  1325. Params->StandardDate.DateString()));
  1326. return Result;
  1327. }
  1328. //---------------------------------------------------------------------------
  1329. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  1330. {
  1331. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  1332. }
  1333. //---------------------------------------------------------------------------
  1334. UnicodeString __fastcall StandardTimestamp()
  1335. {
  1336. return StandardTimestamp(Now());
  1337. }
  1338. //---------------------------------------------------------------------------
  1339. static TDateTime TwoSeconds(0, 0, 2, 0);
  1340. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1341. {
  1342. // "FAT" time precision
  1343. // (when one time is seconds-precision and other is millisecond-precision,
  1344. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1345. // be treated the same)
  1346. int Result;
  1347. if (T1 == T2)
  1348. {
  1349. // just optimization
  1350. Result = 0;
  1351. }
  1352. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1353. {
  1354. Result = -1;
  1355. }
  1356. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1357. {
  1358. Result = 1;
  1359. }
  1360. else
  1361. {
  1362. Result = 0;
  1363. }
  1364. return Result;
  1365. }
  1366. //---------------------------------------------------------------------------
  1367. int __fastcall TimeToMSec(TDateTime T)
  1368. {
  1369. return int(Round(double(T) * double(MSecsPerDay)));
  1370. }
  1371. //---------------------------------------------------------------------------
  1372. int __fastcall TimeToMinutes(TDateTime T)
  1373. {
  1374. return TimeToMSec(T) / MSecsPerSec / SecsPerMin;
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. bool __fastcall RecursiveDeleteFile(const UnicodeString FileName, bool ToRecycleBin)
  1378. {
  1379. SHFILEOPSTRUCT Data;
  1380. memset(&Data, 0, sizeof(Data));
  1381. Data.hwnd = NULL;
  1382. Data.wFunc = FO_DELETE;
  1383. UnicodeString FileList(FileName);
  1384. FileList.SetLength(FileList.Length() + 2);
  1385. FileList[FileList.Length() - 1] = L'\0';
  1386. FileList[FileList.Length()] = L'\0';
  1387. Data.pFrom = FileList.c_str();
  1388. Data.pTo = L"";
  1389. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1390. FOF_NOERRORUI | FOF_SILENT;
  1391. if (ToRecycleBin)
  1392. {
  1393. Data.fFlags |= FOF_ALLOWUNDO;
  1394. }
  1395. int ErrorCode = SHFileOperation(&Data);
  1396. bool Result = (ErrorCode == 0);
  1397. if (!Result)
  1398. {
  1399. // according to MSDN, SHFileOperation may return following non-Win32
  1400. // error codes
  1401. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  1402. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  1403. (ErrorCode == 0x10074))
  1404. {
  1405. ErrorCode = 0;
  1406. }
  1407. SetLastError(ErrorCode);
  1408. }
  1409. return Result;
  1410. }
  1411. //---------------------------------------------------------------------------
  1412. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  1413. {
  1414. unsigned int Result;
  1415. if ((Answers & qaCancel) != 0)
  1416. {
  1417. Result = qaCancel;
  1418. }
  1419. else if ((Answers & qaNo) != 0)
  1420. {
  1421. Result = qaNo;
  1422. }
  1423. else if ((Answers & qaAbort) != 0)
  1424. {
  1425. Result = qaAbort;
  1426. }
  1427. else if ((Answers & qaOK) != 0)
  1428. {
  1429. Result = qaOK;
  1430. }
  1431. else
  1432. {
  1433. assert(false);
  1434. Result = qaCancel;
  1435. }
  1436. return Result;
  1437. }
  1438. //---------------------------------------------------------------------------
  1439. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  1440. {
  1441. unsigned int Result;
  1442. if (FLAGSET(Answers, qaAbort))
  1443. {
  1444. Result = qaAbort;
  1445. }
  1446. else
  1447. {
  1448. Result = CancelAnswer(Answers);
  1449. }
  1450. return Result;
  1451. }
  1452. //---------------------------------------------------------------------------
  1453. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  1454. {
  1455. unsigned int Result;
  1456. if (FLAGSET(Answers, qaSkip))
  1457. {
  1458. Result = qaSkip;
  1459. }
  1460. else if (FLAGSET(Answers, qaIgnore))
  1461. {
  1462. Result = qaIgnore;
  1463. }
  1464. else if (FLAGSET(Answers, qaYes))
  1465. {
  1466. Result = qaYes;
  1467. }
  1468. else if (FLAGSET(Answers, qaOK))
  1469. {
  1470. Result = qaOK;
  1471. }
  1472. else if (FLAGSET(Answers, qaRetry))
  1473. {
  1474. Result = qaRetry;
  1475. }
  1476. else
  1477. {
  1478. Result = CancelAnswer(Answers);
  1479. }
  1480. return Result;
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. TLibModule * __fastcall FindModule(void * Instance)
  1484. {
  1485. TLibModule * CurModule;
  1486. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  1487. while (CurModule)
  1488. {
  1489. if (CurModule->Instance == (unsigned)Instance)
  1490. {
  1491. break;
  1492. }
  1493. else
  1494. {
  1495. CurModule = CurModule->Next;
  1496. }
  1497. }
  1498. return CurModule;
  1499. }
  1500. //---------------------------------------------------------------------------
  1501. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  1502. {
  1503. TLibModule * MainModule = FindModule(HInstance);
  1504. assert(MainModule != NULL);
  1505. UnicodeString Result;
  1506. Result.SetLength(MaxLength);
  1507. int Length = LoadString((HINSTANCE)MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  1508. Result.SetLength(Length);
  1509. return Result;
  1510. }
  1511. //---------------------------------------------------------------------------
  1512. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  1513. {
  1514. UnicodeString Result;
  1515. UnicodeString Str = LoadStr(Ident);
  1516. while (Part > 0)
  1517. {
  1518. Result = CutToChar(Str, L'|', false);
  1519. Part--;
  1520. }
  1521. return Result;
  1522. }
  1523. //---------------------------------------------------------------------------
  1524. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  1525. {
  1526. int i = 1;
  1527. while (i <= S.Length())
  1528. {
  1529. switch (S[i])
  1530. {
  1531. case L'+':
  1532. S[i] = ' ';
  1533. break;
  1534. case L'%':
  1535. if (i <= S.Length() - 2)
  1536. {
  1537. unsigned char B = HexToByte(S.SubString(i + 1, 2));
  1538. if (B > 0)
  1539. {
  1540. S[i] = (wchar_t)B;
  1541. S.Delete(i + 1, 2);
  1542. }
  1543. }
  1544. break;
  1545. }
  1546. i++;
  1547. }
  1548. return S;
  1549. }
  1550. //---------------------------------------------------------------------------
  1551. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, UnicodeString Chars)
  1552. {
  1553. int i = 1;
  1554. while (i <= S.Length())
  1555. {
  1556. if (Chars.Pos(S[i]) > 0)
  1557. {
  1558. UnicodeString H = ByteToHex(AnsiString(UnicodeString(S[i]))[1]);
  1559. S.Insert(H, i + 1);
  1560. S[i] = '%';
  1561. i += H.Length();
  1562. }
  1563. i++;
  1564. }
  1565. return S;
  1566. }
  1567. //---------------------------------------------------------------------------
  1568. UnicodeString __fastcall EncodeUrlChars(UnicodeString S, UnicodeString Ignore)
  1569. {
  1570. UnicodeString Chars;
  1571. if (Ignore.Pos(L' ') == 0)
  1572. {
  1573. Chars += L' ';
  1574. }
  1575. if (Ignore.Pos(L'/') == 0)
  1576. {
  1577. Chars += L'/';
  1578. }
  1579. return DoEncodeUrl(S, Chars);
  1580. }
  1581. //---------------------------------------------------------------------------
  1582. UnicodeString __fastcall NonUrlChars()
  1583. {
  1584. UnicodeString S;
  1585. for (unsigned int I = 0; I <= 127; I++)
  1586. {
  1587. wchar_t C = static_cast<wchar_t>(I);
  1588. if (((C >= L'a') && (C <= L'z')) ||
  1589. ((C >= L'A') && (C <= L'Z')) ||
  1590. ((C >= L'0') && (C <= L'9')) ||
  1591. (C == L'_') || (C == L'-') || (C == L'.'))
  1592. {
  1593. // noop
  1594. }
  1595. else
  1596. {
  1597. S += C;
  1598. }
  1599. }
  1600. return S;
  1601. }
  1602. //---------------------------------------------------------------------------
  1603. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  1604. {
  1605. return DoEncodeUrl(S, NonUrlChars());
  1606. }
  1607. //---------------------------------------------------------------------------
  1608. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  1609. {
  1610. return ReplaceStr(Caption, L"&", L"&&");
  1611. }
  1612. //---------------------------------------------------------------------------
  1613. // duplicated in console's Main.cpp
  1614. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  1615. UnicodeString * RawToken)
  1616. {
  1617. bool Result;
  1618. Token = L"";
  1619. // inspired by Putty's sftp_getcmd() from PSFTP.C
  1620. int Index = 1;
  1621. while ((Index <= Str.Length()) &&
  1622. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  1623. {
  1624. Index++;
  1625. }
  1626. if (Index <= Str.Length())
  1627. {
  1628. bool Quoting = false;
  1629. while (Index <= Str.Length())
  1630. {
  1631. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  1632. {
  1633. break;
  1634. }
  1635. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  1636. (Str[Index + 1] == L'"'))
  1637. {
  1638. Index += 2;
  1639. Token += L'"';
  1640. }
  1641. else if (Str[Index] == L'"')
  1642. {
  1643. Index++;
  1644. Quoting = !Quoting;
  1645. }
  1646. else
  1647. {
  1648. Token += Str[Index];
  1649. Index++;
  1650. }
  1651. }
  1652. if (RawToken != NULL)
  1653. {
  1654. (*RawToken) = Str.SubString(1, Index - 1);
  1655. }
  1656. if (Index <= Str.Length())
  1657. {
  1658. Index++;
  1659. }
  1660. Str = Str.SubString(Index, Str.Length());
  1661. Result = true;
  1662. }
  1663. else
  1664. {
  1665. Result = false;
  1666. Str = L"";
  1667. }
  1668. return Result;
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  1672. {
  1673. if (!Value.IsEmpty())
  1674. {
  1675. if (!List.IsEmpty() &&
  1676. ((List.Length() < Delimiter.Length()) ||
  1677. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  1678. {
  1679. List += Delimiter;
  1680. }
  1681. List += Value;
  1682. }
  1683. }
  1684. //---------------------------------------------------------------------------
  1685. bool __fastcall Is2000()
  1686. {
  1687. return (Win32MajorVersion >= 5);
  1688. }
  1689. //---------------------------------------------------------------------------
  1690. bool __fastcall IsWin7()
  1691. {
  1692. return
  1693. (Win32MajorVersion > 6) ||
  1694. ((Win32MajorVersion == 6) && (Win32MinorVersion >= 1));
  1695. }
  1696. //---------------------------------------------------------------------------
  1697. bool __fastcall IsExactly2008R2()
  1698. {
  1699. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1700. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  1701. TGetProductInfo GetProductInfo =
  1702. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  1703. bool Result;
  1704. if (GetProductInfo == NULL)
  1705. {
  1706. Result = false;
  1707. }
  1708. else
  1709. {
  1710. DWORD Type;
  1711. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  1712. switch (Type)
  1713. {
  1714. case 0x0008 /*PRODUCT_DATACENTER_SERVER*/:
  1715. case 0x000C /*PRODUCT_DATACENTER_SERVER_CORE}*/:
  1716. case 0x0027 /*PRODUCT_DATACENTER_SERVER_CORE_V*/:
  1717. case 0x0025 /*PRODUCT_DATACENTER_SERVER_V*/:
  1718. case 0x000A /*PRODUCT_ENTERPRISE_SERVE*/:
  1719. case 0x000E /*PRODUCT_ENTERPRISE_SERVER_COR*/:
  1720. case 0x0029 /*PRODUCT_ENTERPRISE_SERVER_CORE_*/:
  1721. case 0x000F /*PRODUCT_ENTERPRISE_SERVER_IA6*/:
  1722. case 0x0026 /*PRODUCT_ENTERPRISE_SERVER_*/:
  1723. case 0x002A /*PRODUCT_HYPER*/:
  1724. case 0x001E /*PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMEN*/:
  1725. case 0x0020 /*PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGIN*/:
  1726. case 0x001F /*PRODUCT_MEDIUMBUSINESS_SERVER_SECURIT*/:
  1727. case 0x0018 /*PRODUCT_SERVER_FOR_SMALLBUSINES*/:
  1728. case 0x0023 /*PRODUCT_SERVER_FOR_SMALLBUSINESS_*/:
  1729. case 0x0021 /*PRODUCT_SERVER_FOUNDATIO*/:
  1730. case 0x0009 /*PRODUCT_SMALLBUSINESS_SERVE*/:
  1731. case 0x0038 /*PRODUCT_SOLUTION_EMBEDDEDSERVE*/:
  1732. case 0x0007 /*PRODUCT_STANDARD_SERVE*/:
  1733. case 0x000D /*PRODUCT_STANDARD_SERVER_COR*/:
  1734. case 0x0028 /*PRODUCT_STANDARD_SERVER_CORE_*/:
  1735. case 0x0024 /*PRODUCT_STANDARD_SERVER_*/:
  1736. case 0x0017 /*PRODUCT_STORAGE_ENTERPRISE_SERVE*/:
  1737. case 0x0014 /*PRODUCT_STORAGE_EXPRESS_SERVE*/:
  1738. case 0x0015 /*PRODUCT_STORAGE_STANDARD_SERVE*/:
  1739. case 0x0016 /*PRODUCT_STORAGE_WORKGROUP_SERVE*/:
  1740. case 0x0011 /*PRODUCT_WEB_SERVE*/:
  1741. case 0x001D /*PRODUCT_WEB_SERVER_COR*/:
  1742. Result = true;
  1743. break;
  1744. default:
  1745. Result = false;
  1746. break;
  1747. }
  1748. }
  1749. return Result;
  1750. }
  1751. //---------------------------------------------------------------------------
  1752. LCID __fastcall GetDefaultLCID()
  1753. {
  1754. return Is2000() ? GetUserDefaultLCID() : GetThreadLocale();
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. static UnicodeString ADefaultEncodingName;
  1758. UnicodeString __fastcall DefaultEncodingName()
  1759. {
  1760. if (ADefaultEncodingName.IsEmpty())
  1761. {
  1762. CPINFOEX Info;
  1763. GetCPInfoEx(CP_ACP, 0, &Info);
  1764. ADefaultEncodingName = Info.CodePageName;
  1765. }
  1766. return ADefaultEncodingName;
  1767. }
  1768. //---------------------------------------------------------------------------
  1769. UnicodeString __fastcall WindowsProductName()
  1770. {
  1771. UnicodeString Result;
  1772. TRegistry * Registry = new TRegistry(KEY_READ);
  1773. try
  1774. {
  1775. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1776. if (Registry->OpenKey("SOFTWARE", false) &&
  1777. Registry->OpenKey("Microsoft", false) &&
  1778. Registry->OpenKey("Windows NT", false) &&
  1779. Registry->OpenKey("CurrentVersion", false))
  1780. {
  1781. Result = Registry->ReadString("ProductName");
  1782. }
  1783. delete Registry;
  1784. }
  1785. catch(...)
  1786. {
  1787. }
  1788. return Result;
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  1792. {
  1793. UnicodeString FileName =
  1794. IncludeTrailingPathDelimiter(Path) +
  1795. FORMAT("wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  1796. HANDLE Handle = CreateFile(FileName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  1797. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  1798. bool Result = (Handle != INVALID_HANDLE_VALUE);
  1799. if (Result)
  1800. {
  1801. CloseHandle(Handle);
  1802. }
  1803. return Result;
  1804. }
  1805. //---------------------------------------------------------------------------
  1806. UnicodeString __fastcall FormatNumber(__int64 Number)
  1807. {
  1808. return FormatFloat(L"#,##0", Number);
  1809. }
  1810. //---------------------------------------------------------------------------
  1811. // simple alternative to FormatBytes
  1812. UnicodeString __fastcall FormatSize(__int64 Size)
  1813. {
  1814. return FormatNumber(Size);
  1815. }
  1816. //---------------------------------------------------------------------------
  1817. // Suppress warning about unused constants in DateUtils.hpp
  1818. #pragma warn -8080