Common.cpp 74 KB

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