Common.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125
  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. // Particularly needed when using file name selected by TFilenameEdit,
  366. // as it wraps a path to double-quotes, when there is a space in the path.
  367. UnicodeString __fastcall StripPathQuotes(const UnicodeString Path)
  368. {
  369. if ((Path.Length() >= 2) &&
  370. (Path[1] == L'\"') && (Path[Path.Length()] == L'\"'))
  371. {
  372. return Path.SubString(2, Path.Length() - 2);
  373. }
  374. else
  375. {
  376. return Path;
  377. }
  378. }
  379. //---------------------------------------------------------------------------
  380. UnicodeString __fastcall AddPathQuotes(UnicodeString Path)
  381. {
  382. Path = StripPathQuotes(Path);
  383. if (Path.Pos(L" "))
  384. {
  385. Path = L"\"" + Path + L"\"";
  386. }
  387. return Path;
  388. }
  389. //---------------------------------------------------------------------------
  390. static wchar_t * __fastcall ReplaceChar(
  391. UnicodeString & FileName, wchar_t * InvalidChar, wchar_t InvalidCharsReplacement)
  392. {
  393. int Index = InvalidChar - FileName.c_str() + 1;
  394. if (InvalidCharsReplacement == TokenReplacement)
  395. {
  396. // currently we do not support unicode chars replacement
  397. if (FileName[Index] > 0xFF)
  398. {
  399. EXCEPTION;
  400. }
  401. FileName.Insert(ByteToHex(static_cast<unsigned char>(FileName[Index])), Index + 1);
  402. FileName[Index] = TokenPrefix;
  403. InvalidChar = FileName.c_str() + Index + 2;
  404. }
  405. else
  406. {
  407. FileName[Index] = InvalidCharsReplacement;
  408. InvalidChar = FileName.c_str() + Index;
  409. }
  410. return InvalidChar;
  411. }
  412. //---------------------------------------------------------------------------
  413. UnicodeString __fastcall ValidLocalFileName(UnicodeString FileName)
  414. {
  415. return ValidLocalFileName(FileName, L'_', L"", LocalInvalidChars);
  416. }
  417. //---------------------------------------------------------------------------
  418. UnicodeString __fastcall ValidLocalFileName(
  419. UnicodeString FileName, wchar_t InvalidCharsReplacement,
  420. const UnicodeString & TokenizibleChars, const UnicodeString & LocalInvalidChars)
  421. {
  422. if (InvalidCharsReplacement != NoReplacement)
  423. {
  424. bool ATokenReplacement = (InvalidCharsReplacement == TokenReplacement);
  425. const wchar_t * Chars =
  426. (ATokenReplacement ? TokenizibleChars : LocalInvalidChars).c_str();
  427. wchar_t * InvalidChar = FileName.c_str();
  428. while ((InvalidChar = wcspbrk(InvalidChar, Chars)) != NULL)
  429. {
  430. int Pos = (InvalidChar - FileName.c_str() + 1);
  431. wchar_t Char;
  432. if (ATokenReplacement &&
  433. (*InvalidChar == TokenPrefix) &&
  434. (((FileName.Length() - Pos) <= 1) ||
  435. (((Char = static_cast<wchar_t>(HexToByte(FileName.SubString(Pos + 1, 2)))) == L'\0') ||
  436. (TokenizibleChars.Pos(Char) == 0))))
  437. {
  438. InvalidChar++;
  439. }
  440. else
  441. {
  442. InvalidChar = ReplaceChar(FileName, InvalidChar, InvalidCharsReplacement);
  443. }
  444. }
  445. // Windows trim trailing space or dot, hence we must encode it to preserve it
  446. if (!FileName.IsEmpty() &&
  447. ((FileName[FileName.Length()] == L' ') ||
  448. (FileName[FileName.Length()] == L'.')))
  449. {
  450. ReplaceChar(FileName, FileName.c_str() + FileName.Length() - 1, InvalidCharsReplacement);
  451. }
  452. if (IsReservedName(FileName))
  453. {
  454. int P = FileName.Pos(".");
  455. if (P == 0)
  456. {
  457. P = FileName.Length() + 1;
  458. }
  459. FileName.Insert(L"%00", P);
  460. }
  461. }
  462. return FileName;
  463. }
  464. //---------------------------------------------------------------------------
  465. void __fastcall SplitCommand(UnicodeString Command, UnicodeString &Program,
  466. UnicodeString & Params, UnicodeString & Dir)
  467. {
  468. Command = Command.Trim();
  469. Params = L"";
  470. Dir = L"";
  471. if (!Command.IsEmpty() && (Command[1] == L'\"'))
  472. {
  473. Command.Delete(1, 1);
  474. int P = Command.Pos(L'"');
  475. if (P)
  476. {
  477. Program = Command.SubString(1, P-1).Trim();
  478. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  479. }
  480. else
  481. {
  482. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, (L"\"" + Command)));
  483. }
  484. }
  485. else
  486. {
  487. int P = Command.Pos(L" ");
  488. if (P)
  489. {
  490. Program = Command.SubString(1, P).Trim();
  491. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  492. }
  493. else
  494. {
  495. Program = Command;
  496. }
  497. }
  498. int B = Program.LastDelimiter(L"\\/");
  499. if (B)
  500. {
  501. Dir = Program.SubString(1, B).Trim();
  502. }
  503. }
  504. //---------------------------------------------------------------------------
  505. UnicodeString __fastcall ExtractProgram(UnicodeString Command)
  506. {
  507. UnicodeString Program;
  508. UnicodeString Params;
  509. UnicodeString Dir;
  510. SplitCommand(Command, Program, Params, Dir);
  511. return Program;
  512. }
  513. //---------------------------------------------------------------------------
  514. UnicodeString __fastcall ExtractProgramName(UnicodeString Command)
  515. {
  516. UnicodeString Name = ExtractFileName(ExtractProgram(Command));
  517. int Dot = Name.LastDelimiter(L".");
  518. if (Dot > 0)
  519. {
  520. Name = Name.SubString(1, Dot - 1);
  521. }
  522. return Name;
  523. }
  524. //---------------------------------------------------------------------------
  525. UnicodeString __fastcall FormatCommand(UnicodeString Program, UnicodeString Params)
  526. {
  527. Program = Program.Trim();
  528. Params = Params.Trim();
  529. if (!Params.IsEmpty()) Params = L" " + Params;
  530. if (Program.Pos(L" ")) Program = L"\"" + Program + L"\"";
  531. return Program + Params;
  532. }
  533. //---------------------------------------------------------------------------
  534. const wchar_t ShellCommandFileNamePattern[] = L"!.!";
  535. //---------------------------------------------------------------------------
  536. void __fastcall ReformatFileNameCommand(UnicodeString & Command)
  537. {
  538. if (!Command.IsEmpty())
  539. {
  540. UnicodeString Program, Params, Dir;
  541. SplitCommand(Command, Program, Params, Dir);
  542. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  543. {
  544. Params = Params + (Params.IsEmpty() ? L"" : L" ") + ShellCommandFileNamePattern;
  545. }
  546. Command = FormatCommand(Program, Params);
  547. }
  548. }
  549. //---------------------------------------------------------------------------
  550. UnicodeString __fastcall ExpandFileNameCommand(const UnicodeString Command,
  551. const UnicodeString FileName)
  552. {
  553. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  554. AddPathQuotes(FileName));
  555. }
  556. //---------------------------------------------------------------------------
  557. UnicodeString __fastcall EscapePuttyCommandParam(UnicodeString Param)
  558. {
  559. bool Space = false;
  560. for (int i = 1; i <= Param.Length(); i++)
  561. {
  562. switch (Param[i])
  563. {
  564. case L'"':
  565. Param.Insert(L"\\", i);
  566. i++;
  567. break;
  568. case L' ':
  569. Space = true;
  570. break;
  571. case L'\\':
  572. int i2 = i;
  573. while ((i2 <= Param.Length()) && (Param[i2] == L'\\'))
  574. {
  575. i2++;
  576. }
  577. if ((i2 <= Param.Length()) && (Param[i2] == L'"'))
  578. {
  579. while (Param[i] == L'\\')
  580. {
  581. Param.Insert(L"\\", i);
  582. i += 2;
  583. }
  584. i--;
  585. }
  586. break;
  587. }
  588. }
  589. if (Space)
  590. {
  591. Param = L"\"" + Param + L'"';
  592. }
  593. return Param;
  594. }
  595. //---------------------------------------------------------------------------
  596. UnicodeString __fastcall ExpandEnvironmentVariables(const UnicodeString & Str)
  597. {
  598. UnicodeString Buf;
  599. unsigned int Size = 1024;
  600. Buf.SetLength(Size);
  601. Buf.Unique();
  602. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  603. if (Len > Size)
  604. {
  605. Buf.SetLength(Len);
  606. Buf.Unique();
  607. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  608. }
  609. PackStr(Buf);
  610. return Buf;
  611. }
  612. //---------------------------------------------------------------------------
  613. bool __fastcall CompareFileName(const UnicodeString & Path1, const UnicodeString & Path2)
  614. {
  615. UnicodeString ShortPath1 = ExtractShortPathName(Path1);
  616. UnicodeString ShortPath2 = ExtractShortPathName(Path2);
  617. bool Result;
  618. // ExtractShortPathName returns empty string if file does not exist
  619. if (ShortPath1.IsEmpty() || ShortPath2.IsEmpty())
  620. {
  621. Result = AnsiSameText(Path1, Path2);
  622. }
  623. else
  624. {
  625. Result = AnsiSameText(ShortPath1, ShortPath2);
  626. }
  627. return Result;
  628. }
  629. //---------------------------------------------------------------------------
  630. bool __fastcall ComparePaths(const UnicodeString & Path1, const UnicodeString & Path2)
  631. {
  632. // TODO: ExpandUNCFileName
  633. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  634. }
  635. //---------------------------------------------------------------------------
  636. bool __fastcall IsReservedName(UnicodeString FileName)
  637. {
  638. int P = FileName.Pos(L".");
  639. int Len = (P > 0) ? P - 1 : FileName.Length();
  640. if ((Len == 3) || (Len == 4))
  641. {
  642. if (P > 0)
  643. {
  644. FileName.SetLength(P - 1);
  645. }
  646. static UnicodeString Reserved[] = {
  647. L"CON", L"PRN", L"AUX", L"NUL",
  648. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  649. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  650. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  651. {
  652. if (SameText(FileName, Reserved[Index]))
  653. {
  654. return true;
  655. }
  656. }
  657. }
  658. return false;
  659. }
  660. //---------------------------------------------------------------------------
  661. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  662. {
  663. bool Displayable = true;
  664. int Index = 1;
  665. while ((Index <= Str.Length()) && Displayable)
  666. {
  667. if (((Str[Index] < '\x20') || (static_cast<unsigned char>(Str[Index]) >= static_cast<unsigned char>('\x80'))) &&
  668. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  669. {
  670. Displayable = false;
  671. }
  672. Index++;
  673. }
  674. UnicodeString Result;
  675. if (Displayable)
  676. {
  677. Result = L"\"";
  678. for (int Index = 1; Index <= Str.Length(); Index++)
  679. {
  680. switch (Str[Index])
  681. {
  682. case '\n':
  683. Result += L"\\n";
  684. break;
  685. case '\r':
  686. Result += L"\\r";
  687. break;
  688. case '\t':
  689. Result += L"\\t";
  690. break;
  691. case '\b':
  692. Result += L"\\b";
  693. break;
  694. case '\\':
  695. Result += L"\\\\";
  696. break;
  697. case '"':
  698. Result += L"\\\"";
  699. break;
  700. default:
  701. Result += wchar_t(Str[Index]);
  702. break;
  703. }
  704. }
  705. Result += L"\"";
  706. }
  707. else
  708. {
  709. Result = L"0x" + BytesToHex(Str);
  710. }
  711. return Result;
  712. }
  713. //---------------------------------------------------------------------------
  714. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  715. {
  716. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  717. static wchar_t LowerDigits[] = L"0123456789abcdef";
  718. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  719. UnicodeString Result;
  720. Result.SetLength(2);
  721. Result[1] = Digits[(B & 0xF0) >> 4];
  722. Result[2] = Digits[(B & 0x0F) >> 0];
  723. return Result;
  724. }
  725. //---------------------------------------------------------------------------
  726. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  727. {
  728. UnicodeString Result;
  729. for (size_t i = 0; i < Length; i++)
  730. {
  731. Result += ByteToHex(B[i], UpperCase);
  732. if ((Separator != L'\0') && (i < Length - 1))
  733. {
  734. Result += Separator;
  735. }
  736. }
  737. return Result;
  738. }
  739. //---------------------------------------------------------------------------
  740. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  741. {
  742. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  743. }
  744. //---------------------------------------------------------------------------
  745. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  746. {
  747. return BytesToHex(reinterpret_cast<const unsigned char *>(&Ch), sizeof(Ch), UpperCase);
  748. }
  749. //---------------------------------------------------------------------------
  750. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  751. {
  752. static UnicodeString Digits = L"0123456789ABCDEF";
  753. RawByteString Result;
  754. int L, P1, P2;
  755. L = Hex.Length();
  756. if (L % 2 == 0)
  757. {
  758. for (int i = 1; i <= Hex.Length(); i += 2)
  759. {
  760. P1 = Digits.Pos((wchar_t)toupper(Hex[i]));
  761. P2 = Digits.Pos((wchar_t)toupper(Hex[i + 1]));
  762. if (P1 <= 0 || P2 <= 0)
  763. {
  764. Result = L"";
  765. break;
  766. }
  767. else
  768. {
  769. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  770. }
  771. }
  772. }
  773. return Result;
  774. }
  775. //---------------------------------------------------------------------------
  776. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  777. {
  778. static UnicodeString Digits = L"0123456789ABCDEF";
  779. assert(Hex.Length() == 2);
  780. int P1 = Digits.Pos((wchar_t)toupper(Hex[1]));
  781. int P2 = Digits.Pos((wchar_t)toupper(Hex[2]));
  782. return
  783. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  784. }
  785. //---------------------------------------------------------------------------
  786. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  787. {
  788. return (Ch >= 'a') && (Ch <= 'z');
  789. }
  790. //---------------------------------------------------------------------------
  791. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  792. {
  793. return (Ch >= 'A') && (Ch <= 'Z');
  794. }
  795. //---------------------------------------------------------------------------
  796. bool __fastcall IsLetter(wchar_t Ch)
  797. {
  798. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  799. }
  800. //---------------------------------------------------------------------------
  801. bool __fastcall IsDigit(wchar_t Ch)
  802. {
  803. return (Ch >= '0') && (Ch <= '9');
  804. }
  805. //---------------------------------------------------------------------------
  806. bool __fastcall IsHex(wchar_t Ch)
  807. {
  808. return
  809. IsDigit(Ch) ||
  810. ((Ch >= 'A') && (Ch <= 'F')) ||
  811. ((Ch >= 'a') && (Ch <= 'f'));
  812. }
  813. //---------------------------------------------------------------------------
  814. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  815. {
  816. if ((Result != ERROR_SUCCESS) &&
  817. (Result != ERROR_FILE_NOT_FOUND) &&
  818. (Result != ERROR_NO_MORE_FILES))
  819. {
  820. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  821. }
  822. return Result;
  823. }
  824. //---------------------------------------------------------------------------
  825. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  826. {
  827. F.Path = Path;
  828. return FindFirst(Path, Attr, F);
  829. }
  830. //---------------------------------------------------------------------------
  831. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  832. {
  833. int Result = FindFirstUnchecked(Path, Attr, F);
  834. return FindCheck(Result, F.Path);
  835. }
  836. //---------------------------------------------------------------------------
  837. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  838. // I.e. even if we do not care that FindFirst failed, if FindNext
  839. // failes after successfull FindFirst, it mean some terrible problem
  840. int __fastcall FindNextChecked(TSearchRecChecked & F)
  841. {
  842. return FindCheck(FindNext(F), F.Path);
  843. }
  844. //---------------------------------------------------------------------------
  845. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  846. {
  847. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  848. bool Result = (FindFirst(FileName, FindAttrs, Rec) == 0);
  849. if (Result)
  850. {
  851. FindClose(Rec);
  852. }
  853. return Result;
  854. }
  855. //---------------------------------------------------------------------------
  856. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  857. TProcessLocalFileEvent CallBackFunc, void * Param,
  858. int FindAttrs)
  859. {
  860. assert(CallBackFunc);
  861. if (FindAttrs < 0)
  862. {
  863. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  864. }
  865. TSearchRecChecked SearchRec;
  866. DirName = IncludeTrailingBackslash(DirName);
  867. if (FindFirstChecked(DirName + L"*.*", FindAttrs, SearchRec) == 0)
  868. {
  869. try
  870. {
  871. do
  872. {
  873. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  874. {
  875. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  876. }
  877. } while (FindNextChecked(SearchRec) == 0);
  878. }
  879. __finally
  880. {
  881. FindClose(SearchRec);
  882. }
  883. }
  884. }
  885. //---------------------------------------------------------------------------
  886. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  887. {
  888. try
  889. {
  890. TDateTime DateTime = EncodeDate(Year, Month, Day);
  891. return DateTime;
  892. }
  893. catch (EConvertError & E)
  894. {
  895. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  896. }
  897. }
  898. //---------------------------------------------------------------------------
  899. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  900. {
  901. try
  902. {
  903. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  904. return DateTime;
  905. }
  906. catch (EConvertError & E)
  907. {
  908. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  909. }
  910. }
  911. //---------------------------------------------------------------------------
  912. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  913. {
  914. try
  915. {
  916. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  917. return DateTime;
  918. }
  919. catch (EConvertError & E)
  920. {
  921. 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))));
  922. }
  923. }
  924. //---------------------------------------------------------------------------
  925. struct TDateTimeParams
  926. {
  927. TDateTime UnixEpoch;
  928. double BaseDifference;
  929. long BaseDifferenceSec;
  930. // All Current* are actually global, not per-year
  931. double CurrentDaylightDifference;
  932. long CurrentDaylightDifferenceSec;
  933. double CurrentDifference;
  934. long CurrentDifferenceSec;
  935. double StandardDifference;
  936. long StandardDifferenceSec;
  937. double DaylightDifference;
  938. long DaylightDifferenceSec;
  939. SYSTEMTIME SystemStandardDate;
  940. SYSTEMTIME SystemDaylightDate;
  941. TDateTime StandardDate;
  942. TDateTime DaylightDate;
  943. UnicodeString StandardName;
  944. UnicodeString DaylightName;
  945. // This is actually global, not per-year
  946. bool DaylightHack;
  947. bool HasDST() const
  948. {
  949. // On some systems it occurs that StandardDate is unset, while
  950. // DaylightDate is set. MSDN states that this is invalid and
  951. // should be treated as if there is no daylight saving.
  952. // So check both.
  953. return
  954. (SystemStandardDate.wMonth != 0) &&
  955. (SystemDaylightDate.wMonth != 0);
  956. }
  957. bool SummerDST() const
  958. {
  959. return HasDST() && (DaylightDate < StandardDate);
  960. }
  961. };
  962. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  963. static TYearlyDateTimeParams YearlyDateTimeParams;
  964. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(new TCriticalSection());
  965. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  966. TDateTime & Result);
  967. //---------------------------------------------------------------------------
  968. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  969. {
  970. unsigned short Year, Month, Day;
  971. DecodeDate(DateTime, Year, Month, Day);
  972. return Year;
  973. }
  974. //---------------------------------------------------------------------------
  975. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  976. {
  977. TGuard Guard(DateTimeParamsSection.get());
  978. TDateTimeParams * Result;
  979. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  980. if (i != YearlyDateTimeParams.end())
  981. {
  982. Result = &(*i).second;
  983. }
  984. else
  985. {
  986. // creates new entry as a side effect
  987. Result = &YearlyDateTimeParams[Year];
  988. TIME_ZONE_INFORMATION TZI;
  989. unsigned long GTZI;
  990. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  991. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  992. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  993. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  994. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  995. {
  996. GTZI = GetTimeZoneInformation(&TZI);
  997. }
  998. else
  999. {
  1000. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1001. GTZI = TIME_ZONE_ID_UNKNOWN;
  1002. }
  1003. switch (GTZI)
  1004. {
  1005. case TIME_ZONE_ID_UNKNOWN:
  1006. Result->CurrentDaylightDifferenceSec = 0;
  1007. break;
  1008. case TIME_ZONE_ID_STANDARD:
  1009. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1010. break;
  1011. case TIME_ZONE_ID_DAYLIGHT:
  1012. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1013. break;
  1014. case TIME_ZONE_ID_INVALID:
  1015. default:
  1016. throw Exception(TIMEZONE_ERROR);
  1017. }
  1018. Result->BaseDifferenceSec = TZI.Bias;
  1019. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1020. Result->BaseDifferenceSec *= SecsPerMin;
  1021. Result->CurrentDifferenceSec = TZI.Bias +
  1022. Result->CurrentDaylightDifferenceSec;
  1023. Result->CurrentDifference =
  1024. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1025. Result->CurrentDifferenceSec *= SecsPerMin;
  1026. Result->CurrentDaylightDifference =
  1027. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1028. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1029. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1030. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1031. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1032. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1033. Result->SystemStandardDate = TZI.StandardDate;
  1034. Result->SystemDaylightDate = TZI.DaylightDate;
  1035. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1036. if (Result->HasDST())
  1037. {
  1038. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1039. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1040. }
  1041. Result->StandardName = TZI.StandardName;
  1042. Result->DaylightName = TZI.DaylightName;
  1043. Result->DaylightHack = !IsWin7();
  1044. }
  1045. return Result;
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1049. TDateTime & Result)
  1050. {
  1051. if (Date.wYear == 0)
  1052. {
  1053. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1054. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1055. (7 * (Date.wDay - 1));
  1056. if (Date.wDay == 5)
  1057. {
  1058. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1059. if (Month > 12)
  1060. {
  1061. Month = static_cast<unsigned short>(Month - 12);
  1062. Year++;
  1063. }
  1064. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1065. {
  1066. Result -= 7;
  1067. }
  1068. }
  1069. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1070. Date.wMilliseconds);
  1071. }
  1072. else
  1073. {
  1074. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1075. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1076. }
  1077. }
  1078. //---------------------------------------------------------------------------
  1079. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1080. {
  1081. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1082. bool Result;
  1083. // On some systems it occurs that StandardDate is unset, while
  1084. // DaylightDate is set. MSDN states that this is invalid and
  1085. // should be treated as if there is no daylight saving.
  1086. // So check both.
  1087. if (!Params->HasDST())
  1088. {
  1089. Result = false;
  1090. }
  1091. else
  1092. {
  1093. if (Params->SummerDST())
  1094. {
  1095. Result =
  1096. (DateTime >= Params->DaylightDate) &&
  1097. (DateTime < Params->StandardDate);
  1098. }
  1099. else
  1100. {
  1101. Result =
  1102. (DateTime < Params->StandardDate) ||
  1103. (DateTime >= Params->DaylightDate);
  1104. }
  1105. }
  1106. return Result;
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. bool __fastcall UsesDaylightHack()
  1110. {
  1111. return GetDateTimeParams(0)->DaylightHack;
  1112. }
  1113. //---------------------------------------------------------------------------
  1114. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1115. {
  1116. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1117. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1118. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1119. if (Params->DaylightHack)
  1120. {
  1121. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1122. {
  1123. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1124. Result -= CurrentParams->CurrentDifference;
  1125. }
  1126. else if (DSTMode == dstmKeep)
  1127. {
  1128. Result -= Params->BaseDifference;
  1129. }
  1130. }
  1131. else
  1132. {
  1133. Result -= Params->BaseDifference;
  1134. }
  1135. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1136. {
  1137. Result -= (IsDateInDST(Result) ?
  1138. Params->DaylightDifference : Params->StandardDifference);
  1139. }
  1140. return Result;
  1141. }
  1142. //---------------------------------------------------------------------------
  1143. __int64 __fastcall Round(double Number)
  1144. {
  1145. double Floor = floor(Number);
  1146. double Ceil = ceil(Number);
  1147. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime)
  1151. {
  1152. S = S.Trim();
  1153. int Index = 1;
  1154. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1155. {
  1156. Index++;
  1157. }
  1158. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1159. int Number;
  1160. bool Result = TryStrToInt(NumberStr, Number);
  1161. if (Result)
  1162. {
  1163. S.Delete(1, Index - 1);
  1164. S = S.Trim().UpperCase();
  1165. DateTime = Now();
  1166. // These may not overlap with ParseSize (K, M and G)
  1167. if (S == "S")
  1168. {
  1169. DateTime = IncSecond(DateTime, -Number);
  1170. }
  1171. else if (S == "N")
  1172. {
  1173. DateTime = IncMinute(DateTime, -Number);
  1174. }
  1175. else if (S == "H")
  1176. {
  1177. DateTime = IncHour(DateTime, -Number);
  1178. }
  1179. else if (S == "D")
  1180. {
  1181. DateTime = IncDay(DateTime, -Number);
  1182. }
  1183. else if (S == "Y")
  1184. {
  1185. DateTime = IncYear(DateTime, -Number);
  1186. }
  1187. else
  1188. {
  1189. Result = false;
  1190. }
  1191. }
  1192. return Result;
  1193. }
  1194. //---------------------------------------------------------------------------
  1195. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1196. {
  1197. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1198. assert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1199. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1200. CurrentParams->CurrentDifferenceSec;
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1204. TDSTMode /*DSTMode*/)
  1205. {
  1206. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1207. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1208. if (!Params->DaylightHack)
  1209. {
  1210. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  1211. // We are incrementing and decrementing BaseDifferenceSec because it
  1212. // can actually change between years
  1213. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  1214. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1215. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  1216. Params->BaseDifferenceSec;
  1217. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1218. UnixTimeStamp -=
  1219. CurrentParams->CurrentDaylightDifferenceSec +
  1220. CurrentParams->BaseDifferenceSec;
  1221. }
  1222. FILETIME Result;
  1223. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1224. return Result;
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1228. {
  1229. // duplicated in DirView.pas
  1230. TDateTime Result;
  1231. // The 0xFFF... is sometime seen for invalid timestamps,
  1232. // it would cause failure in SystemTimeToDateTime below
  1233. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  1234. {
  1235. Result = MinDateTime;
  1236. }
  1237. else
  1238. {
  1239. SYSTEMTIME SysTime;
  1240. if (!UsesDaylightHack())
  1241. {
  1242. SYSTEMTIME UniverzalSysTime;
  1243. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1244. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1245. }
  1246. else
  1247. {
  1248. FILETIME LocalFileTime;
  1249. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1250. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1251. }
  1252. Result = SystemTimeToDateTimeVerbose(SysTime);
  1253. }
  1254. return Result;
  1255. }
  1256. //---------------------------------------------------------------------------
  1257. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1258. TDSTMode DSTMode)
  1259. {
  1260. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1261. if (UsesDaylightHack())
  1262. {
  1263. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1264. {
  1265. FILETIME LocalFileTime;
  1266. SYSTEMTIME SystemTime;
  1267. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1268. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1269. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1270. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1271. Result += (IsDateInDST(DateTime) ?
  1272. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1273. if (DSTMode == dstmKeep)
  1274. {
  1275. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1276. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1277. }
  1278. }
  1279. }
  1280. else
  1281. {
  1282. if (DSTMode == dstmWin)
  1283. {
  1284. FILETIME LocalFileTime;
  1285. SYSTEMTIME SystemTime;
  1286. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1287. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1288. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1289. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1290. Result -= (IsDateInDST(DateTime) ?
  1291. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1292. }
  1293. }
  1294. return Result;
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1298. {
  1299. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1300. DateTime +=
  1301. (IsDateInDST(DateTime) ?
  1302. Params->DaylightDifference : Params->StandardDifference);
  1303. DateTime += Params->BaseDifference;
  1304. if (Params->DaylightHack)
  1305. {
  1306. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1307. DateTime += CurrentParams->CurrentDaylightDifference;
  1308. }
  1309. return DateTime;
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1313. {
  1314. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1315. DateTime -=
  1316. (IsDateInDST(DateTime) ?
  1317. Params->DaylightDifference : Params->StandardDifference);
  1318. DateTime -= Params->BaseDifference;
  1319. if (Params->DaylightHack)
  1320. {
  1321. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1322. DateTime -= CurrentParams->CurrentDaylightDifference;
  1323. }
  1324. return DateTime;
  1325. }
  1326. //---------------------------------------------------------------------------
  1327. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1328. TDSTMode DSTMode)
  1329. {
  1330. __int64 Result;
  1331. if ((FileTime.dwLowDateTime == 0) &&
  1332. (FileTime.dwHighDateTime == 0))
  1333. {
  1334. Result = ::DateTimeToUnix(Now());
  1335. }
  1336. else
  1337. {
  1338. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1339. }
  1340. return Result;
  1341. }
  1342. //---------------------------------------------------------------------------
  1343. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1344. {
  1345. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1346. if (Params->DaylightHack)
  1347. {
  1348. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1349. {
  1350. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1351. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  1352. }
  1353. if (!IsDateInDST(DateTime))
  1354. {
  1355. if (DSTMode == dstmWin)
  1356. {
  1357. DateTime = DateTime - Params->DaylightDifference;
  1358. }
  1359. }
  1360. else
  1361. {
  1362. DateTime = DateTime - Params->StandardDifference;
  1363. }
  1364. }
  1365. else
  1366. {
  1367. if (DSTMode == dstmWin)
  1368. {
  1369. if (IsDateInDST(DateTime))
  1370. {
  1371. DateTime = DateTime + Params->DaylightDifference;
  1372. }
  1373. else
  1374. {
  1375. DateTime = DateTime + Params->StandardDifference;
  1376. }
  1377. }
  1378. }
  1379. return DateTime;
  1380. }
  1381. //---------------------------------------------------------------------------
  1382. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  1383. {
  1384. UnicodeString Result = Format;
  1385. bool AsIs = false;
  1386. int Index = 1;
  1387. while (Index <= Result.Length())
  1388. {
  1389. wchar_t F = Result[Index];
  1390. if ((F == L'\'') || (F == L'\"'))
  1391. {
  1392. AsIs = !AsIs;
  1393. Index++;
  1394. }
  1395. else if (!AsIs && ((F == L'a') || (F == L'A')))
  1396. {
  1397. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  1398. {
  1399. Index += 5;
  1400. }
  1401. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  1402. {
  1403. Index += 3;
  1404. }
  1405. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  1406. {
  1407. Index += 4;
  1408. }
  1409. else
  1410. {
  1411. Index++;
  1412. }
  1413. }
  1414. else
  1415. {
  1416. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  1417. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1418. {
  1419. Result.Insert(F, Index);
  1420. }
  1421. while ((Index <= Result.Length()) && (F == Result[Index]))
  1422. {
  1423. Index++;
  1424. }
  1425. }
  1426. }
  1427. return Result;
  1428. }
  1429. //---------------------------------------------------------------------------
  1430. static UnicodeString __fastcall FormatTimeZone(long Sec)
  1431. {
  1432. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  1433. UnicodeString Str;
  1434. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  1435. {
  1436. Str = FORMAT(L"%d", (-Span.Hours));
  1437. }
  1438. else if (Span.Seconds == 0)
  1439. {
  1440. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  1441. }
  1442. else
  1443. {
  1444. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  1445. }
  1446. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  1447. return Str;
  1448. }
  1449. //---------------------------------------------------------------------------
  1450. UnicodeString __fastcall GetTimeZoneLogString()
  1451. {
  1452. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1453. UnicodeString Result =
  1454. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  1455. if (!CurrentParams->HasDST())
  1456. {
  1457. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  1458. }
  1459. else
  1460. {
  1461. Result +=
  1462. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  1463. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  1464. CurrentParams->StandardName,
  1465. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  1466. CurrentParams->DaylightName,
  1467. CurrentParams->DaylightDate.DateString(),
  1468. CurrentParams->StandardDate.DateString()));
  1469. }
  1470. return Result;
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. bool __fastcall AdjustClockForDSTEnabled()
  1474. {
  1475. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  1476. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  1477. bool DynamicDaylightTimeDisabled = false;
  1478. TRegistry * Registry = new TRegistry(KEY_READ);
  1479. try
  1480. {
  1481. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1482. if (Registry->OpenKey(L"SYSTEM", false) &&
  1483. Registry->OpenKey(L"CurrentControlSet", false) &&
  1484. Registry->OpenKey(L"Control", false) &&
  1485. Registry->OpenKey(L"TimeZoneInformation", false))
  1486. {
  1487. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  1488. {
  1489. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  1490. }
  1491. // WORKAROUND
  1492. // Windows XP equivalent
  1493. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  1494. {
  1495. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  1496. }
  1497. }
  1498. delete Registry;
  1499. }
  1500. catch(...)
  1501. {
  1502. }
  1503. return !DynamicDaylightTimeDisabled;
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. UnicodeString __fastcall StandardDatestamp()
  1507. {
  1508. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  1509. }
  1510. //---------------------------------------------------------------------------
  1511. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  1512. {
  1513. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  1514. }
  1515. //---------------------------------------------------------------------------
  1516. UnicodeString __fastcall StandardTimestamp()
  1517. {
  1518. return StandardTimestamp(Now());
  1519. }
  1520. //---------------------------------------------------------------------------
  1521. static TDateTime TwoSeconds(0, 0, 2, 0);
  1522. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1523. {
  1524. // "FAT" time precision
  1525. // (when one time is seconds-precision and other is millisecond-precision,
  1526. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1527. // be treated the same)
  1528. int Result;
  1529. if (T1 == T2)
  1530. {
  1531. // just optimization
  1532. Result = 0;
  1533. }
  1534. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1535. {
  1536. Result = -1;
  1537. }
  1538. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1539. {
  1540. Result = 1;
  1541. }
  1542. else
  1543. {
  1544. Result = 0;
  1545. }
  1546. return Result;
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. int __fastcall TimeToMSec(TDateTime T)
  1550. {
  1551. return int(Round(double(T) * double(MSecsPerDay)));
  1552. }
  1553. //---------------------------------------------------------------------------
  1554. int __fastcall TimeToSeconds(TDateTime T)
  1555. {
  1556. return TimeToMSec(T) / MSecsPerSec;
  1557. }
  1558. //---------------------------------------------------------------------------
  1559. int __fastcall TimeToMinutes(TDateTime T)
  1560. {
  1561. return TimeToSeconds(T) / SecsPerMin;
  1562. }
  1563. //---------------------------------------------------------------------------
  1564. bool __fastcall RecursiveDeleteFile(const UnicodeString FileName, bool ToRecycleBin)
  1565. {
  1566. SHFILEOPSTRUCT Data;
  1567. memset(&Data, 0, sizeof(Data));
  1568. Data.hwnd = NULL;
  1569. Data.wFunc = FO_DELETE;
  1570. UnicodeString FileList(FileName);
  1571. FileList.SetLength(FileList.Length() + 2);
  1572. FileList[FileList.Length() - 1] = L'\0';
  1573. FileList[FileList.Length()] = L'\0';
  1574. Data.pFrom = FileList.c_str();
  1575. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  1576. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1577. FOF_NOERRORUI | FOF_SILENT;
  1578. if (ToRecycleBin)
  1579. {
  1580. Data.fFlags |= FOF_ALLOWUNDO;
  1581. }
  1582. int ErrorCode = SHFileOperation(&Data);
  1583. bool Result = (ErrorCode == 0);
  1584. if (!Result)
  1585. {
  1586. // according to MSDN, SHFileOperation may return following non-Win32
  1587. // error codes
  1588. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  1589. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  1590. (ErrorCode == 0x10074))
  1591. {
  1592. ErrorCode = 0;
  1593. }
  1594. SetLastError(ErrorCode);
  1595. }
  1596. return Result;
  1597. }
  1598. //---------------------------------------------------------------------------
  1599. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  1600. {
  1601. if (!DeleteFile(FileName))
  1602. {
  1603. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  1604. }
  1605. }
  1606. //---------------------------------------------------------------------------
  1607. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  1608. {
  1609. unsigned int Result;
  1610. if ((Answers & qaCancel) != 0)
  1611. {
  1612. Result = qaCancel;
  1613. }
  1614. else if ((Answers & qaNo) != 0)
  1615. {
  1616. Result = qaNo;
  1617. }
  1618. else if ((Answers & qaAbort) != 0)
  1619. {
  1620. Result = qaAbort;
  1621. }
  1622. else if ((Answers & qaOK) != 0)
  1623. {
  1624. Result = qaOK;
  1625. }
  1626. else
  1627. {
  1628. assert(false);
  1629. Result = qaCancel;
  1630. }
  1631. return Result;
  1632. }
  1633. //---------------------------------------------------------------------------
  1634. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  1635. {
  1636. unsigned int Result;
  1637. if (FLAGSET(Answers, qaAbort))
  1638. {
  1639. Result = qaAbort;
  1640. }
  1641. else
  1642. {
  1643. Result = CancelAnswer(Answers);
  1644. }
  1645. return Result;
  1646. }
  1647. //---------------------------------------------------------------------------
  1648. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  1649. {
  1650. unsigned int Result;
  1651. if (FLAGSET(Answers, qaSkip))
  1652. {
  1653. Result = qaSkip;
  1654. }
  1655. else if (FLAGSET(Answers, qaIgnore))
  1656. {
  1657. Result = qaIgnore;
  1658. }
  1659. else if (FLAGSET(Answers, qaYes))
  1660. {
  1661. Result = qaYes;
  1662. }
  1663. else if (FLAGSET(Answers, qaOK))
  1664. {
  1665. Result = qaOK;
  1666. }
  1667. else if (FLAGSET(Answers, qaRetry))
  1668. {
  1669. Result = qaRetry;
  1670. }
  1671. else
  1672. {
  1673. Result = CancelAnswer(Answers);
  1674. }
  1675. return Result;
  1676. }
  1677. //---------------------------------------------------------------------------
  1678. TLibModule * __fastcall FindModule(void * Instance)
  1679. {
  1680. TLibModule * CurModule;
  1681. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  1682. while (CurModule)
  1683. {
  1684. if (CurModule->Instance == (unsigned)Instance)
  1685. {
  1686. break;
  1687. }
  1688. else
  1689. {
  1690. CurModule = CurModule->Next;
  1691. }
  1692. }
  1693. return CurModule;
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  1697. {
  1698. TLibModule * MainModule = FindModule(HInstance);
  1699. assert(MainModule != NULL);
  1700. UnicodeString Result;
  1701. Result.SetLength(MaxLength);
  1702. int Length = LoadString((HINSTANCE)MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  1703. Result.SetLength(Length);
  1704. return Result;
  1705. }
  1706. //---------------------------------------------------------------------------
  1707. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  1708. {
  1709. UnicodeString Result;
  1710. UnicodeString Str = LoadStr(Ident);
  1711. while (Part > 0)
  1712. {
  1713. Result = CutToChar(Str, L'|', false);
  1714. Part--;
  1715. }
  1716. return Result;
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  1720. {
  1721. int i = 1;
  1722. while (i <= S.Length())
  1723. {
  1724. switch (S[i])
  1725. {
  1726. case L'+':
  1727. S[i] = ' ';
  1728. break;
  1729. case L'%':
  1730. {
  1731. UnicodeString Hex;
  1732. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  1733. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  1734. {
  1735. Hex += S.SubString(i + 1, 2);
  1736. S.Delete(i, 3);
  1737. }
  1738. if (!Hex.IsEmpty())
  1739. {
  1740. RawByteString Bytes = HexToBytes(Hex);
  1741. UTF8String UTF8(Bytes.c_str(), Bytes.Length());
  1742. UnicodeString Chars(UTF8);
  1743. S.Insert(Chars, i);
  1744. i += Chars.Length() - 1;
  1745. }
  1746. }
  1747. break;
  1748. }
  1749. i++;
  1750. }
  1751. return S;
  1752. }
  1753. //---------------------------------------------------------------------------
  1754. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, UnicodeString Chars)
  1755. {
  1756. int i = 1;
  1757. while (i <= S.Length())
  1758. {
  1759. if (Chars.Pos(S[i]) > 0)
  1760. {
  1761. UnicodeString H = ByteToHex(AnsiString(UnicodeString(S[i]))[1]);
  1762. S.Insert(H, i + 1);
  1763. S[i] = '%';
  1764. i += H.Length();
  1765. }
  1766. i++;
  1767. }
  1768. return S;
  1769. }
  1770. //---------------------------------------------------------------------------
  1771. UnicodeString __fastcall EncodeUrlChars(UnicodeString S, UnicodeString Ignore)
  1772. {
  1773. UnicodeString Chars;
  1774. if (Ignore.Pos(L' ') == 0)
  1775. {
  1776. Chars += L' ';
  1777. }
  1778. if (Ignore.Pos(L'/') == 0)
  1779. {
  1780. Chars += L'/';
  1781. }
  1782. return DoEncodeUrl(S, Chars);
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. UnicodeString __fastcall NonUrlChars()
  1786. {
  1787. UnicodeString S;
  1788. for (unsigned int I = 0; I <= 127; I++)
  1789. {
  1790. wchar_t C = static_cast<wchar_t>(I);
  1791. if (IsLetter(C) ||
  1792. IsDigit(C) ||
  1793. (C == L'_') || (C == L'-') || (C == L'.'))
  1794. {
  1795. // noop
  1796. }
  1797. else
  1798. {
  1799. S += C;
  1800. }
  1801. }
  1802. return S;
  1803. }
  1804. //---------------------------------------------------------------------------
  1805. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  1806. {
  1807. return DoEncodeUrl(S, NonUrlChars());
  1808. }
  1809. //---------------------------------------------------------------------------
  1810. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  1811. {
  1812. // see also TWebHelpSystem::ShowHelp
  1813. const wchar_t FragmentSeparator = L'#';
  1814. UnicodeString URL = ::CutToChar(AURL, FragmentSeparator, false);
  1815. if (URL.Pos(L"?") == 0)
  1816. {
  1817. URL += L"?";
  1818. }
  1819. else
  1820. {
  1821. URL += L"&";
  1822. }
  1823. URL += Params;
  1824. AddToList(URL, AURL, FragmentSeparator);
  1825. return URL;
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  1829. {
  1830. return ReplaceStr(Caption, L"&", L"&&");
  1831. }
  1832. //---------------------------------------------------------------------------
  1833. // duplicated in console's Main.cpp
  1834. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  1835. UnicodeString * RawToken)
  1836. {
  1837. bool Result;
  1838. Token = L"";
  1839. // inspired by Putty's sftp_getcmd() from PSFTP.C
  1840. int Index = 1;
  1841. while ((Index <= Str.Length()) &&
  1842. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  1843. {
  1844. Index++;
  1845. }
  1846. if (Index <= Str.Length())
  1847. {
  1848. bool Quoting = false;
  1849. while (Index <= Str.Length())
  1850. {
  1851. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  1852. {
  1853. break;
  1854. }
  1855. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  1856. (Str[Index + 1] == L'"'))
  1857. {
  1858. Index += 2;
  1859. Token += L'"';
  1860. }
  1861. else if (Str[Index] == L'"')
  1862. {
  1863. Index++;
  1864. Quoting = !Quoting;
  1865. }
  1866. else
  1867. {
  1868. Token += Str[Index];
  1869. Index++;
  1870. }
  1871. }
  1872. if (RawToken != NULL)
  1873. {
  1874. (*RawToken) = Str.SubString(1, Index - 1);
  1875. }
  1876. if (Index <= Str.Length())
  1877. {
  1878. Index++;
  1879. }
  1880. Str = Str.SubString(Index, Str.Length());
  1881. Result = true;
  1882. }
  1883. else
  1884. {
  1885. Result = false;
  1886. Str = L"";
  1887. }
  1888. return Result;
  1889. }
  1890. //---------------------------------------------------------------------------
  1891. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  1892. {
  1893. if (!Value.IsEmpty())
  1894. {
  1895. if (!List.IsEmpty() &&
  1896. ((List.Length() < Delimiter.Length()) ||
  1897. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  1898. {
  1899. List += Delimiter;
  1900. }
  1901. List += Value;
  1902. }
  1903. }
  1904. //---------------------------------------------------------------------------
  1905. bool __fastcall IsWinVista()
  1906. {
  1907. // Vista is 6.0
  1908. // Win XP is 5.1
  1909. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  1910. // (we consider it WinXP for now)
  1911. return CheckWin32Version(6, 0);
  1912. }
  1913. //---------------------------------------------------------------------------
  1914. bool __fastcall IsWin7()
  1915. {
  1916. return CheckWin32Version(6, 1);
  1917. }
  1918. //---------------------------------------------------------------------------
  1919. bool __fastcall IsWine()
  1920. {
  1921. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  1922. return
  1923. ALWAYS_TRUE(NtDll != NULL) &&
  1924. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  1925. }
  1926. //---------------------------------------------------------------------------
  1927. LCID __fastcall GetDefaultLCID()
  1928. {
  1929. return GetUserDefaultLCID();
  1930. }
  1931. //---------------------------------------------------------------------------
  1932. static UnicodeString ADefaultEncodingName;
  1933. UnicodeString __fastcall DefaultEncodingName()
  1934. {
  1935. if (ADefaultEncodingName.IsEmpty())
  1936. {
  1937. CPINFOEX Info;
  1938. GetCPInfoEx(CP_ACP, 0, &Info);
  1939. ADefaultEncodingName = Info.CodePageName;
  1940. }
  1941. return ADefaultEncodingName;
  1942. }
  1943. //---------------------------------------------------------------------------
  1944. bool _fastcall GetWindowsProductType(DWORD & Type)
  1945. {
  1946. bool Result;
  1947. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1948. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  1949. TGetProductInfo GetProductInfo =
  1950. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  1951. if (GetProductInfo == NULL)
  1952. {
  1953. Result = false;
  1954. }
  1955. else
  1956. {
  1957. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  1958. Result = true;
  1959. }
  1960. return Result;
  1961. }
  1962. //---------------------------------------------------------------------------
  1963. UnicodeString __fastcall WindowsProductName()
  1964. {
  1965. UnicodeString Result;
  1966. TRegistry * Registry = new TRegistry(KEY_READ);
  1967. try
  1968. {
  1969. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1970. if (Registry->OpenKey(L"SOFTWARE", false) &&
  1971. Registry->OpenKey(L"Microsoft", false) &&
  1972. Registry->OpenKey(L"Windows NT", false) &&
  1973. Registry->OpenKey(L"CurrentVersion", false))
  1974. {
  1975. Result = Registry->ReadString(L"ProductName");
  1976. }
  1977. delete Registry;
  1978. }
  1979. catch(...)
  1980. {
  1981. }
  1982. return Result;
  1983. }
  1984. //---------------------------------------------------------------------------
  1985. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  1986. {
  1987. UnicodeString FileName =
  1988. IncludeTrailingPathDelimiter(Path) +
  1989. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  1990. HANDLE Handle = CreateFile(FileName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  1991. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  1992. bool Result = (Handle != INVALID_HANDLE_VALUE);
  1993. if (Result)
  1994. {
  1995. CloseHandle(Handle);
  1996. }
  1997. return Result;
  1998. }
  1999. //---------------------------------------------------------------------------
  2000. UnicodeString __fastcall FormatNumber(__int64 Number)
  2001. {
  2002. return FormatFloat(L"#,##0", Number);
  2003. }
  2004. //---------------------------------------------------------------------------
  2005. // simple alternative to FormatBytes
  2006. UnicodeString __fastcall FormatSize(__int64 Size)
  2007. {
  2008. return FormatNumber(Size);
  2009. }
  2010. //---------------------------------------------------------------------------
  2011. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  2012. {
  2013. return ChangeFileExt(ExtractFileName(Path), L"");
  2014. }
  2015. //---------------------------------------------------------------------------
  2016. // Suppress warning about unused constants in DateUtils.hpp
  2017. #pragma warn -8080