Common.cpp 29 KB

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