Common.cpp 60 KB

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