Common.cpp 72 KB

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