Common.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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 <math.h>
  11. #include <shfolder.h>
  12. //---------------------------------------------------------------------------
  13. #pragma package(smart_init)
  14. //---------------------------------------------------------------------------
  15. //---------------------------------------------------------------------------
  16. // TCriticalSection
  17. //---------------------------------------------------------------------------
  18. __fastcall TCriticalSection::TCriticalSection()
  19. {
  20. FAcquired = 0;
  21. InitializeCriticalSection(&FSection);
  22. }
  23. //---------------------------------------------------------------------------
  24. __fastcall TCriticalSection::~TCriticalSection()
  25. {
  26. assert(FAcquired == 0);
  27. DeleteCriticalSection(&FSection);
  28. }
  29. //---------------------------------------------------------------------------
  30. void __fastcall TCriticalSection::Enter()
  31. {
  32. EnterCriticalSection(&FSection);
  33. FAcquired++;
  34. }
  35. //---------------------------------------------------------------------------
  36. void __fastcall TCriticalSection::Leave()
  37. {
  38. FAcquired--;
  39. LeaveCriticalSection(&FSection);
  40. }
  41. //---------------------------------------------------------------------------
  42. // TGuard
  43. //---------------------------------------------------------------------------
  44. __fastcall TGuard::TGuard(TCriticalSection * ACriticalSection) :
  45. FCriticalSection(ACriticalSection)
  46. {
  47. assert(ACriticalSection != NULL);
  48. FCriticalSection->Enter();
  49. }
  50. //---------------------------------------------------------------------------
  51. __fastcall TGuard::~TGuard()
  52. {
  53. FCriticalSection->Leave();
  54. }
  55. //---------------------------------------------------------------------------
  56. // TUnguard
  57. //---------------------------------------------------------------------------
  58. __fastcall TUnguard::TUnguard(TCriticalSection * ACriticalSection) :
  59. FCriticalSection(ACriticalSection)
  60. {
  61. assert(ACriticalSection != NULL);
  62. FCriticalSection->Leave();
  63. }
  64. //---------------------------------------------------------------------------
  65. __fastcall TUnguard::~TUnguard()
  66. {
  67. FCriticalSection->Enter();
  68. }
  69. //---------------------------------------------------------------------------
  70. //---------------------------------------------------------------------------
  71. const char EngShortMonthNames[12][4] =
  72. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  73. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  74. //---------------------------------------------------------------------------
  75. AnsiString ReplaceChar(AnsiString Str, Char A, Char B)
  76. {
  77. for (Integer Index = 0; Index < Str.Length(); Index++)
  78. if (Str[Index+1] == A) Str[Index+1] = B;
  79. return Str;
  80. }
  81. //---------------------------------------------------------------------------
  82. AnsiString DeleteChar(AnsiString Str, Char C)
  83. {
  84. int P;
  85. while ((P = Str.Pos(C)) > 0)
  86. {
  87. Str.Delete(P, 1);
  88. }
  89. return Str;
  90. }
  91. //---------------------------------------------------------------------------
  92. void PackStr(AnsiString &Str)
  93. {
  94. // Following will free unnecessary bytes
  95. Str = Str.c_str();
  96. }
  97. //---------------------------------------------------------------------------
  98. AnsiString MakeValidFileName(AnsiString FileName)
  99. {
  100. AnsiString IllegalChars = ";,=+<>|\"[] \\/?*";
  101. for (int Index = 0; Index < IllegalChars.Length(); Index++)
  102. {
  103. FileName = ReplaceChar(FileName, IllegalChars[Index+1], '-');
  104. }
  105. return FileName;
  106. }
  107. //---------------------------------------------------------------------------
  108. AnsiString RootKeyToStr(HKEY RootKey)
  109. {
  110. if (RootKey == HKEY_USERS) return "HKEY_USERS";
  111. else
  112. if (RootKey == HKEY_LOCAL_MACHINE) return "HKEY_LOCAL_MACHINE";
  113. else
  114. if (RootKey == HKEY_CURRENT_USER) return "HKEY_CURRENT_USER";
  115. else
  116. if (RootKey == HKEY_CLASSES_ROOT) return "HKEY_CLASSES_ROOT";
  117. else
  118. if (RootKey == HKEY_CURRENT_CONFIG) return "HKEY_CURRENT_CONFIG";
  119. else
  120. if (RootKey == HKEY_DYN_DATA) return "HKEY_DYN_DATA";
  121. else
  122. { Abort(); return ""; };
  123. }
  124. //---------------------------------------------------------------------------
  125. AnsiString BooleanToEngStr(bool B)
  126. {
  127. return B ? "Yes" : "No";
  128. }
  129. //---------------------------------------------------------------------------
  130. AnsiString BooleanToStr(bool B)
  131. {
  132. return B ? LoadStr(YES_STR) : LoadStr(NO_STR);
  133. }
  134. //---------------------------------------------------------------------------
  135. AnsiString DefaultStr(const AnsiString & Str, const AnsiString & Default)
  136. {
  137. if (!Str.IsEmpty())
  138. {
  139. return Str;
  140. }
  141. else
  142. {
  143. return Default;
  144. }
  145. }
  146. //---------------------------------------------------------------------------
  147. AnsiString CutToChar(AnsiString &Str, Char Ch, bool Trim)
  148. {
  149. Integer P = Str.Pos(Ch);
  150. AnsiString Result;
  151. if (P)
  152. {
  153. Result = Str.SubString(1, P-1);
  154. Str.Delete(1, P);
  155. }
  156. else
  157. {
  158. Result = Str;
  159. Str = "";
  160. }
  161. if (Trim)
  162. {
  163. Result = Result.TrimRight();
  164. Str = Str.TrimLeft();
  165. }
  166. return Result;
  167. }
  168. //---------------------------------------------------------------------------
  169. AnsiString CutToChars(AnsiString & Str, AnsiString Chs, bool Trim,
  170. char * Delimiter)
  171. {
  172. int P;
  173. for (P = 1; P <= Str.Length(); P++)
  174. {
  175. if (IsDelimiter(Chs, Str, P))
  176. {
  177. break;
  178. }
  179. }
  180. AnsiString Result;
  181. if (P <= Str.Length())
  182. {
  183. if (Delimiter != NULL)
  184. {
  185. *Delimiter = Str[P];
  186. }
  187. Result = Str.SubString(1, P-1);
  188. Str.Delete(1, P);
  189. }
  190. else
  191. {
  192. if (Delimiter != NULL)
  193. {
  194. *Delimiter = '\0';
  195. }
  196. Result = Str;
  197. Str = "";
  198. }
  199. if (Trim)
  200. {
  201. Result = Result.TrimRight();
  202. Str = Str.TrimLeft();
  203. }
  204. return Result;
  205. }
  206. //---------------------------------------------------------------------------
  207. AnsiString DelimitStr(AnsiString Str, AnsiString Chars)
  208. {
  209. for (int i = 1; i <= Str.Length(); i++)
  210. {
  211. if (Str.IsDelimiter(Chars, i))
  212. {
  213. Str.Insert("\\", i);
  214. i++;
  215. }
  216. }
  217. return Str;
  218. }
  219. //---------------------------------------------------------------------------
  220. AnsiString ShellDelimitStr(AnsiString Str, char Quote)
  221. {
  222. AnsiString Chars = "$\\";
  223. if (Quote == '"')
  224. {
  225. Chars += "`\"";
  226. }
  227. return DelimitStr(Str, Chars);
  228. }
  229. //---------------------------------------------------------------------------
  230. AnsiString ExceptionLogString(Exception *E)
  231. {
  232. assert(E);
  233. if (E->InheritsFrom(__classid(Exception)))
  234. {
  235. AnsiString Msg;
  236. Msg = FORMAT("(%s) %s", (E->ClassName(), E->Message));
  237. if (E->InheritsFrom(__classid(ExtException)))
  238. {
  239. TStrings * MoreMessages = ((ExtException*)E)->MoreMessages;
  240. if (MoreMessages)
  241. {
  242. Msg += "\n" +
  243. StringReplace(MoreMessages->Text, "\r", "", TReplaceFlags() << rfReplaceAll);
  244. }
  245. }
  246. return Msg;
  247. }
  248. else
  249. {
  250. char Buffer[1024];
  251. ExceptionErrorMessage(ExceptObject(), ExceptAddr(), Buffer, sizeof(Buffer));
  252. return AnsiString(Buffer);
  253. }
  254. }
  255. //---------------------------------------------------------------------------
  256. bool IsDots(const AnsiString Str)
  257. {
  258. char * str = Str.c_str();
  259. return (str[strspn(str, ".")] == '\0');
  260. }
  261. //---------------------------------------------------------------------------
  262. AnsiString __fastcall SystemTemporaryDirectory()
  263. {
  264. AnsiString TempDir;
  265. TempDir.SetLength(MAX_PATH);
  266. TempDir.SetLength(GetTempPath(MAX_PATH, TempDir.c_str()));
  267. return TempDir;
  268. }
  269. //---------------------------------------------------------------------------
  270. AnsiString __fastcall GetShellFolderPath(int CSIdl)
  271. {
  272. AnsiString Result;
  273. HMODULE Shell32Lib = LoadLibrary("SHELL32.DLL");
  274. if (Shell32Lib != NULL)
  275. {
  276. PFNSHGETFOLDERPATH SHGetFolderPath = (PFNSHGETFOLDERPATH)
  277. GetProcAddress(Shell32Lib, "SHGetFolderPathA");
  278. if (SHGetFolderPath != NULL)
  279. {
  280. char Path[2 * MAX_PATH + 10] = "\0";
  281. if (SUCCEEDED(SHGetFolderPath(NULL, CSIdl, NULL, SHGFP_TYPE_CURRENT, Path)))
  282. {
  283. Result = Path;
  284. }
  285. }
  286. }
  287. return Result;
  288. }
  289. //---------------------------------------------------------------------------
  290. AnsiString __fastcall StripPathQuotes(const AnsiString Path)
  291. {
  292. if ((Path.Length() >= 2) &&
  293. (Path[1] == '\"') && (Path[Path.Length()] == '\"'))
  294. {
  295. return Path.SubString(2, Path.Length() - 2);
  296. }
  297. else
  298. {
  299. return Path;
  300. }
  301. }
  302. //---------------------------------------------------------------------------
  303. AnsiString __fastcall AddPathQuotes(AnsiString Path)
  304. {
  305. Path = StripPathQuotes(Path);
  306. if (Path.Pos(" "))
  307. {
  308. Path = "\"" + Path + "\"";
  309. }
  310. return Path;
  311. }
  312. //---------------------------------------------------------------------------
  313. void __fastcall SplitCommand(AnsiString Command, AnsiString &Program,
  314. AnsiString & Params, AnsiString & Dir)
  315. {
  316. Command = Command.Trim();
  317. Params = "";
  318. Dir = "";
  319. if (!Command.IsEmpty() && (Command[1] == '\"'))
  320. {
  321. Command.Delete(1, 1);
  322. int P = Command.Pos('"');
  323. if (P)
  324. {
  325. Program = Command.SubString(1, P-1).Trim();
  326. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  327. }
  328. else
  329. {
  330. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, ("\"" + Command)));
  331. }
  332. }
  333. else
  334. {
  335. int P = Command.Pos(" ");
  336. if (P)
  337. {
  338. Program = Command.SubString(1, P).Trim();
  339. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  340. }
  341. else
  342. {
  343. Program = Command;
  344. }
  345. }
  346. int B = Program.LastDelimiter("\\/");
  347. if (B)
  348. {
  349. Dir = Program.SubString(1, B).Trim();
  350. }
  351. }
  352. //---------------------------------------------------------------------------
  353. AnsiString __fastcall ExtractProgram(AnsiString Command)
  354. {
  355. AnsiString Program;
  356. AnsiString Params;
  357. AnsiString Dir;
  358. SplitCommand(Command, Program, Params, Dir);
  359. return Program;
  360. }
  361. //---------------------------------------------------------------------------
  362. AnsiString __fastcall FormatCommand(AnsiString Program, AnsiString Params)
  363. {
  364. Program = Program.Trim();
  365. Params = Params.Trim();
  366. if (!Params.IsEmpty()) Params = " " + Params;
  367. if (Program.Pos(" ")) Program = "\"" + Program + "\"";
  368. return Program + Params;
  369. }
  370. //---------------------------------------------------------------------------
  371. const char ShellCommandFileNamePattern[] = "!.!";
  372. //---------------------------------------------------------------------------
  373. void __fastcall ReformatFileNameCommand(AnsiString & Command)
  374. {
  375. AnsiString Program, Params, Dir;
  376. SplitCommand(Command, Program, Params, Dir);
  377. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  378. {
  379. Params = Params + (Params.IsEmpty() ? "" : " ") + ShellCommandFileNamePattern;
  380. }
  381. Command = FormatCommand(Program, Params);
  382. }
  383. //---------------------------------------------------------------------------
  384. AnsiString __fastcall ExpandFileNameCommand(const AnsiString Command,
  385. const AnsiString FileName)
  386. {
  387. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  388. AddPathQuotes(FileName));
  389. }
  390. //---------------------------------------------------------------------------
  391. AnsiString __fastcall ExpandEnvironmentVariables(const AnsiString & Str)
  392. {
  393. AnsiString Buf;
  394. unsigned int Size = 1024;
  395. Buf.SetLength(Size);
  396. Buf.Unique();
  397. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  398. if (Len > Size)
  399. {
  400. Buf.SetLength(Len);
  401. Buf.Unique();
  402. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  403. }
  404. PackStr(Buf);
  405. return Buf;
  406. }
  407. //---------------------------------------------------------------------------
  408. bool __fastcall CompareFileName(const AnsiString & Path1, const AnsiString & Path2)
  409. {
  410. AnsiString ShortPath1 = ExtractShortPathName(Path1);
  411. AnsiString ShortPath2 = ExtractShortPathName(Path2);
  412. bool Result;
  413. // ExtractShortPathName returns empty string if file does not exist
  414. if (ShortPath1.IsEmpty() || ShortPath2.IsEmpty())
  415. {
  416. Result = AnsiSameText(Path1, Path2);
  417. }
  418. else
  419. {
  420. Result = AnsiSameText(ExtractShortPathName(Path1), ExtractShortPathName(Path2));
  421. }
  422. return Result;
  423. }
  424. //---------------------------------------------------------------------------
  425. bool __fastcall ComparePaths(const AnsiString & Path1, const AnsiString & Path2)
  426. {
  427. // TODO: ExpandUNCFileName
  428. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  429. }
  430. //---------------------------------------------------------------------------
  431. bool __fastcall IsDisplayableStr(const AnsiString Str)
  432. {
  433. bool Displayable = true;
  434. int Index = 1;
  435. while ((Index <= Str.Length()) && Displayable)
  436. {
  437. if (Str[Index] < '\32')
  438. {
  439. Displayable = false;
  440. }
  441. Index++;
  442. }
  443. return Displayable;
  444. }
  445. //---------------------------------------------------------------------------
  446. AnsiString __fastcall CharToHex(char Ch)
  447. {
  448. return IntToHex((unsigned char)Ch, 2);
  449. }
  450. //---------------------------------------------------------------------------
  451. AnsiString __fastcall StrToHex(const AnsiString Str)
  452. {
  453. AnsiString Result;
  454. for (int i = 1; i <= Str.Length(); i++)
  455. {
  456. Result += CharToHex(Str[i]);
  457. }
  458. return Result;
  459. }
  460. //---------------------------------------------------------------------------
  461. AnsiString __fastcall HexToStr(const AnsiString Hex)
  462. {
  463. static AnsiString Digits = "0123456789ABCDEF";
  464. AnsiString Result;
  465. int L, P1, P2;
  466. L = Hex.Length();
  467. if (L % 2 == 0)
  468. {
  469. for (int i = 1; i <= Hex.Length(); i += 2)
  470. {
  471. P1 = Digits.Pos((char)toupper(Hex[i]));
  472. P2 = Digits.Pos((char)toupper(Hex[i + 1]));
  473. if (P1 <= 0 || P2 <= 0)
  474. {
  475. Result = "";
  476. break;
  477. }
  478. else
  479. {
  480. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  481. }
  482. }
  483. }
  484. return Result;
  485. }
  486. //---------------------------------------------------------------------------
  487. unsigned int __fastcall HexToInt(const AnsiString Hex, int MinChars)
  488. {
  489. static AnsiString Digits = "0123456789ABCDEF";
  490. int Result = 0;
  491. int I = 1;
  492. while (I <= Hex.Length())
  493. {
  494. int A = Digits.Pos((char)toupper(Hex[I]));
  495. if (A <= 0)
  496. {
  497. if ((MinChars < 0) || (I <= MinChars))
  498. {
  499. Result = 0;
  500. }
  501. break;
  502. }
  503. Result = (Result * 16) + (A - 1);
  504. I++;
  505. }
  506. return Result;
  507. }
  508. //---------------------------------------------------------------------------
  509. char __fastcall HexToChar(const AnsiString Hex)
  510. {
  511. return (char)HexToInt(Hex);
  512. }
  513. //---------------------------------------------------------------------------
  514. bool __fastcall FileSearchRec(const AnsiString FileName, TSearchRec & Rec)
  515. {
  516. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  517. bool Result = (FindFirst(FileName, FindAttrs, Rec) == 0);
  518. if (Result)
  519. {
  520. FindClose(Rec);
  521. }
  522. return Result;
  523. }
  524. //---------------------------------------------------------------------------
  525. void __fastcall ProcessLocalDirectory(AnsiString DirName,
  526. TProcessLocalFileEvent CallBackFunc, void * Param,
  527. int FindAttrs)
  528. {
  529. assert(CallBackFunc);
  530. if (FindAttrs < 0)
  531. {
  532. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  533. }
  534. TSearchRec SearchRec;
  535. DirName = IncludeTrailingBackslash(DirName);
  536. if (FindFirst(DirName + "*.*", FindAttrs, SearchRec) == 0)
  537. {
  538. try
  539. {
  540. do
  541. {
  542. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  543. {
  544. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  545. }
  546. } while (FindNext(SearchRec) == 0);
  547. }
  548. __finally
  549. {
  550. FindClose(SearchRec);
  551. }
  552. }
  553. }
  554. //---------------------------------------------------------------------------
  555. struct TDateTimeParams
  556. {
  557. TDateTime UnixEpoch;
  558. double BaseDifference;
  559. long BaseDifferenceSec;
  560. double CurrentDaylightDifference;
  561. long CurrentDaylightDifferenceSec;
  562. double CurrentDifference;
  563. long CurrentDifferenceSec;
  564. double StandardDifference;
  565. long StandardDifferenceSec;
  566. double DaylightDifference;
  567. long DaylightDifferenceSec;
  568. SYSTEMTIME StandardDate;
  569. SYSTEMTIME DaylightDate;
  570. };
  571. static bool DateTimeParamsInitialized = false;
  572. static TDateTimeParams DateTimeParams;
  573. static TCriticalSection DateTimeParamsSection;
  574. //---------------------------------------------------------------------------
  575. static TDateTimeParams * __fastcall GetDateTimeParams()
  576. {
  577. if (!DateTimeParamsInitialized)
  578. {
  579. TGuard Guard(&DateTimeParamsSection);
  580. if (!DateTimeParamsInitialized)
  581. {
  582. TIME_ZONE_INFORMATION TZI;
  583. unsigned long GTZI;
  584. GTZI = GetTimeZoneInformation(&TZI);
  585. switch (GTZI)
  586. {
  587. case TIME_ZONE_ID_UNKNOWN:
  588. DateTimeParams.CurrentDifferenceSec = 0;
  589. DateTimeParams.CurrentDaylightDifferenceSec = 0;
  590. break;
  591. case TIME_ZONE_ID_STANDARD:
  592. DateTimeParams.CurrentDaylightDifferenceSec = TZI.StandardBias;
  593. break;
  594. case TIME_ZONE_ID_DAYLIGHT:
  595. DateTimeParams.CurrentDaylightDifferenceSec = TZI.DaylightBias;
  596. break;
  597. case TIME_ZONE_ID_INVALID:
  598. default:
  599. throw Exception(TIMEZONE_ERROR);
  600. }
  601. // Is it same as SysUtils::UnixDateDelta = 25569 ??
  602. DateTimeParams.UnixEpoch = EncodeDate(1970, 1, 1);
  603. DateTimeParams.BaseDifferenceSec = TZI.Bias;
  604. DateTimeParams.BaseDifference = double(TZI.Bias) / 1440;
  605. DateTimeParams.BaseDifferenceSec *= 60;
  606. DateTimeParams.CurrentDifferenceSec = TZI.Bias +
  607. DateTimeParams.CurrentDaylightDifferenceSec;
  608. DateTimeParams.CurrentDifference =
  609. double(DateTimeParams.CurrentDifferenceSec) / 1440;
  610. DateTimeParams.CurrentDifferenceSec *= 60;
  611. DateTimeParams.CurrentDaylightDifference =
  612. double(DateTimeParams.CurrentDaylightDifferenceSec) / 1440;
  613. DateTimeParams.CurrentDaylightDifferenceSec *= 60;
  614. DateTimeParams.DaylightDifferenceSec = TZI.DaylightBias * 60;
  615. DateTimeParams.DaylightDifference = double(TZI.DaylightBias) / 1440;
  616. DateTimeParams.StandardDifferenceSec = TZI.StandardBias * 60;
  617. DateTimeParams.StandardDifference = double(TZI.StandardBias) / 1440;
  618. DateTimeParams.StandardDate = TZI.StandardDate;
  619. DateTimeParams.DaylightDate = TZI.DaylightDate;
  620. DateTimeParamsInitialized = true;
  621. }
  622. }
  623. return &DateTimeParams;
  624. }
  625. //---------------------------------------------------------------------------
  626. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  627. TDateTime & Result)
  628. {
  629. if (Date.wYear == 0)
  630. {
  631. TDateTime Temp = EncodeDate(Year, Date.wMonth, 1);
  632. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  633. (7 * (Date.wDay - 1));
  634. if (Date.wDay == 5)
  635. {
  636. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  637. if (Month > 12)
  638. {
  639. Month = static_cast<unsigned short>(Month - 12);
  640. Year++;
  641. }
  642. if (Result > EncodeDate(Year, Month, 1))
  643. {
  644. Result -= 7;
  645. }
  646. }
  647. Result += EncodeTime(Date.wHour, Date.wMinute, Date.wSecond,
  648. Date.wMilliseconds);
  649. }
  650. else
  651. {
  652. Result = EncodeDate(Year, Date.wMonth, Date.wDay) +
  653. EncodeTime(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  654. }
  655. }
  656. //---------------------------------------------------------------------------
  657. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  658. {
  659. struct TDSTCache
  660. {
  661. bool Filled;
  662. unsigned short Year;
  663. TDateTime StandardDate;
  664. TDateTime DaylightDate;
  665. };
  666. static TDSTCache DSTCache[10];
  667. static int DSTCacheCount = 0;
  668. static TCriticalSection Section;
  669. TDateTimeParams * Params = GetDateTimeParams();
  670. bool Result;
  671. if (Params->StandardDate.wMonth == 0)
  672. {
  673. Result = false;
  674. }
  675. else
  676. {
  677. unsigned short Year, Month, Day;
  678. DecodeDate(DateTime, Year, Month, Day);
  679. TDSTCache * CurrentCache = &DSTCache[0];
  680. int CacheIndex = 0;
  681. while ((CacheIndex < DSTCacheCount) && (CacheIndex < LENOF(DSTCache)) &&
  682. CurrentCache->Filled && (CurrentCache->Year != Year))
  683. {
  684. CacheIndex++;
  685. CurrentCache++;
  686. }
  687. if ((CacheIndex < DSTCacheCount) && (CacheIndex < LENOF(DSTCache)) &&
  688. CurrentCache->Filled)
  689. {
  690. assert(CurrentCache->Year == Year);
  691. Result = (DateTime >= CurrentCache->DaylightDate) &&
  692. (DateTime < CurrentCache->StandardDate);
  693. }
  694. else
  695. {
  696. TDSTCache NewCache;
  697. EncodeDSTMargin(Params->StandardDate, Year, NewCache.StandardDate);
  698. EncodeDSTMargin(Params->DaylightDate, Year, NewCache.DaylightDate);
  699. if (DSTCacheCount < LENOF(DSTCache))
  700. {
  701. TGuard Guard(&Section);
  702. if (DSTCacheCount < LENOF(DSTCache))
  703. {
  704. NewCache.Year = Year;
  705. DSTCache[DSTCacheCount] = NewCache;
  706. DSTCache[DSTCacheCount].Filled = true;
  707. DSTCacheCount++;
  708. }
  709. }
  710. Result = (DateTime >= NewCache.DaylightDate) &&
  711. (DateTime < NewCache.StandardDate);
  712. }
  713. }
  714. return Result;
  715. }
  716. //---------------------------------------------------------------------------
  717. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  718. {
  719. TDateTimeParams * Params = GetDateTimeParams();
  720. TDateTime Result;
  721. Result = Params->UnixEpoch + (double(TimeStamp) / 86400);
  722. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  723. {
  724. Result -= Params->CurrentDifference;
  725. }
  726. else if (DSTMode == dstmKeep)
  727. {
  728. Result -= Params->BaseDifference;
  729. }
  730. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  731. {
  732. Result -= (IsDateInDST(Result) ?
  733. Params->DaylightDifference : Params->StandardDifference);
  734. }
  735. return Result;
  736. }
  737. //---------------------------------------------------------------------------
  738. inline __int64 __fastcall Round(double Number)
  739. {
  740. double Floor = floor(Number);
  741. double Ceil = ceil(Number);
  742. return ((Number - Floor) > (Ceil - Number)) ? Ceil : Floor;
  743. }
  744. //---------------------------------------------------------------------------
  745. #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
  746. ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
  747. #define TIME_WIN_TO_POSIX(ft, t) ((t) = (__int64) \
  748. ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
  749. //---------------------------------------------------------------------------
  750. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  751. {
  752. TDateTimeParams * Params = GetDateTimeParams();
  753. return Round(double(DateTime - Params->UnixEpoch) * 86400) +
  754. Params->CurrentDifferenceSec;
  755. }
  756. //---------------------------------------------------------------------------
  757. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  758. TDSTMode /*DSTMode*/)
  759. {
  760. FILETIME Result;
  761. __int64 UnixTimeStamp = DateTimeToUnix(DateTime);
  762. TIME_POSIX_TO_WIN(UnixTimeStamp, Result);
  763. return Result;
  764. }
  765. //---------------------------------------------------------------------------
  766. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  767. TDSTMode DSTMode)
  768. {
  769. __int64 Result;
  770. TIME_WIN_TO_POSIX(FileTime, Result);
  771. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  772. {
  773. FILETIME LocalFileTime;
  774. SYSTEMTIME SystemTime;
  775. TDateTime DateTime;
  776. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  777. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  778. DateTime = SystemTimeToDateTime(SystemTime);
  779. TDateTimeParams * Params = GetDateTimeParams();
  780. Result += (IsDateInDST(DateTime) ?
  781. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  782. if (DSTMode == dstmKeep)
  783. {
  784. Result -= Params->CurrentDaylightDifferenceSec;
  785. }
  786. }
  787. return Result;
  788. }
  789. //---------------------------------------------------------------------------
  790. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  791. TDSTMode DSTMode)
  792. {
  793. __int64 Result;
  794. if ((FileTime.dwLowDateTime == 0) &&
  795. (FileTime.dwHighDateTime == 0))
  796. {
  797. Result = DateTimeToUnix(Now());
  798. }
  799. else
  800. {
  801. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  802. }
  803. return Result;
  804. }
  805. //---------------------------------------------------------------------------
  806. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  807. {
  808. TDateTimeParams * Params = GetDateTimeParams();
  809. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  810. {
  811. DateTime = DateTime - Params->CurrentDaylightDifference;
  812. }
  813. if (!IsDateInDST(DateTime))
  814. {
  815. if (DSTMode == dstmWin)
  816. {
  817. DateTime = DateTime - Params->DaylightDifference;
  818. }
  819. }
  820. else
  821. {
  822. DateTime = DateTime - Params->StandardDifference;
  823. }
  824. return DateTime;
  825. }
  826. //---------------------------------------------------------------------------
  827. __inline static bool __fastcall UnifySignificance(unsigned short & V1,
  828. unsigned short & V2)
  829. {
  830. bool Result = (V1 == 0) || (V2 == 0);
  831. if (Result)
  832. {
  833. V1 = 0;
  834. V2 = 0;
  835. }
  836. return Result;
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall UnifyDateTimePrecision(TDateTime & DateTime1, TDateTime & DateTime2)
  840. {
  841. unsigned short Y1, M1, D1, H1, N1, S1, MS1;
  842. unsigned short Y2, M2, D2, H2, N2, S2, MS2;
  843. bool Changed;
  844. if (DateTime1 != DateTime2)
  845. {
  846. DateTime1.DecodeDate(&Y1, &M1, &D1);
  847. DateTime1.DecodeTime(&H1, &N1, &S1, &MS1);
  848. DateTime2.DecodeDate(&Y2, &M2, &D2);
  849. DateTime2.DecodeTime(&H2, &N2, &S2, &MS2);
  850. Changed = UnifySignificance(MS1, MS2);
  851. if (Changed && UnifySignificance(S1, S2) && UnifySignificance(N1, N2) &&
  852. UnifySignificance(H1, H2) && UnifySignificance(D1, D2) &&
  853. UnifySignificance(M1, M2))
  854. {
  855. UnifySignificance(Y1, Y2);
  856. }
  857. if (Changed)
  858. {
  859. DateTime1 = EncodeDate(Y1, M1, D1) + EncodeTime(H1, N1, S1, MS1);
  860. DateTime2 = EncodeDate(Y2, M2, D2) + EncodeTime(H2, N2, S2, MS2);
  861. }
  862. }
  863. }
  864. //---------------------------------------------------------------------------
  865. AnsiString __fastcall FixedLenDateTimeFormat(const AnsiString & Format)
  866. {
  867. AnsiString Result = Format;
  868. bool AsIs = false;
  869. int Index = 1;
  870. while (Index <= Result.Length())
  871. {
  872. char F = Result[Index];
  873. if ((F == '\'') || (F == '\"'))
  874. {
  875. AsIs = !AsIs;
  876. Index++;
  877. }
  878. else if (!AsIs && ((F == 'a') || (F == 'A')))
  879. {
  880. if (Result.SubString(Index, 5).LowerCase() == "am/pm")
  881. {
  882. Index += 5;
  883. }
  884. else if (Result.SubString(Index, 3).LowerCase() == "a/p")
  885. {
  886. Index += 3;
  887. }
  888. else if (Result.SubString(Index, 4).LowerCase() == "ampm")
  889. {
  890. Index += 4;
  891. }
  892. else
  893. {
  894. Index++;
  895. }
  896. }
  897. else
  898. {
  899. if (!AsIs && (strchr("dDeEmMhHnNsS", F) != NULL) &&
  900. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  901. {
  902. Result.Insert(F, Index);
  903. }
  904. while ((Index <= Result.Length()) && (F == Result[Index]))
  905. {
  906. Index++;
  907. }
  908. }
  909. }
  910. return Result;
  911. }
  912. //---------------------------------------------------------------------------
  913. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  914. {
  915. // "FAT" time precision
  916. // (when one time is seconds-precision and other is millisecond-precision,
  917. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  918. // be treated the same)
  919. static TDateTime TwoSeconds(0, 0, 2, 0);
  920. int Result;
  921. if (T1 == T2)
  922. {
  923. // just optimalisation
  924. Result = 0;
  925. }
  926. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  927. {
  928. Result = -1;
  929. }
  930. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  931. {
  932. Result = 1;
  933. }
  934. else
  935. {
  936. Result = 0;
  937. }
  938. return Result;
  939. }
  940. //---------------------------------------------------------------------------
  941. bool __fastcall RecursiveDeleteFile(const AnsiString FileName, bool ToRecycleBin)
  942. {
  943. SHFILEOPSTRUCT Data;
  944. memset(&Data, 0, sizeof(Data));
  945. Data.hwnd = NULL;
  946. Data.wFunc = FO_DELETE;
  947. AnsiString FileList(FileName);
  948. FileList.SetLength(FileList.Length() + 2);
  949. FileList[FileList.Length() - 1] = '\0';
  950. FileList[FileList.Length()] = '\0';
  951. Data.pFrom = FileList.c_str();
  952. Data.pTo = "";
  953. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  954. FOF_NOERRORUI | FOF_SILENT;
  955. if (ToRecycleBin)
  956. {
  957. Data.fFlags |= FOF_ALLOWUNDO;
  958. }
  959. int ErrorCode = SHFileOperation(&Data);
  960. bool Result = (ErrorCode == 0);
  961. if (!Result)
  962. {
  963. // according to MSDN, SHFileOperation may return following non-Win32
  964. // error codes
  965. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  966. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  967. (ErrorCode == 0x10074))
  968. {
  969. ErrorCode = 0;
  970. }
  971. SetLastError(ErrorCode);
  972. }
  973. return Result;
  974. }
  975. //---------------------------------------------------------------------------
  976. int __fastcall CancelAnswer(int Answers)
  977. {
  978. int Result;
  979. if ((Answers & qaCancel) != 0)
  980. {
  981. Result = qaCancel;
  982. }
  983. else if ((Answers & qaNo) != 0)
  984. {
  985. Result = qaNo;
  986. }
  987. else if ((Answers & qaAbort) != 0)
  988. {
  989. Result = qaAbort;
  990. }
  991. else if ((Answers & qaOK) != 0)
  992. {
  993. Result = qaOK;
  994. }
  995. else
  996. {
  997. assert(false);
  998. Result = qaCancel;
  999. }
  1000. return Result;
  1001. }
  1002. //---------------------------------------------------------------------------
  1003. int __fastcall AbortAnswer(int Answers)
  1004. {
  1005. int Result;
  1006. if (FLAGSET(Answers, qaAbort))
  1007. {
  1008. Result = qaAbort;
  1009. }
  1010. else
  1011. {
  1012. Result = CancelAnswer(Answers);
  1013. }
  1014. return Result;
  1015. }
  1016. //---------------------------------------------------------------------------
  1017. int __fastcall ContinueAnswer(int Answers)
  1018. {
  1019. int Result;
  1020. if (FLAGSET(Answers, qaSkip))
  1021. {
  1022. Result = qaSkip;
  1023. }
  1024. else if (FLAGSET(Answers, qaIgnore))
  1025. {
  1026. Result = qaIgnore;
  1027. }
  1028. else if (FLAGSET(Answers, qaYes))
  1029. {
  1030. Result = qaYes;
  1031. }
  1032. else if (FLAGSET(Answers, qaOK))
  1033. {
  1034. Result = qaOK;
  1035. }
  1036. else if (FLAGSET(Answers, qaRetry))
  1037. {
  1038. Result = qaRetry;
  1039. }
  1040. else
  1041. {
  1042. Result = CancelAnswer(Answers);
  1043. }
  1044. return Result;
  1045. }
  1046. //---------------------------------------------------------------------------
  1047. TPasLibModule * __fastcall FindModule(void * Instance)
  1048. {
  1049. TPasLibModule * CurModule;
  1050. CurModule = reinterpret_cast<TPasLibModule*>(LibModuleList);
  1051. while (CurModule)
  1052. {
  1053. if (CurModule->Instance == Instance)
  1054. {
  1055. break;
  1056. }
  1057. else
  1058. {
  1059. CurModule = CurModule->Next;
  1060. }
  1061. }
  1062. return CurModule;
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. AnsiString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  1066. {
  1067. TPasLibModule * MainModule = FindModule(HInstance);
  1068. assert(MainModule != NULL);
  1069. AnsiString Result;
  1070. Result.SetLength(MaxLength);
  1071. int Length = LoadString(MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  1072. Result.SetLength(Length);
  1073. return Result;
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. AnsiString __fastcall LoadStrPart(int Ident, int Part)
  1077. {
  1078. AnsiString Result;
  1079. AnsiString Str = LoadStr(Ident);
  1080. while (Part > 0)
  1081. {
  1082. Result = CutToChar(Str, '|', false);
  1083. Part--;
  1084. }
  1085. return Result;
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. AnsiString __fastcall DecodeUrlChars(AnsiString S)
  1089. {
  1090. int i = 1;
  1091. while (i <= S.Length())
  1092. {
  1093. switch (S[i])
  1094. {
  1095. case '+':
  1096. S[i] = ' ';
  1097. break;
  1098. case '%':
  1099. if (i <= S.Length() - 2)
  1100. {
  1101. S[i] = HexToStr(S.SubString(i + 1, 2))[1];
  1102. S.Delete(i + 1, 2);
  1103. }
  1104. break;
  1105. }
  1106. i++;
  1107. }
  1108. return S;
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. AnsiString __fastcall EncodeUrlChars(AnsiString S, AnsiString Ignore)
  1112. {
  1113. AnsiString Encode = "/ ";
  1114. int i = 1;
  1115. while (i <= S.Length())
  1116. {
  1117. if ((Encode.Pos(S[i]) > 0) &&
  1118. (Ignore.Pos(S[i]) == 0))
  1119. {
  1120. AnsiString H = CharToHex(S[i]);
  1121. S.Insert(H, i + 1);
  1122. S[i] = '%';
  1123. i += H.Length();
  1124. }
  1125. i++;
  1126. }
  1127. return S;
  1128. }
  1129. //---------------------------------------------------------------------------
  1130. void __fastcall OemToAnsi(AnsiString & Str)
  1131. {
  1132. if (!Str.IsEmpty())
  1133. {
  1134. Str.Unique();
  1135. OemToChar(Str.c_str(), Str.c_str());
  1136. }
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. void __fastcall AnsiToOem(AnsiString & Str)
  1140. {
  1141. if (!Str.IsEmpty())
  1142. {
  1143. Str.Unique();
  1144. CharToOem(Str.c_str(), Str.c_str());
  1145. }
  1146. }
  1147. //---------------------------------------------------------------------------
  1148. AnsiString __fastcall EscapeHotkey(const AnsiString & Caption)
  1149. {
  1150. return StringReplace(Caption, "&", "&&", TReplaceFlags() << rfReplaceAll);
  1151. }
  1152. //---------------------------------------------------------------------------
  1153. bool __fastcall CutToken(AnsiString & Str, AnsiString & Token)
  1154. {
  1155. bool Result;
  1156. Token = "";
  1157. // inspired by Putty's sftp_getcmd() from PSFTP.C
  1158. int Index = 1;
  1159. while ((Index <= Str.Length()) &&
  1160. ((Str[Index] == ' ') || (Str[Index] == '\t')))
  1161. {
  1162. Index++;
  1163. }
  1164. if (Index <= Str.Length())
  1165. {
  1166. bool Quoting = false;
  1167. while (Index <= Str.Length())
  1168. {
  1169. if (!Quoting && ((Str[Index] == ' ') || (Str[Index] == '\t')))
  1170. {
  1171. break;
  1172. }
  1173. else if ((Str[Index] == '"') && (Index + 1 <= Str.Length()) &&
  1174. (Str[Index + 1] == '"'))
  1175. {
  1176. Index += 2;
  1177. Token += '"';
  1178. }
  1179. else if (Str[Index] == '"')
  1180. {
  1181. Index++;
  1182. Quoting = !Quoting;
  1183. }
  1184. else
  1185. {
  1186. Token += Str[Index];
  1187. Index++;
  1188. }
  1189. }
  1190. if (Index <= Str.Length())
  1191. {
  1192. Index++;
  1193. }
  1194. Str = Str.SubString(Index, Str.Length());
  1195. Result = true;
  1196. }
  1197. else
  1198. {
  1199. Result = false;
  1200. Str = "";
  1201. }
  1202. return Result;
  1203. }