Common.cpp 57 KB

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