Common.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504
  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"HKU";
  111. else
  112. if (RootKey == HKEY_LOCAL_MACHINE) return L"HKLM";
  113. else
  114. if (RootKey == HKEY_CURRENT_USER) return L"HKCU";
  115. else
  116. if (RootKey == HKEY_CLASSES_ROOT) return L"HKCR";
  117. else
  118. if (RootKey == HKEY_CURRENT_CONFIG) return L"HKCC";
  119. else
  120. if (RootKey == HKEY_DYN_DATA) return L"HKDD";
  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. int __fastcall CompareLogicalText(const UnicodeString & S1, const UnicodeString & S2)
  673. {
  674. return StrCmpLogicalW(S1.c_str(), S2.c_str());
  675. }
  676. //---------------------------------------------------------------------------
  677. bool __fastcall IsReservedName(UnicodeString FileName)
  678. {
  679. int P = FileName.Pos(L".");
  680. int Len = (P > 0) ? P - 1 : FileName.Length();
  681. if ((Len == 3) || (Len == 4))
  682. {
  683. if (P > 0)
  684. {
  685. FileName.SetLength(P - 1);
  686. }
  687. static UnicodeString Reserved[] = {
  688. L"CON", L"PRN", L"AUX", L"NUL",
  689. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  690. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  691. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  692. {
  693. if (SameText(FileName, Reserved[Index]))
  694. {
  695. return true;
  696. }
  697. }
  698. }
  699. return false;
  700. }
  701. //---------------------------------------------------------------------------
  702. // ApiPath support functions
  703. // Inspired by
  704. // http://stackoverflow.com/questions/18580945/need-clarification-for-converting-paths-into-long-unicode-paths-or-the-ones-star
  705. // This can be reimplemented using PathCchCanonicalizeEx on Windows 8 and later
  706. enum PATH_PREFIX_TYPE
  707. {
  708. PPT_UNKNOWN,
  709. PPT_ABSOLUTE, //Found absolute path that is none of the other types
  710. PPT_UNC, //Found \\server\share\ prefix
  711. PPT_LONG_UNICODE, //Found \\?\ prefix
  712. PPT_LONG_UNICODE_UNC, //Found \\?\UNC\ prefix
  713. };
  714. //---------------------------------------------------------------------------
  715. static int __fastcall PathRootLength(UnicodeString Path)
  716. {
  717. // Correction for PathSkipRoot API
  718. // Replace all /'s with \'s because PathSkipRoot can't handle /'s
  719. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  720. // Now call the API
  721. LPCTSTR Buffer = PathSkipRoot(Result.c_str());
  722. return (Buffer != NULL) ? (Buffer - Result.c_str()) : -1;
  723. }
  724. //---------------------------------------------------------------------------
  725. static bool __fastcall PathIsRelative_CorrectedForMicrosoftStupidity(UnicodeString Path)
  726. {
  727. // Correction for PathIsRelative API
  728. // Replace all /'s with \'s because PathIsRelative can't handle /'s
  729. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  730. //Now call the API
  731. return PathIsRelative(Result.c_str());
  732. }
  733. //---------------------------------------------------------------------------
  734. static int __fastcall GetOffsetAfterPathRoot(UnicodeString Path, PATH_PREFIX_TYPE & PrefixType)
  735. {
  736. // Checks if 'pPath' begins with the drive, share, prefix, etc
  737. // EXAMPLES:
  738. // Path Return: Points at: PrefixType:
  739. // Relative\Folder\File.txt 0 Relative\Folder\File.txt PPT_UNKNOWN
  740. // \RelativeToRoot\Folder 1 RelativeToRoot\Folder PPT_ABSOLUTE
  741. // C:\Windows\Folder 3 Windows\Folder PPT_ABSOLUTE
  742. // \\server\share\Desktop 15 Desktop PPT_UNC
  743. // \\?\C:\Windows\Folder 7 Windows\Folder PPT_LONG_UNICODE
  744. // \\?\UNC\server\share\Desktop 21 Desktop PPT_LONG_UNICODE_UNC
  745. // RETURN:
  746. // = Index in 'pPath' after the root, or
  747. // = 0 if no root was found
  748. int Result = 0;
  749. PrefixType = PPT_UNKNOWN;
  750. if (!Path.IsEmpty())
  751. {
  752. int Len = Path.Length();
  753. bool WinXPOnly = !IsWinVista();
  754. // The PathSkipRoot() API doesn't work correctly on Windows XP
  755. if (!WinXPOnly)
  756. {
  757. // Works since Vista and up, but still needs correction :)
  758. int RootLength = PathRootLength(Path);
  759. if (RootLength >= 0)
  760. {
  761. Result = RootLength + 1;
  762. }
  763. }
  764. // Now determine the type of prefix
  765. int IndCheckUNC = -1;
  766. if ((Len >= 8) &&
  767. (Path[1] == L'\\' || Path[1] == L'/') &&
  768. (Path[2] == L'\\' || Path[2] == L'/') &&
  769. (Path[3] == L'?') &&
  770. (Path[4] == L'\\' || Path[4] == L'/') &&
  771. (Path[5] == L'U' || Path[5] == L'u') &&
  772. (Path[6] == L'N' || Path[6] == L'n') &&
  773. (Path[7] == L'C' || Path[7] == L'c') &&
  774. (Path[8] == L'\\' || Path[8] == L'/'))
  775. {
  776. // Found \\?\UNC\ prefix
  777. PrefixType = PPT_LONG_UNICODE_UNC;
  778. if (WinXPOnly)
  779. {
  780. //For older OS
  781. Result += 8;
  782. }
  783. //Check for UNC share later
  784. IndCheckUNC = 8;
  785. }
  786. else if ((Len >= 4) &&
  787. (Path[1] == L'\\' || Path[1] == L'/') &&
  788. (Path[2] == L'\\' || Path[2] == L'/') &&
  789. (Path[3] == L'?') &&
  790. (Path[4] == L'\\' || Path[4] == L'/'))
  791. {
  792. // Found \\?\ prefix
  793. PrefixType = PPT_LONG_UNICODE;
  794. if (WinXPOnly)
  795. {
  796. //For older OS
  797. Result += 4;
  798. }
  799. }
  800. else if ((Len >= 2) &&
  801. (Path[1] == L'\\' || Path[1] == L'/') &&
  802. (Path[2] == L'\\' || Path[2] == L'/'))
  803. {
  804. // Check for UNC share later
  805. IndCheckUNC = 2;
  806. }
  807. if (IndCheckUNC >= 0)
  808. {
  809. // Check for UNC, i.e. \\server\share\ part
  810. int Index = IndCheckUNC;
  811. for (int SkipSlashes = 2; SkipSlashes > 0; SkipSlashes--)
  812. {
  813. for(; Index <= Len; Index++)
  814. {
  815. TCHAR z = Path[Index];
  816. if ((z == L'\\') || (z == L'/') || (Index >= Len))
  817. {
  818. Index++;
  819. if (SkipSlashes == 1)
  820. {
  821. if (PrefixType == PPT_UNKNOWN)
  822. {
  823. PrefixType = PPT_UNC;
  824. }
  825. if (WinXPOnly)
  826. {
  827. //For older OS
  828. Result = Index;
  829. }
  830. }
  831. break;
  832. }
  833. }
  834. }
  835. }
  836. if (WinXPOnly)
  837. {
  838. // Only if we didn't determine any other type
  839. if (PrefixType == PPT_UNKNOWN)
  840. {
  841. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path.SubString(Result, Path.Length() - Result + 1)))
  842. {
  843. PrefixType = PPT_ABSOLUTE;
  844. }
  845. }
  846. // For older OS only
  847. int RootLength = PathRootLength(Path.SubString(Result, Path.Length() - Result + 1));
  848. if (RootLength >= 0)
  849. {
  850. Result = RootLength + 1;
  851. }
  852. }
  853. else
  854. {
  855. // Only if we didn't determine any other type
  856. if (PrefixType == PPT_UNKNOWN)
  857. {
  858. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path))
  859. {
  860. PrefixType = PPT_ABSOLUTE;
  861. }
  862. }
  863. }
  864. }
  865. return Result;
  866. }
  867. //---------------------------------------------------------------------------
  868. UnicodeString __fastcall MakeUnicodeLargePath(UnicodeString Path)
  869. {
  870. // Convert path from 'into a larger Unicode path, that allows up to 32,767 character length
  871. UnicodeString Result;
  872. if (!Path.IsEmpty())
  873. {
  874. // Determine the type of the existing prefix
  875. PATH_PREFIX_TYPE PrefixType;
  876. GetOffsetAfterPathRoot(Path, PrefixType);
  877. // Assume path to be without change
  878. Result = Path;
  879. switch (PrefixType)
  880. {
  881. case PPT_ABSOLUTE:
  882. {
  883. // First we need to check if its an absolute path relative to the root
  884. bool AddPrefix = true;
  885. if ((Path.Length() >= 1) &&
  886. ((Path[1] == L'\\') || (Path[1] == L'/')))
  887. {
  888. AddPrefix = FALSE;
  889. // Get current root path
  890. UnicodeString CurrentDir = GetCurrentDir();
  891. PATH_PREFIX_TYPE PrefixType2; // unused
  892. int Following = GetOffsetAfterPathRoot(CurrentDir, PrefixType2);
  893. if (Following > 0)
  894. {
  895. AddPrefix = true;
  896. Result = CurrentDir.SubString(1, Following - 1) + Result.SubString(2, Result.Length() - 1);
  897. }
  898. }
  899. if (AddPrefix)
  900. {
  901. // Add \\?\ prefix
  902. Result = L"\\\\?\\" + Result;
  903. }
  904. }
  905. break;
  906. case PPT_UNC:
  907. // First we need to remove the opening slashes for UNC share
  908. if ((Result.Length() >= 2) &&
  909. ((Result[1] == L'\\') || (Result[1] == L'/')) &&
  910. ((Result[2] == L'\\') || (Result[2] == L'/')))
  911. {
  912. Result = Result.SubString(3, Result.Length() - 2);
  913. }
  914. // Add \\?\UNC\ prefix
  915. Result = L"\\\\?\\UNC\\" + Result;
  916. break;
  917. }
  918. }
  919. return Result;
  920. }
  921. //---------------------------------------------------------------------------
  922. UnicodeString __fastcall ApiPath(UnicodeString Path)
  923. {
  924. if (Path.Length() >= MAX_PATH)
  925. {
  926. if (Configuration != NULL)
  927. {
  928. Configuration->Usage->Inc(L"LongPath");
  929. }
  930. Path = MakeUnicodeLargePath(Path);
  931. }
  932. return Path;
  933. }
  934. //---------------------------------------------------------------------------
  935. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  936. {
  937. bool Displayable = true;
  938. int Index = 1;
  939. while ((Index <= Str.Length()) && Displayable)
  940. {
  941. if (((Str[Index] < '\x20') || (static_cast<unsigned char>(Str[Index]) >= static_cast<unsigned char>('\x80'))) &&
  942. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  943. {
  944. Displayable = false;
  945. }
  946. Index++;
  947. }
  948. UnicodeString Result;
  949. if (Displayable)
  950. {
  951. Result = L"\"";
  952. for (int Index = 1; Index <= Str.Length(); Index++)
  953. {
  954. switch (Str[Index])
  955. {
  956. case '\n':
  957. Result += L"\\n";
  958. break;
  959. case '\r':
  960. Result += L"\\r";
  961. break;
  962. case '\t':
  963. Result += L"\\t";
  964. break;
  965. case '\b':
  966. Result += L"\\b";
  967. break;
  968. case '\\':
  969. Result += L"\\\\";
  970. break;
  971. case '"':
  972. Result += L"\\\"";
  973. break;
  974. default:
  975. Result += wchar_t(Str[Index]);
  976. break;
  977. }
  978. }
  979. Result += L"\"";
  980. }
  981. else
  982. {
  983. Result = L"0x" + BytesToHex(Str);
  984. }
  985. return Result;
  986. }
  987. //---------------------------------------------------------------------------
  988. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  989. {
  990. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  991. static wchar_t LowerDigits[] = L"0123456789abcdef";
  992. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  993. UnicodeString Result;
  994. Result.SetLength(2);
  995. Result[1] = Digits[(B & 0xF0) >> 4];
  996. Result[2] = Digits[(B & 0x0F) >> 0];
  997. return Result;
  998. }
  999. //---------------------------------------------------------------------------
  1000. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  1001. {
  1002. UnicodeString Result;
  1003. for (size_t i = 0; i < Length; i++)
  1004. {
  1005. Result += ByteToHex(B[i], UpperCase);
  1006. if ((Separator != L'\0') && (i < Length - 1))
  1007. {
  1008. Result += Separator;
  1009. }
  1010. }
  1011. return Result;
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  1015. {
  1016. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  1017. }
  1018. //---------------------------------------------------------------------------
  1019. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  1020. {
  1021. return BytesToHex(reinterpret_cast<const unsigned char *>(&Ch), sizeof(Ch), UpperCase);
  1022. }
  1023. //---------------------------------------------------------------------------
  1024. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  1025. {
  1026. static UnicodeString Digits = L"0123456789ABCDEF";
  1027. RawByteString Result;
  1028. int L, P1, P2;
  1029. L = Hex.Length();
  1030. if (L % 2 == 0)
  1031. {
  1032. for (int i = 1; i <= Hex.Length(); i += 2)
  1033. {
  1034. P1 = Digits.Pos((wchar_t)toupper(Hex[i]));
  1035. P2 = Digits.Pos((wchar_t)toupper(Hex[i + 1]));
  1036. if (P1 <= 0 || P2 <= 0)
  1037. {
  1038. Result = L"";
  1039. break;
  1040. }
  1041. else
  1042. {
  1043. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  1044. }
  1045. }
  1046. }
  1047. return Result;
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  1051. {
  1052. static UnicodeString Digits = L"0123456789ABCDEF";
  1053. assert(Hex.Length() == 2);
  1054. int P1 = Digits.Pos((wchar_t)toupper(Hex[1]));
  1055. int P2 = Digits.Pos((wchar_t)toupper(Hex[2]));
  1056. return
  1057. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  1058. }
  1059. //---------------------------------------------------------------------------
  1060. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  1061. {
  1062. return (Ch >= 'a') && (Ch <= 'z');
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  1066. {
  1067. return (Ch >= 'A') && (Ch <= 'Z');
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. bool __fastcall IsLetter(wchar_t Ch)
  1071. {
  1072. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. bool __fastcall IsDigit(wchar_t Ch)
  1076. {
  1077. return (Ch >= '0') && (Ch <= '9');
  1078. }
  1079. //---------------------------------------------------------------------------
  1080. bool __fastcall IsHex(wchar_t Ch)
  1081. {
  1082. return
  1083. IsDigit(Ch) ||
  1084. ((Ch >= 'A') && (Ch <= 'F')) ||
  1085. ((Ch >= 'a') && (Ch <= 'f'));
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  1089. {
  1090. if ((Result != ERROR_SUCCESS) &&
  1091. (Result != ERROR_FILE_NOT_FOUND) &&
  1092. (Result != ERROR_NO_MORE_FILES))
  1093. {
  1094. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  1095. }
  1096. return Result;
  1097. }
  1098. //---------------------------------------------------------------------------
  1099. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1100. {
  1101. F.Path = Path;
  1102. return FindFirst(ApiPath(Path), Attr, F);
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1106. {
  1107. int Result = FindFirstUnchecked(Path, Attr, F);
  1108. return FindCheck(Result, F.Path);
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  1112. // I.e. even if we do not care that FindFirst failed, if FindNext
  1113. // failes after successfull FindFirst, it mean some terrible problem
  1114. int __fastcall FindNextChecked(TSearchRecChecked & F)
  1115. {
  1116. return FindCheck(FindNext(F), F.Path);
  1117. }
  1118. //---------------------------------------------------------------------------
  1119. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  1120. {
  1121. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1122. bool Result = (FindFirst(ApiPath(FileName), FindAttrs, Rec) == 0);
  1123. if (Result)
  1124. {
  1125. FindClose(Rec);
  1126. }
  1127. return Result;
  1128. }
  1129. //---------------------------------------------------------------------------
  1130. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  1131. TProcessLocalFileEvent CallBackFunc, void * Param,
  1132. int FindAttrs)
  1133. {
  1134. assert(CallBackFunc);
  1135. if (FindAttrs < 0)
  1136. {
  1137. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1138. }
  1139. TSearchRecChecked SearchRec;
  1140. DirName = IncludeTrailingBackslash(DirName);
  1141. if (FindFirstChecked(DirName + L"*.*", FindAttrs, SearchRec) == 0)
  1142. {
  1143. try
  1144. {
  1145. do
  1146. {
  1147. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1148. {
  1149. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  1150. }
  1151. } while (FindNextChecked(SearchRec) == 0);
  1152. }
  1153. __finally
  1154. {
  1155. FindClose(SearchRec);
  1156. }
  1157. }
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  1161. {
  1162. try
  1163. {
  1164. TDateTime DateTime = EncodeDate(Year, Month, Day);
  1165. return DateTime;
  1166. }
  1167. catch (EConvertError & E)
  1168. {
  1169. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  1170. }
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  1174. {
  1175. try
  1176. {
  1177. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  1178. return DateTime;
  1179. }
  1180. catch (EConvertError & E)
  1181. {
  1182. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  1183. }
  1184. }
  1185. //---------------------------------------------------------------------------
  1186. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  1187. {
  1188. try
  1189. {
  1190. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1191. return DateTime;
  1192. }
  1193. catch (EConvertError & E)
  1194. {
  1195. 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))));
  1196. }
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. struct TDateTimeParams
  1200. {
  1201. TDateTime UnixEpoch;
  1202. double BaseDifference;
  1203. long BaseDifferenceSec;
  1204. // All Current* are actually global, not per-year and
  1205. // are valid for Year 0 (current) only
  1206. double CurrentDaylightDifference;
  1207. long CurrentDaylightDifferenceSec;
  1208. double CurrentDifference;
  1209. long CurrentDifferenceSec;
  1210. double StandardDifference;
  1211. long StandardDifferenceSec;
  1212. double DaylightDifference;
  1213. long DaylightDifferenceSec;
  1214. SYSTEMTIME SystemStandardDate;
  1215. SYSTEMTIME SystemDaylightDate;
  1216. TDateTime StandardDate;
  1217. TDateTime DaylightDate;
  1218. UnicodeString StandardName;
  1219. UnicodeString DaylightName;
  1220. // This is actually global, not per-year
  1221. bool DaylightHack;
  1222. bool HasDST() const
  1223. {
  1224. // On some systems it occurs that StandardDate is unset, while
  1225. // DaylightDate is set. MSDN states that this is invalid and
  1226. // should be treated as if there is no daylight saving.
  1227. // So check both.
  1228. return
  1229. (SystemStandardDate.wMonth != 0) &&
  1230. (SystemDaylightDate.wMonth != 0);
  1231. }
  1232. bool SummerDST() const
  1233. {
  1234. return HasDST() && (DaylightDate < StandardDate);
  1235. }
  1236. };
  1237. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  1238. static TYearlyDateTimeParams YearlyDateTimeParams;
  1239. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(new TCriticalSection());
  1240. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1241. TDateTime & Result);
  1242. //---------------------------------------------------------------------------
  1243. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  1244. {
  1245. unsigned short Year, Month, Day;
  1246. DecodeDate(DateTime, Year, Month, Day);
  1247. return Year;
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  1251. {
  1252. TGuard Guard(DateTimeParamsSection.get());
  1253. TDateTimeParams * Result;
  1254. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  1255. if (i != YearlyDateTimeParams.end())
  1256. {
  1257. Result = &(*i).second;
  1258. }
  1259. else
  1260. {
  1261. // creates new entry as a side effect
  1262. Result = &YearlyDateTimeParams[Year];
  1263. TIME_ZONE_INFORMATION TZI;
  1264. unsigned long GTZI;
  1265. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1266. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  1267. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  1268. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  1269. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  1270. {
  1271. GTZI = GetTimeZoneInformation(&TZI);
  1272. }
  1273. else
  1274. {
  1275. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1276. GTZI = TIME_ZONE_ID_UNKNOWN;
  1277. }
  1278. switch (GTZI)
  1279. {
  1280. case TIME_ZONE_ID_UNKNOWN:
  1281. Result->CurrentDaylightDifferenceSec = 0;
  1282. break;
  1283. case TIME_ZONE_ID_STANDARD:
  1284. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1285. break;
  1286. case TIME_ZONE_ID_DAYLIGHT:
  1287. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1288. break;
  1289. case TIME_ZONE_ID_INVALID:
  1290. default:
  1291. throw Exception(TIMEZONE_ERROR);
  1292. }
  1293. Result->BaseDifferenceSec = TZI.Bias;
  1294. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1295. Result->BaseDifferenceSec *= SecsPerMin;
  1296. Result->CurrentDifferenceSec = TZI.Bias +
  1297. Result->CurrentDaylightDifferenceSec;
  1298. Result->CurrentDifference =
  1299. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1300. Result->CurrentDifferenceSec *= SecsPerMin;
  1301. Result->CurrentDaylightDifference =
  1302. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1303. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1304. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1305. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1306. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1307. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1308. Result->SystemStandardDate = TZI.StandardDate;
  1309. Result->SystemDaylightDate = TZI.DaylightDate;
  1310. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1311. if (Result->HasDST())
  1312. {
  1313. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1314. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1315. }
  1316. Result->StandardName = TZI.StandardName;
  1317. Result->DaylightName = TZI.DaylightName;
  1318. Result->DaylightHack = !IsWin7();
  1319. }
  1320. return Result;
  1321. }
  1322. //---------------------------------------------------------------------------
  1323. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1324. TDateTime & Result)
  1325. {
  1326. if (Date.wYear == 0)
  1327. {
  1328. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1329. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1330. (7 * (Date.wDay - 1));
  1331. // Day 5 means, the last occurence of day-of-week in month
  1332. if (Date.wDay == 5)
  1333. {
  1334. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1335. if (Month > 12)
  1336. {
  1337. Month = static_cast<unsigned short>(Month - 12);
  1338. Year++;
  1339. }
  1340. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1341. {
  1342. Result -= 7;
  1343. }
  1344. }
  1345. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1346. Date.wMilliseconds);
  1347. }
  1348. else
  1349. {
  1350. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1351. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1352. }
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1356. {
  1357. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1358. bool Result;
  1359. // On some systems it occurs that StandardDate is unset, while
  1360. // DaylightDate is set. MSDN states that this is invalid and
  1361. // should be treated as if there is no daylight saving.
  1362. // So check both.
  1363. if (!Params->HasDST())
  1364. {
  1365. Result = false;
  1366. }
  1367. else
  1368. {
  1369. if (Params->SummerDST())
  1370. {
  1371. Result =
  1372. (DateTime >= Params->DaylightDate) &&
  1373. (DateTime < Params->StandardDate);
  1374. }
  1375. else
  1376. {
  1377. Result =
  1378. (DateTime < Params->StandardDate) ||
  1379. (DateTime >= Params->DaylightDate);
  1380. }
  1381. }
  1382. return Result;
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. bool __fastcall UsesDaylightHack()
  1386. {
  1387. return GetDateTimeParams(0)->DaylightHack;
  1388. }
  1389. //---------------------------------------------------------------------------
  1390. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1391. {
  1392. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1393. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1394. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1395. if (Params->DaylightHack)
  1396. {
  1397. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1398. {
  1399. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1400. Result -= CurrentParams->CurrentDifference;
  1401. }
  1402. else if (DSTMode == dstmKeep)
  1403. {
  1404. Result -= Params->BaseDifference;
  1405. }
  1406. }
  1407. else
  1408. {
  1409. Result -= Params->BaseDifference;
  1410. }
  1411. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1412. {
  1413. Result -= (IsDateInDST(Result) ?
  1414. Params->DaylightDifference : Params->StandardDifference);
  1415. }
  1416. return Result;
  1417. }
  1418. //---------------------------------------------------------------------------
  1419. __int64 __fastcall Round(double Number)
  1420. {
  1421. double Floor = floor(Number);
  1422. double Ceil = ceil(Number);
  1423. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1424. }
  1425. //---------------------------------------------------------------------------
  1426. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime)
  1427. {
  1428. S = S.Trim();
  1429. int Index = 1;
  1430. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1431. {
  1432. Index++;
  1433. }
  1434. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1435. int Number;
  1436. bool Result = TryStrToInt(NumberStr, Number);
  1437. if (Result)
  1438. {
  1439. S.Delete(1, Index - 1);
  1440. S = S.Trim().UpperCase();
  1441. DateTime = Now();
  1442. // These may not overlap with ParseSize (K, M and G)
  1443. if (S == "S")
  1444. {
  1445. DateTime = IncSecond(DateTime, -Number);
  1446. }
  1447. else if (S == "N")
  1448. {
  1449. DateTime = IncMinute(DateTime, -Number);
  1450. }
  1451. else if (S == "H")
  1452. {
  1453. DateTime = IncHour(DateTime, -Number);
  1454. }
  1455. else if (S == "D")
  1456. {
  1457. DateTime = IncDay(DateTime, -Number);
  1458. }
  1459. else if (S == "Y")
  1460. {
  1461. DateTime = IncYear(DateTime, -Number);
  1462. }
  1463. else
  1464. {
  1465. Result = false;
  1466. }
  1467. }
  1468. return Result;
  1469. }
  1470. //---------------------------------------------------------------------------
  1471. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1472. {
  1473. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1474. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1475. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1476. CurrentParams->CurrentDifferenceSec;
  1477. }
  1478. //---------------------------------------------------------------------------
  1479. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1480. TDSTMode /*DSTMode*/)
  1481. {
  1482. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1483. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1484. if (!Params->DaylightHack)
  1485. {
  1486. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  1487. // We are incrementing and decrementing BaseDifferenceSec because it
  1488. // can actually change between years
  1489. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  1490. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1491. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  1492. Params->BaseDifferenceSec;
  1493. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1494. UnixTimeStamp -=
  1495. CurrentParams->CurrentDaylightDifferenceSec +
  1496. CurrentParams->BaseDifferenceSec;
  1497. }
  1498. FILETIME Result;
  1499. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1500. return Result;
  1501. }
  1502. //---------------------------------------------------------------------------
  1503. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1504. {
  1505. // duplicated in DirView.pas
  1506. TDateTime Result;
  1507. // The 0xFFF... is sometime seen for invalid timestamps,
  1508. // it would cause failure in SystemTimeToDateTime below
  1509. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  1510. {
  1511. Result = MinDateTime;
  1512. }
  1513. else
  1514. {
  1515. SYSTEMTIME SysTime;
  1516. if (!UsesDaylightHack())
  1517. {
  1518. SYSTEMTIME UniverzalSysTime;
  1519. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1520. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1521. }
  1522. else
  1523. {
  1524. FILETIME LocalFileTime;
  1525. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1526. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1527. }
  1528. Result = SystemTimeToDateTimeVerbose(SysTime);
  1529. }
  1530. return Result;
  1531. }
  1532. //---------------------------------------------------------------------------
  1533. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1534. TDSTMode DSTMode)
  1535. {
  1536. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1537. if (UsesDaylightHack())
  1538. {
  1539. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1540. {
  1541. FILETIME LocalFileTime;
  1542. SYSTEMTIME SystemTime;
  1543. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1544. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1545. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1546. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1547. Result += (IsDateInDST(DateTime) ?
  1548. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1549. if (DSTMode == dstmKeep)
  1550. {
  1551. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1552. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1553. }
  1554. }
  1555. }
  1556. else
  1557. {
  1558. if (DSTMode == dstmWin)
  1559. {
  1560. FILETIME LocalFileTime;
  1561. SYSTEMTIME SystemTime;
  1562. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1563. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1564. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1565. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1566. Result -= (IsDateInDST(DateTime) ?
  1567. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1568. }
  1569. }
  1570. return Result;
  1571. }
  1572. //---------------------------------------------------------------------------
  1573. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1574. {
  1575. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1576. DateTime +=
  1577. (IsDateInDST(DateTime) ?
  1578. Params->DaylightDifference : Params->StandardDifference);
  1579. DateTime += Params->BaseDifference;
  1580. if (Params->DaylightHack)
  1581. {
  1582. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1583. DateTime += CurrentParams->CurrentDaylightDifference;
  1584. }
  1585. return DateTime;
  1586. }
  1587. //---------------------------------------------------------------------------
  1588. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1589. {
  1590. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1591. DateTime -=
  1592. (IsDateInDST(DateTime) ?
  1593. Params->DaylightDifference : Params->StandardDifference);
  1594. DateTime -= Params->BaseDifference;
  1595. if (Params->DaylightHack)
  1596. {
  1597. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1598. DateTime -= CurrentParams->CurrentDaylightDifference;
  1599. }
  1600. return DateTime;
  1601. }
  1602. //---------------------------------------------------------------------------
  1603. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1604. TDSTMode DSTMode)
  1605. {
  1606. __int64 Result;
  1607. if ((FileTime.dwLowDateTime == 0) &&
  1608. (FileTime.dwHighDateTime == 0))
  1609. {
  1610. Result = ::DateTimeToUnix(Now());
  1611. }
  1612. else
  1613. {
  1614. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1615. }
  1616. return Result;
  1617. }
  1618. //---------------------------------------------------------------------------
  1619. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1620. {
  1621. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1622. if (Params->DaylightHack)
  1623. {
  1624. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1625. {
  1626. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1627. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  1628. }
  1629. if (!IsDateInDST(DateTime))
  1630. {
  1631. if (DSTMode == dstmWin)
  1632. {
  1633. DateTime = DateTime - Params->DaylightDifference;
  1634. }
  1635. }
  1636. else
  1637. {
  1638. DateTime = DateTime - Params->StandardDifference;
  1639. }
  1640. }
  1641. else
  1642. {
  1643. if (DSTMode == dstmWin)
  1644. {
  1645. if (IsDateInDST(DateTime))
  1646. {
  1647. DateTime = DateTime + Params->DaylightDifference;
  1648. }
  1649. else
  1650. {
  1651. DateTime = DateTime + Params->StandardDifference;
  1652. }
  1653. }
  1654. }
  1655. return DateTime;
  1656. }
  1657. //---------------------------------------------------------------------------
  1658. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  1659. {
  1660. UnicodeString Result = Format;
  1661. bool AsIs = false;
  1662. int Index = 1;
  1663. while (Index <= Result.Length())
  1664. {
  1665. wchar_t F = Result[Index];
  1666. if ((F == L'\'') || (F == L'\"'))
  1667. {
  1668. AsIs = !AsIs;
  1669. Index++;
  1670. }
  1671. else if (!AsIs && ((F == L'a') || (F == L'A')))
  1672. {
  1673. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  1674. {
  1675. Index += 5;
  1676. }
  1677. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  1678. {
  1679. Index += 3;
  1680. }
  1681. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  1682. {
  1683. Index += 4;
  1684. }
  1685. else
  1686. {
  1687. Index++;
  1688. }
  1689. }
  1690. else
  1691. {
  1692. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  1693. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1694. {
  1695. Result.Insert(F, Index);
  1696. }
  1697. while ((Index <= Result.Length()) && (F == Result[Index]))
  1698. {
  1699. Index++;
  1700. }
  1701. }
  1702. }
  1703. return Result;
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. UnicodeString __fastcall FormatTimeZone(long Sec)
  1707. {
  1708. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  1709. UnicodeString Str;
  1710. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  1711. {
  1712. Str = FORMAT(L"%d", (-Span.Hours));
  1713. }
  1714. else if (Span.Seconds == 0)
  1715. {
  1716. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  1717. }
  1718. else
  1719. {
  1720. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  1721. }
  1722. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  1723. return Str;
  1724. }
  1725. //---------------------------------------------------------------------------
  1726. UnicodeString __fastcall GetTimeZoneLogString()
  1727. {
  1728. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1729. UnicodeString Result =
  1730. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  1731. if (!CurrentParams->HasDST())
  1732. {
  1733. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  1734. }
  1735. else
  1736. {
  1737. Result +=
  1738. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  1739. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  1740. CurrentParams->StandardName,
  1741. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  1742. CurrentParams->DaylightName,
  1743. CurrentParams->DaylightDate.DateString(),
  1744. CurrentParams->StandardDate.DateString()));
  1745. }
  1746. return Result;
  1747. }
  1748. //---------------------------------------------------------------------------
  1749. bool __fastcall AdjustClockForDSTEnabled()
  1750. {
  1751. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  1752. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  1753. bool DynamicDaylightTimeDisabled = false;
  1754. TRegistry * Registry = new TRegistry(KEY_READ);
  1755. try
  1756. {
  1757. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1758. if (Registry->OpenKey(L"SYSTEM", false) &&
  1759. Registry->OpenKey(L"CurrentControlSet", false) &&
  1760. Registry->OpenKey(L"Control", false) &&
  1761. Registry->OpenKey(L"TimeZoneInformation", false))
  1762. {
  1763. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  1764. {
  1765. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  1766. }
  1767. // WORKAROUND
  1768. // Windows XP equivalent
  1769. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  1770. {
  1771. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  1772. }
  1773. }
  1774. delete Registry;
  1775. }
  1776. catch(...)
  1777. {
  1778. }
  1779. return !DynamicDaylightTimeDisabled;
  1780. }
  1781. //---------------------------------------------------------------------------
  1782. UnicodeString __fastcall StandardDatestamp()
  1783. {
  1784. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  1785. }
  1786. //---------------------------------------------------------------------------
  1787. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  1788. {
  1789. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  1790. }
  1791. //---------------------------------------------------------------------------
  1792. UnicodeString __fastcall StandardTimestamp()
  1793. {
  1794. return StandardTimestamp(Now());
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. static TDateTime TwoSeconds(0, 0, 2, 0);
  1798. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1799. {
  1800. // "FAT" time precision
  1801. // (when one time is seconds-precision and other is millisecond-precision,
  1802. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1803. // be treated the same)
  1804. int Result;
  1805. if (T1 == T2)
  1806. {
  1807. // just optimization
  1808. Result = 0;
  1809. }
  1810. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1811. {
  1812. Result = -1;
  1813. }
  1814. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1815. {
  1816. Result = 1;
  1817. }
  1818. else
  1819. {
  1820. Result = 0;
  1821. }
  1822. return Result;
  1823. }
  1824. //---------------------------------------------------------------------------
  1825. int __fastcall TimeToMSec(TDateTime T)
  1826. {
  1827. return int(Round(double(T) * double(MSecsPerDay)));
  1828. }
  1829. //---------------------------------------------------------------------------
  1830. int __fastcall TimeToSeconds(TDateTime T)
  1831. {
  1832. return TimeToMSec(T) / MSecsPerSec;
  1833. }
  1834. //---------------------------------------------------------------------------
  1835. int __fastcall TimeToMinutes(TDateTime T)
  1836. {
  1837. return TimeToSeconds(T) / SecsPerMin;
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. bool __fastcall RecursiveDeleteFile(const UnicodeString FileName, bool ToRecycleBin)
  1841. {
  1842. SHFILEOPSTRUCT Data;
  1843. memset(&Data, 0, sizeof(Data));
  1844. Data.hwnd = NULL;
  1845. Data.wFunc = FO_DELETE;
  1846. // SHFileOperation does not support long paths anyway
  1847. UnicodeString FileList(ApiPath(FileName));
  1848. FileList.SetLength(FileList.Length() + 2);
  1849. FileList[FileList.Length() - 1] = L'\0';
  1850. FileList[FileList.Length()] = L'\0';
  1851. Data.pFrom = FileList.c_str();
  1852. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  1853. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1854. FOF_NOERRORUI | FOF_SILENT;
  1855. if (ToRecycleBin)
  1856. {
  1857. Data.fFlags |= FOF_ALLOWUNDO;
  1858. }
  1859. int ErrorCode = SHFileOperation(&Data);
  1860. bool Result = (ErrorCode == 0);
  1861. if (!Result)
  1862. {
  1863. // according to MSDN, SHFileOperation may return following non-Win32
  1864. // error codes
  1865. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  1866. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  1867. (ErrorCode == 0x10074))
  1868. {
  1869. ErrorCode = 0;
  1870. }
  1871. SetLastError(ErrorCode);
  1872. }
  1873. return Result;
  1874. }
  1875. //---------------------------------------------------------------------------
  1876. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  1877. {
  1878. if (!DeleteFile(ApiPath(FileName)))
  1879. {
  1880. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  1881. }
  1882. }
  1883. //---------------------------------------------------------------------------
  1884. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  1885. {
  1886. unsigned int Result;
  1887. if ((Answers & qaCancel) != 0)
  1888. {
  1889. Result = qaCancel;
  1890. }
  1891. else if ((Answers & qaNo) != 0)
  1892. {
  1893. Result = qaNo;
  1894. }
  1895. else if ((Answers & qaAbort) != 0)
  1896. {
  1897. Result = qaAbort;
  1898. }
  1899. else if ((Answers & qaOK) != 0)
  1900. {
  1901. Result = qaOK;
  1902. }
  1903. else
  1904. {
  1905. FAIL;
  1906. Result = qaCancel;
  1907. }
  1908. return Result;
  1909. }
  1910. //---------------------------------------------------------------------------
  1911. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  1912. {
  1913. unsigned int Result;
  1914. if (FLAGSET(Answers, qaAbort))
  1915. {
  1916. Result = qaAbort;
  1917. }
  1918. else
  1919. {
  1920. Result = CancelAnswer(Answers);
  1921. }
  1922. return Result;
  1923. }
  1924. //---------------------------------------------------------------------------
  1925. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  1926. {
  1927. unsigned int Result;
  1928. if (FLAGSET(Answers, qaSkip))
  1929. {
  1930. Result = qaSkip;
  1931. }
  1932. else if (FLAGSET(Answers, qaIgnore))
  1933. {
  1934. Result = qaIgnore;
  1935. }
  1936. else if (FLAGSET(Answers, qaYes))
  1937. {
  1938. Result = qaYes;
  1939. }
  1940. else if (FLAGSET(Answers, qaOK))
  1941. {
  1942. Result = qaOK;
  1943. }
  1944. else if (FLAGSET(Answers, qaRetry))
  1945. {
  1946. Result = qaRetry;
  1947. }
  1948. else
  1949. {
  1950. Result = CancelAnswer(Answers);
  1951. }
  1952. return Result;
  1953. }
  1954. //---------------------------------------------------------------------------
  1955. TLibModule * __fastcall FindModule(void * Instance)
  1956. {
  1957. TLibModule * CurModule;
  1958. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  1959. while (CurModule)
  1960. {
  1961. if (CurModule->Instance == (unsigned)Instance)
  1962. {
  1963. break;
  1964. }
  1965. else
  1966. {
  1967. CurModule = CurModule->Next;
  1968. }
  1969. }
  1970. return CurModule;
  1971. }
  1972. //---------------------------------------------------------------------------
  1973. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  1974. {
  1975. TLibModule * MainModule = FindModule(HInstance);
  1976. assert(MainModule != NULL);
  1977. UnicodeString Result;
  1978. Result.SetLength(MaxLength);
  1979. int Length = LoadString((HINSTANCE)MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  1980. Result.SetLength(Length);
  1981. return Result;
  1982. }
  1983. //---------------------------------------------------------------------------
  1984. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  1985. {
  1986. UnicodeString Result;
  1987. UnicodeString Str = LoadStr(Ident);
  1988. while (Part > 0)
  1989. {
  1990. Result = CutToChar(Str, L'|', false);
  1991. Part--;
  1992. }
  1993. return Result;
  1994. }
  1995. //---------------------------------------------------------------------------
  1996. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  1997. {
  1998. int i = 1;
  1999. while (i <= S.Length())
  2000. {
  2001. switch (S[i])
  2002. {
  2003. case L'+':
  2004. S[i] = ' ';
  2005. break;
  2006. case L'%':
  2007. {
  2008. UnicodeString Hex;
  2009. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2010. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2011. {
  2012. Hex += S.SubString(i + 1, 2);
  2013. S.Delete(i, 3);
  2014. }
  2015. if (!Hex.IsEmpty())
  2016. {
  2017. RawByteString Bytes = HexToBytes(Hex);
  2018. UTF8String UTF8(Bytes.c_str(), Bytes.Length());
  2019. UnicodeString Chars(UTF8);
  2020. S.Insert(Chars, i);
  2021. i += Chars.Length() - 1;
  2022. }
  2023. }
  2024. break;
  2025. }
  2026. i++;
  2027. }
  2028. return S;
  2029. }
  2030. //---------------------------------------------------------------------------
  2031. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, UnicodeString Chars)
  2032. {
  2033. int i = 1;
  2034. while (i <= S.Length())
  2035. {
  2036. if (Chars.Pos(S[i]) > 0)
  2037. {
  2038. UnicodeString H = ByteToHex(AnsiString(UnicodeString(S[i]))[1]);
  2039. S.Insert(H, i + 1);
  2040. S[i] = '%';
  2041. i += H.Length();
  2042. }
  2043. i++;
  2044. }
  2045. return S;
  2046. }
  2047. //---------------------------------------------------------------------------
  2048. // we should probably replace all uses with EncodeUrlString
  2049. UnicodeString __fastcall EncodeUrlChars(UnicodeString S)
  2050. {
  2051. return DoEncodeUrl(S, L" /");
  2052. }
  2053. //---------------------------------------------------------------------------
  2054. UnicodeString __fastcall NonUrlChars()
  2055. {
  2056. UnicodeString S;
  2057. for (unsigned int I = 0; I <= 127; I++)
  2058. {
  2059. wchar_t C = static_cast<wchar_t>(I);
  2060. if (IsLetter(C) ||
  2061. IsDigit(C) ||
  2062. (C == L'_') || (C == L'-') || (C == L'.'))
  2063. {
  2064. // noop
  2065. }
  2066. else
  2067. {
  2068. S += C;
  2069. }
  2070. }
  2071. return S;
  2072. }
  2073. //---------------------------------------------------------------------------
  2074. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  2075. {
  2076. return DoEncodeUrl(S, NonUrlChars());
  2077. }
  2078. //---------------------------------------------------------------------------
  2079. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2080. {
  2081. UnicodeString Ignore = NonUrlChars();
  2082. int P = Ignore.Pos(L"/");
  2083. if (ALWAYS_TRUE(P > 0))
  2084. {
  2085. Ignore.Delete(P, 1);
  2086. }
  2087. return DoEncodeUrl(S, Ignore);
  2088. }
  2089. //---------------------------------------------------------------------------
  2090. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2091. {
  2092. // see also TWebHelpSystem::ShowHelp
  2093. const wchar_t FragmentSeparator = L'#';
  2094. UnicodeString URL = ::CutToChar(AURL, FragmentSeparator, false);
  2095. if (URL.Pos(L"?") == 0)
  2096. {
  2097. URL += L"?";
  2098. }
  2099. else
  2100. {
  2101. URL += L"&";
  2102. }
  2103. URL += Params;
  2104. AddToList(URL, AURL, FragmentSeparator);
  2105. return URL;
  2106. }
  2107. //---------------------------------------------------------------------------
  2108. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2109. {
  2110. return ReplaceStr(Caption, L"&", L"&&");
  2111. }
  2112. //---------------------------------------------------------------------------
  2113. // duplicated in console's Main.cpp
  2114. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2115. UnicodeString * RawToken)
  2116. {
  2117. bool Result;
  2118. Token = L"";
  2119. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2120. int Index = 1;
  2121. while ((Index <= Str.Length()) &&
  2122. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2123. {
  2124. Index++;
  2125. }
  2126. if (Index <= Str.Length())
  2127. {
  2128. bool Quoting = false;
  2129. while (Index <= Str.Length())
  2130. {
  2131. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2132. {
  2133. break;
  2134. }
  2135. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2136. (Str[Index + 1] == L'"'))
  2137. {
  2138. Index += 2;
  2139. Token += L'"';
  2140. }
  2141. else if (Str[Index] == L'"')
  2142. {
  2143. Index++;
  2144. Quoting = !Quoting;
  2145. }
  2146. else
  2147. {
  2148. Token += Str[Index];
  2149. Index++;
  2150. }
  2151. }
  2152. if (RawToken != NULL)
  2153. {
  2154. (*RawToken) = Str.SubString(1, Index - 1);
  2155. }
  2156. if (Index <= Str.Length())
  2157. {
  2158. Index++;
  2159. }
  2160. Str = Str.SubString(Index, Str.Length());
  2161. Result = true;
  2162. }
  2163. else
  2164. {
  2165. Result = false;
  2166. Str = L"";
  2167. }
  2168. return Result;
  2169. }
  2170. //---------------------------------------------------------------------------
  2171. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2172. {
  2173. if (!Value.IsEmpty())
  2174. {
  2175. if (!List.IsEmpty() &&
  2176. ((List.Length() < Delimiter.Length()) ||
  2177. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2178. {
  2179. List += Delimiter;
  2180. }
  2181. List += Value;
  2182. }
  2183. }
  2184. //---------------------------------------------------------------------------
  2185. bool __fastcall IsWinVista()
  2186. {
  2187. // Vista is 6.0
  2188. // Win XP is 5.1
  2189. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  2190. // (we consider it WinXP for now)
  2191. return CheckWin32Version(6, 0);
  2192. }
  2193. //---------------------------------------------------------------------------
  2194. bool __fastcall IsWin7()
  2195. {
  2196. return CheckWin32Version(6, 1);
  2197. }
  2198. //---------------------------------------------------------------------------
  2199. bool __fastcall IsWine()
  2200. {
  2201. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2202. return
  2203. ALWAYS_TRUE(NtDll != NULL) &&
  2204. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2205. }
  2206. //---------------------------------------------------------------------------
  2207. LCID __fastcall GetDefaultLCID()
  2208. {
  2209. return GetUserDefaultLCID();
  2210. }
  2211. //---------------------------------------------------------------------------
  2212. static UnicodeString ADefaultEncodingName;
  2213. UnicodeString __fastcall DefaultEncodingName()
  2214. {
  2215. if (ADefaultEncodingName.IsEmpty())
  2216. {
  2217. CPINFOEX Info;
  2218. GetCPInfoEx(CP_ACP, 0, &Info);
  2219. ADefaultEncodingName = Info.CodePageName;
  2220. }
  2221. return ADefaultEncodingName;
  2222. }
  2223. //---------------------------------------------------------------------------
  2224. bool _fastcall GetWindowsProductType(DWORD & Type)
  2225. {
  2226. bool Result;
  2227. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2228. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  2229. TGetProductInfo GetProductInfo =
  2230. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  2231. if (GetProductInfo == NULL)
  2232. {
  2233. Result = false;
  2234. }
  2235. else
  2236. {
  2237. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  2238. Result = true;
  2239. }
  2240. return Result;
  2241. }
  2242. //---------------------------------------------------------------------------
  2243. UnicodeString __fastcall WindowsProductName()
  2244. {
  2245. UnicodeString Result;
  2246. TRegistry * Registry = new TRegistry(KEY_READ);
  2247. try
  2248. {
  2249. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2250. if (Registry->OpenKey(L"SOFTWARE", false) &&
  2251. Registry->OpenKey(L"Microsoft", false) &&
  2252. Registry->OpenKey(L"Windows NT", false) &&
  2253. Registry->OpenKey(L"CurrentVersion", false))
  2254. {
  2255. Result = Registry->ReadString(L"ProductName");
  2256. }
  2257. delete Registry;
  2258. }
  2259. catch(...)
  2260. {
  2261. }
  2262. return Result;
  2263. }
  2264. //---------------------------------------------------------------------------
  2265. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  2266. {
  2267. UnicodeString FileName =
  2268. IncludeTrailingPathDelimiter(Path) +
  2269. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  2270. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  2271. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  2272. bool Result = (Handle != INVALID_HANDLE_VALUE);
  2273. if (Result)
  2274. {
  2275. CloseHandle(Handle);
  2276. }
  2277. return Result;
  2278. }
  2279. //---------------------------------------------------------------------------
  2280. UnicodeString __fastcall FormatNumber(__int64 Number)
  2281. {
  2282. return FormatFloat(L"#,##0", Number);
  2283. }
  2284. //---------------------------------------------------------------------------
  2285. // simple alternative to FormatBytes
  2286. UnicodeString __fastcall FormatSize(__int64 Size)
  2287. {
  2288. return FormatNumber(Size);
  2289. }
  2290. //---------------------------------------------------------------------------
  2291. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  2292. {
  2293. return ChangeFileExt(ExtractFileName(Path), L"");
  2294. }
  2295. //---------------------------------------------------------------------------
  2296. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  2297. {
  2298. std::unique_ptr<TStringList> List(new TStringList());
  2299. List->Text = Text;
  2300. return List.release();
  2301. }
  2302. //---------------------------------------------------------------------------
  2303. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  2304. {
  2305. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  2306. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  2307. {
  2308. Version.SetLength(Version.Length() - 2);
  2309. }
  2310. return Version;
  2311. }
  2312. //---------------------------------------------------------------------------
  2313. UnicodeString __fastcall FormatVersion(int MajovVersion, int MinorVersion, int Release)
  2314. {
  2315. return
  2316. TrimVersion(FORMAT(L"%d.%d.%d",
  2317. (MajovVersion, MinorVersion, Release)));
  2318. }
  2319. //---------------------------------------------------------------------------
  2320. TFormatSettings __fastcall GetEngFormatSettings()
  2321. {
  2322. return TFormatSettings::Create((TLocaleID)1033);
  2323. }
  2324. //---------------------------------------------------------------------------
  2325. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  2326. {
  2327. TFormatSettings FormatSettings = GetEngFormatSettings();
  2328. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  2329. }
  2330. //---------------------------------------------------------------------------
  2331. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  2332. {
  2333. TStringList * Result = new TStringList();
  2334. Result->CaseSensitive = CaseSensitive;
  2335. Result->Duplicates = Duplicates;
  2336. return Result;
  2337. }
  2338. //---------------------------------------------------------------------------
  2339. static UnicodeString __fastcall NormalizeIdent(UnicodeString Ident)
  2340. {
  2341. int Index = 1;
  2342. while (Index <= Ident.Length())
  2343. {
  2344. if (Ident[Index] == L'-')
  2345. {
  2346. Ident.Delete(Index, 1);
  2347. }
  2348. else
  2349. {
  2350. Index++;
  2351. }
  2352. }
  2353. return Ident;
  2354. }
  2355. //---------------------------------------------------------------------------
  2356. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  2357. {
  2358. UnicodeString NormalizedIdent(NormalizeIdent(Ident));
  2359. for (int Index = 0; Index < Idents->Count; Index++)
  2360. {
  2361. if (SameText(NormalizedIdent, NormalizeIdent(Idents->Strings[Index])))
  2362. {
  2363. return Idents->Strings[Index];
  2364. }
  2365. }
  2366. return Ident;
  2367. }