Common.cpp 58 KB

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