Common.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  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 <math.h>
  11. #include <shfolder.h>
  12. //---------------------------------------------------------------------------
  13. #pragma package(smart_init)
  14. //---------------------------------------------------------------------------
  15. //---------------------------------------------------------------------------
  16. // TCriticalSection
  17. //---------------------------------------------------------------------------
  18. __fastcall TCriticalSection::TCriticalSection()
  19. {
  20. FAcquired = 0;
  21. InitializeCriticalSection(&FSection);
  22. }
  23. //---------------------------------------------------------------------------
  24. __fastcall TCriticalSection::~TCriticalSection()
  25. {
  26. assert(FAcquired == 0);
  27. DeleteCriticalSection(&FSection);
  28. }
  29. //---------------------------------------------------------------------------
  30. void __fastcall TCriticalSection::Enter()
  31. {
  32. EnterCriticalSection(&FSection);
  33. FAcquired++;
  34. }
  35. //---------------------------------------------------------------------------
  36. void __fastcall TCriticalSection::Leave()
  37. {
  38. FAcquired--;
  39. LeaveCriticalSection(&FSection);
  40. }
  41. //---------------------------------------------------------------------------
  42. // TGuard
  43. //---------------------------------------------------------------------------
  44. __fastcall TGuard::TGuard(TCriticalSection * ACriticalSection) :
  45. FCriticalSection(ACriticalSection)
  46. {
  47. assert(ACriticalSection != NULL);
  48. FCriticalSection->Enter();
  49. }
  50. //---------------------------------------------------------------------------
  51. __fastcall TGuard::~TGuard()
  52. {
  53. FCriticalSection->Leave();
  54. }
  55. //---------------------------------------------------------------------------
  56. // TUnguard
  57. //---------------------------------------------------------------------------
  58. __fastcall TUnguard::TUnguard(TCriticalSection * ACriticalSection) :
  59. FCriticalSection(ACriticalSection)
  60. {
  61. assert(ACriticalSection != NULL);
  62. FCriticalSection->Leave();
  63. }
  64. //---------------------------------------------------------------------------
  65. __fastcall TUnguard::~TUnguard()
  66. {
  67. FCriticalSection->Enter();
  68. }
  69. //---------------------------------------------------------------------------
  70. //---------------------------------------------------------------------------
  71. const char EngShortMonthNames[12][4] =
  72. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  73. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  74. //---------------------------------------------------------------------------
  75. AnsiString ReplaceChar(AnsiString Str, Char A, Char B)
  76. {
  77. for (Integer Index = 0; Index < Str.Length(); Index++)
  78. if (Str[Index+1] == A) Str[Index+1] = B;
  79. return Str;
  80. }
  81. //---------------------------------------------------------------------------
  82. AnsiString DeleteChar(AnsiString Str, Char C)
  83. {
  84. int P;
  85. while ((P = Str.Pos(C)) > 0)
  86. {
  87. Str.Delete(P, 1);
  88. }
  89. return Str;
  90. }
  91. //---------------------------------------------------------------------------
  92. void PackStr(AnsiString &Str)
  93. {
  94. // Following will free unnecessary bytes
  95. Str = Str.c_str();
  96. }
  97. //---------------------------------------------------------------------------
  98. AnsiString MakeValidFileName(AnsiString FileName)
  99. {
  100. AnsiString IllegalChars = ":;,=+<>|\"[] \\/?*";
  101. for (int Index = 0; Index < IllegalChars.Length(); Index++)
  102. {
  103. FileName = ReplaceChar(FileName, IllegalChars[Index+1], '-');
  104. }
  105. return FileName;
  106. }
  107. //---------------------------------------------------------------------------
  108. AnsiString RootKeyToStr(HKEY RootKey)
  109. {
  110. if (RootKey == HKEY_USERS) return "HKEY_USERS";
  111. else
  112. if (RootKey == HKEY_LOCAL_MACHINE) return "HKEY_LOCAL_MACHINE";
  113. else
  114. if (RootKey == HKEY_CURRENT_USER) return "HKEY_CURRENT_USER";
  115. else
  116. if (RootKey == HKEY_CLASSES_ROOT) return "HKEY_CLASSES_ROOT";
  117. else
  118. if (RootKey == HKEY_CURRENT_CONFIG) return "HKEY_CURRENT_CONFIG";
  119. else
  120. if (RootKey == HKEY_DYN_DATA) return "HKEY_DYN_DATA";
  121. else
  122. { Abort(); return ""; };
  123. }
  124. //---------------------------------------------------------------------------
  125. AnsiString BooleanToEngStr(bool B)
  126. {
  127. if (B)
  128. {
  129. return "Yes";
  130. }
  131. else
  132. {
  133. return "No";
  134. }
  135. }
  136. //---------------------------------------------------------------------------
  137. AnsiString BooleanToStr(bool B)
  138. {
  139. if (B)
  140. {
  141. return LoadStr(YES_STR);
  142. }
  143. else
  144. {
  145. return LoadStr(NO_STR);
  146. }
  147. }
  148. //---------------------------------------------------------------------------
  149. AnsiString DefaultStr(const AnsiString & Str, const AnsiString & Default)
  150. {
  151. if (!Str.IsEmpty())
  152. {
  153. return Str;
  154. }
  155. else
  156. {
  157. return Default;
  158. }
  159. }
  160. //---------------------------------------------------------------------------
  161. AnsiString CutToChar(AnsiString &Str, Char Ch, bool Trim)
  162. {
  163. Integer P = Str.Pos(Ch);
  164. AnsiString Result;
  165. if (P)
  166. {
  167. Result = Str.SubString(1, P-1);
  168. Str.Delete(1, P);
  169. }
  170. else
  171. {
  172. Result = Str;
  173. Str = "";
  174. }
  175. if (Trim)
  176. {
  177. Result = Result.TrimRight();
  178. Str = Str.TrimLeft();
  179. }
  180. return Result;
  181. }
  182. //---------------------------------------------------------------------------
  183. AnsiString CopyToChars(const AnsiString & Str, int & From, AnsiString Chs, bool Trim,
  184. char * Delimiter)
  185. {
  186. int P;
  187. for (P = From; P <= Str.Length(); P++)
  188. {
  189. if (IsDelimiter(Chs, Str, P))
  190. {
  191. break;
  192. }
  193. }
  194. AnsiString Result;
  195. if (P <= Str.Length())
  196. {
  197. if (Delimiter != NULL)
  198. {
  199. *Delimiter = Str[P];
  200. }
  201. Result = Str.SubString(From, P-From);
  202. From = P+1;
  203. }
  204. else
  205. {
  206. if (Delimiter != NULL)
  207. {
  208. *Delimiter = '\0';
  209. }
  210. Result = Str.SubString(From, Str.Length() - From + 1);
  211. From = P;
  212. }
  213. if (Trim)
  214. {
  215. Result = Result.TrimRight();
  216. while ((P <= Str.Length()) && (Str[P] == ' '))
  217. {
  218. P++;
  219. }
  220. }
  221. return Result;
  222. }
  223. //---------------------------------------------------------------------------
  224. AnsiString DelimitStr(AnsiString Str, AnsiString Chars)
  225. {
  226. for (int i = 1; i <= Str.Length(); i++)
  227. {
  228. if (Str.IsDelimiter(Chars, i))
  229. {
  230. Str.Insert("\\", i);
  231. i++;
  232. }
  233. }
  234. return Str;
  235. }
  236. //---------------------------------------------------------------------------
  237. AnsiString ShellDelimitStr(AnsiString Str, char Quote)
  238. {
  239. AnsiString Chars = "$\\";
  240. if (Quote == '"')
  241. {
  242. Chars += "`\"";
  243. }
  244. return DelimitStr(Str, Chars);
  245. }
  246. //---------------------------------------------------------------------------
  247. AnsiString ExceptionLogString(Exception *E)
  248. {
  249. assert(E);
  250. if (E->InheritsFrom(__classid(Exception)))
  251. {
  252. AnsiString Msg;
  253. Msg = FORMAT("(%s) %s", (E->ClassName(), E->Message));
  254. if (E->InheritsFrom(__classid(ExtException)))
  255. {
  256. TStrings * MoreMessages = ((ExtException*)E)->MoreMessages;
  257. if (MoreMessages)
  258. {
  259. Msg += "\n" +
  260. StringReplace(MoreMessages->Text, "\r", "", TReplaceFlags() << rfReplaceAll);
  261. }
  262. }
  263. return Msg;
  264. }
  265. else
  266. {
  267. char Buffer[1024];
  268. ExceptionErrorMessage(ExceptObject(), ExceptAddr(), Buffer, sizeof(Buffer));
  269. return AnsiString(Buffer);
  270. }
  271. }
  272. //---------------------------------------------------------------------------
  273. bool IsNumber(const AnsiString Str)
  274. {
  275. int Value;
  276. return TryStrToInt(Str, Value);
  277. }
  278. //---------------------------------------------------------------------------
  279. AnsiString __fastcall SystemTemporaryDirectory()
  280. {
  281. AnsiString TempDir;
  282. TempDir.SetLength(MAX_PATH);
  283. TempDir.SetLength(GetTempPath(MAX_PATH, TempDir.c_str()));
  284. return TempDir;
  285. }
  286. //---------------------------------------------------------------------------
  287. AnsiString __fastcall GetShellFolderPath(int CSIdl)
  288. {
  289. AnsiString Result;
  290. HMODULE Shell32Lib = LoadLibrary("SHELL32.DLL");
  291. if (Shell32Lib != NULL)
  292. {
  293. PFNSHGETFOLDERPATH SHGetFolderPath = (PFNSHGETFOLDERPATH)
  294. GetProcAddress(Shell32Lib, "SHGetFolderPathA");
  295. if (SHGetFolderPath != NULL)
  296. {
  297. char Path[2 * MAX_PATH + 10] = "\0";
  298. if (SUCCEEDED(SHGetFolderPath(NULL, CSIdl, NULL, SHGFP_TYPE_CURRENT, Path)))
  299. {
  300. Result = Path;
  301. }
  302. }
  303. }
  304. return Result;
  305. }
  306. //---------------------------------------------------------------------------
  307. AnsiString __fastcall StripPathQuotes(const AnsiString Path)
  308. {
  309. if ((Path.Length() >= 2) &&
  310. (Path[1] == '\"') && (Path[Path.Length()] == '\"'))
  311. {
  312. return Path.SubString(2, Path.Length() - 2);
  313. }
  314. else
  315. {
  316. return Path;
  317. }
  318. }
  319. //---------------------------------------------------------------------------
  320. AnsiString __fastcall AddPathQuotes(AnsiString Path)
  321. {
  322. Path = StripPathQuotes(Path);
  323. if (Path.Pos(" "))
  324. {
  325. Path = "\"" + Path + "\"";
  326. }
  327. return Path;
  328. }
  329. //---------------------------------------------------------------------------
  330. void __fastcall SplitCommand(AnsiString Command, AnsiString &Program,
  331. AnsiString & Params, AnsiString & Dir)
  332. {
  333. Command = Command.Trim();
  334. Params = "";
  335. Dir = "";
  336. if (!Command.IsEmpty() && (Command[1] == '\"'))
  337. {
  338. Command.Delete(1, 1);
  339. int P = Command.Pos('"');
  340. if (P)
  341. {
  342. Program = Command.SubString(1, P-1).Trim();
  343. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  344. }
  345. else
  346. {
  347. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, ("\"" + Command)));
  348. }
  349. }
  350. else
  351. {
  352. int P = Command.Pos(" ");
  353. if (P)
  354. {
  355. Program = Command.SubString(1, P).Trim();
  356. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  357. }
  358. else
  359. {
  360. Program = Command;
  361. }
  362. }
  363. int B = Program.LastDelimiter("\\/");
  364. if (B)
  365. {
  366. Dir = Program.SubString(1, B).Trim();
  367. }
  368. }
  369. //---------------------------------------------------------------------------
  370. AnsiString __fastcall ExtractProgram(AnsiString Command)
  371. {
  372. AnsiString Program;
  373. AnsiString Params;
  374. AnsiString Dir;
  375. SplitCommand(Command, Program, Params, Dir);
  376. return Program;
  377. }
  378. //---------------------------------------------------------------------------
  379. AnsiString __fastcall FormatCommand(AnsiString Program, AnsiString Params)
  380. {
  381. Program = Program.Trim();
  382. Params = Params.Trim();
  383. if (!Params.IsEmpty()) Params = " " + Params;
  384. if (Program.Pos(" ")) Program = "\"" + Program + "\"";
  385. return Program + Params;
  386. }
  387. //---------------------------------------------------------------------------
  388. const char ShellCommandFileNamePattern[] = "!.!";
  389. //---------------------------------------------------------------------------
  390. void __fastcall ReformatFileNameCommand(AnsiString & Command)
  391. {
  392. if (!Command.IsEmpty())
  393. {
  394. AnsiString Program, Params, Dir;
  395. SplitCommand(Command, Program, Params, Dir);
  396. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  397. {
  398. Params = Params + (Params.IsEmpty() ? "" : " ") + ShellCommandFileNamePattern;
  399. }
  400. Command = FormatCommand(Program, Params);
  401. }
  402. }
  403. //---------------------------------------------------------------------------
  404. AnsiString __fastcall ExpandFileNameCommand(const AnsiString Command,
  405. const AnsiString FileName)
  406. {
  407. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  408. AddPathQuotes(FileName));
  409. }
  410. //---------------------------------------------------------------------------
  411. AnsiString __fastcall EscapePuttyCommandParam(AnsiString Param)
  412. {
  413. bool Space = false;
  414. for (int i = 1; i <= Param.Length(); i++)
  415. {
  416. switch (Param[i])
  417. {
  418. case '"':
  419. Param.Insert("\\", i);
  420. i++;
  421. break;
  422. case ' ':
  423. Space = true;
  424. break;
  425. case '\\':
  426. int i2 = i;
  427. while ((i2 <= Param.Length()) && (Param[i2] == '\\'))
  428. {
  429. i2++;
  430. }
  431. if ((i2 <= Param.Length()) && (Param[i2] == '"'))
  432. {
  433. while (Param[i] == '\\')
  434. {
  435. Param.Insert("\\", i);
  436. i += 2;
  437. }
  438. i--;
  439. }
  440. break;
  441. }
  442. }
  443. if (Space)
  444. {
  445. Param = "\"" + Param + '"';
  446. }
  447. return Param;
  448. }
  449. //---------------------------------------------------------------------------
  450. AnsiString __fastcall ExpandEnvironmentVariables(const AnsiString & Str)
  451. {
  452. AnsiString Buf;
  453. unsigned int Size = 1024;
  454. Buf.SetLength(Size);
  455. Buf.Unique();
  456. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  457. if (Len > Size)
  458. {
  459. Buf.SetLength(Len);
  460. Buf.Unique();
  461. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  462. }
  463. PackStr(Buf);
  464. return Buf;
  465. }
  466. //---------------------------------------------------------------------------
  467. bool __fastcall CompareFileName(const AnsiString & Path1, const AnsiString & Path2)
  468. {
  469. AnsiString ShortPath1 = ExtractShortPathName(Path1);
  470. AnsiString ShortPath2 = ExtractShortPathName(Path2);
  471. bool Result;
  472. // ExtractShortPathName returns empty string if file does not exist
  473. if (ShortPath1.IsEmpty() || ShortPath2.IsEmpty())
  474. {
  475. Result = AnsiSameText(Path1, Path2);
  476. }
  477. else
  478. {
  479. Result = AnsiSameText(ShortPath1, ShortPath2);
  480. }
  481. return Result;
  482. }
  483. //---------------------------------------------------------------------------
  484. bool __fastcall ComparePaths(const AnsiString & Path1, const AnsiString & Path2)
  485. {
  486. // TODO: ExpandUNCFileName
  487. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  488. }
  489. //---------------------------------------------------------------------------
  490. bool __fastcall IsReservedName(AnsiString FileName)
  491. {
  492. int P = FileName.Pos(".");
  493. int Len = (P > 0) ? P - 1 : FileName.Length();
  494. if ((Len == 3) || (Len == 4))
  495. {
  496. if (P > 0)
  497. {
  498. FileName.SetLength(P - 1);
  499. }
  500. static AnsiString Reserved[] = {
  501. "CON", "PRN", "AUX", "NUL",
  502. "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
  503. "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };
  504. for (int Index = 0; Index < LENOF(Reserved); Index++)
  505. {
  506. if (SameText(FileName, Reserved[Index]))
  507. {
  508. return true;
  509. }
  510. }
  511. }
  512. return false;
  513. }
  514. //---------------------------------------------------------------------------
  515. AnsiString __fastcall DisplayableStr(const AnsiString Str)
  516. {
  517. bool Displayable = true;
  518. int Index = 1;
  519. while ((Index <= Str.Length()) && Displayable)
  520. {
  521. if ((Str[Index] < '\32') &&
  522. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  523. {
  524. Displayable = false;
  525. }
  526. Index++;
  527. }
  528. AnsiString Result;
  529. if (Displayable)
  530. {
  531. Result = "\"";
  532. for (int Index = 1; Index <= Str.Length(); Index++)
  533. {
  534. switch (Str[Index])
  535. {
  536. case '\n':
  537. Result += "\\n";
  538. break;
  539. case '\r':
  540. Result += "\\r";
  541. break;
  542. case '\t':
  543. Result += "\\t";
  544. break;
  545. case '\b':
  546. Result += "\\b";
  547. break;
  548. case '\\':
  549. Result += "\\\\";
  550. break;
  551. case '"':
  552. Result += "\\\"";
  553. break;
  554. default:
  555. Result += Str[Index];
  556. break;
  557. }
  558. }
  559. Result += "\"";
  560. }
  561. else
  562. {
  563. Result = "0x" + StrToHex(Str);
  564. }
  565. return Result;
  566. }
  567. //---------------------------------------------------------------------------
  568. AnsiString __fastcall CharToHex(char Ch, bool UpperCase)
  569. {
  570. static char UpperDigits[] = "0123456789ABCDEF";
  571. static char LowerDigits[] = "0123456789abcdef";
  572. const char * Digits = (UpperCase ? UpperDigits : LowerDigits);
  573. AnsiString Result;
  574. Result.SetLength(2);
  575. Result[1] = Digits[((unsigned char)Ch & 0xF0) >> 4];
  576. Result[2] = Digits[ (unsigned char)Ch & 0x0F];
  577. return Result;
  578. }
  579. //---------------------------------------------------------------------------
  580. AnsiString __fastcall StrToHex(const AnsiString Str, bool UpperCase, char Separator)
  581. {
  582. AnsiString Result;
  583. for (int i = 1; i <= Str.Length(); i++)
  584. {
  585. Result += CharToHex(Str[i], UpperCase);
  586. if ((Separator != '\0') && (i < Str.Length()))
  587. {
  588. Result += Separator;
  589. }
  590. }
  591. return Result;
  592. }
  593. //---------------------------------------------------------------------------
  594. AnsiString __fastcall HexToStr(const AnsiString Hex)
  595. {
  596. static AnsiString Digits = "0123456789ABCDEF";
  597. AnsiString Result;
  598. int L, P1, P2;
  599. L = Hex.Length();
  600. if (L % 2 == 0)
  601. {
  602. for (int i = 1; i <= Hex.Length(); i += 2)
  603. {
  604. P1 = Digits.Pos((char)toupper(Hex[i]));
  605. P2 = Digits.Pos((char)toupper(Hex[i + 1]));
  606. if (P1 <= 0 || P2 <= 0)
  607. {
  608. Result = "";
  609. break;
  610. }
  611. else
  612. {
  613. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  614. }
  615. }
  616. }
  617. return Result;
  618. }
  619. //---------------------------------------------------------------------------
  620. unsigned int __fastcall HexToInt(const AnsiString Hex, int MinChars)
  621. {
  622. static AnsiString Digits = "0123456789ABCDEF";
  623. int Result = 0;
  624. int I = 1;
  625. while (I <= Hex.Length())
  626. {
  627. int A = Digits.Pos((char)toupper(Hex[I]));
  628. if (A <= 0)
  629. {
  630. if ((MinChars < 0) || (I <= MinChars))
  631. {
  632. Result = 0;
  633. }
  634. break;
  635. }
  636. Result = (Result * 16) + (A - 1);
  637. I++;
  638. }
  639. return Result;
  640. }
  641. //---------------------------------------------------------------------------
  642. char __fastcall HexToChar(const AnsiString Hex, int MinChars)
  643. {
  644. return (char)HexToInt(Hex, MinChars);
  645. }
  646. //---------------------------------------------------------------------------
  647. bool __fastcall FileSearchRec(const AnsiString FileName, TSearchRec & Rec)
  648. {
  649. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  650. bool Result = (FindFirst(FileName, FindAttrs, Rec) == 0);
  651. if (Result)
  652. {
  653. FindClose(Rec);
  654. }
  655. return Result;
  656. }
  657. //---------------------------------------------------------------------------
  658. void __fastcall ProcessLocalDirectory(AnsiString DirName,
  659. TProcessLocalFileEvent CallBackFunc, void * Param,
  660. int FindAttrs)
  661. {
  662. assert(CallBackFunc);
  663. if (FindAttrs < 0)
  664. {
  665. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  666. }
  667. TSearchRec SearchRec;
  668. DirName = IncludeTrailingBackslash(DirName);
  669. if (FindFirst(DirName + "*.*", FindAttrs, SearchRec) == 0)
  670. {
  671. try
  672. {
  673. do
  674. {
  675. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  676. {
  677. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  678. }
  679. } while (FindNext(SearchRec) == 0);
  680. }
  681. __finally
  682. {
  683. FindClose(SearchRec);
  684. }
  685. }
  686. }
  687. //---------------------------------------------------------------------------
  688. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  689. {
  690. try
  691. {
  692. return EncodeDate(Year, Month, Day);
  693. }
  694. catch (EConvertError & E)
  695. {
  696. throw EConvertError(FORMAT("%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  697. }
  698. }
  699. //---------------------------------------------------------------------------
  700. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  701. {
  702. try
  703. {
  704. return EncodeTime(Hour, Min, Sec, MSec);
  705. }
  706. catch (EConvertError & E)
  707. {
  708. throw EConvertError(FORMAT("%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  709. }
  710. }
  711. //---------------------------------------------------------------------------
  712. struct TDateTimeParams
  713. {
  714. TDateTime UnixEpoch;
  715. double BaseDifference;
  716. long BaseDifferenceSec;
  717. double CurrentDaylightDifference;
  718. long CurrentDaylightDifferenceSec;
  719. double CurrentDifference;
  720. long CurrentDifferenceSec;
  721. double StandardDifference;
  722. long StandardDifferenceSec;
  723. double DaylightDifference;
  724. long DaylightDifferenceSec;
  725. SYSTEMTIME StandardDate;
  726. SYSTEMTIME DaylightDate;
  727. bool DaylightHack;
  728. };
  729. static bool DateTimeParamsInitialized = false;
  730. static TDateTimeParams DateTimeParams;
  731. static TCriticalSection DateTimeParamsSection;
  732. //---------------------------------------------------------------------------
  733. static TDateTimeParams * __fastcall GetDateTimeParams()
  734. {
  735. if (!DateTimeParamsInitialized)
  736. {
  737. TGuard Guard(&DateTimeParamsSection);
  738. if (!DateTimeParamsInitialized)
  739. {
  740. TIME_ZONE_INFORMATION TZI;
  741. unsigned long GTZI;
  742. GTZI = GetTimeZoneInformation(&TZI);
  743. switch (GTZI)
  744. {
  745. case TIME_ZONE_ID_UNKNOWN:
  746. DateTimeParams.CurrentDaylightDifferenceSec = 0;
  747. break;
  748. case TIME_ZONE_ID_STANDARD:
  749. DateTimeParams.CurrentDaylightDifferenceSec = TZI.StandardBias;
  750. break;
  751. case TIME_ZONE_ID_DAYLIGHT:
  752. DateTimeParams.CurrentDaylightDifferenceSec = TZI.DaylightBias;
  753. break;
  754. case TIME_ZONE_ID_INVALID:
  755. default:
  756. throw Exception(TIMEZONE_ERROR);
  757. }
  758. // Is it same as SysUtils::UnixDateDelta = 25569 ??
  759. DateTimeParams.UnixEpoch = EncodeDateVerbose(1970, 1, 1);
  760. DateTimeParams.BaseDifferenceSec = TZI.Bias;
  761. DateTimeParams.BaseDifference = double(TZI.Bias) / 1440;
  762. DateTimeParams.BaseDifferenceSec *= 60;
  763. DateTimeParams.CurrentDifferenceSec = TZI.Bias +
  764. DateTimeParams.CurrentDaylightDifferenceSec;
  765. DateTimeParams.CurrentDifference =
  766. double(DateTimeParams.CurrentDifferenceSec) / 1440;
  767. DateTimeParams.CurrentDifferenceSec *= 60;
  768. DateTimeParams.CurrentDaylightDifference =
  769. double(DateTimeParams.CurrentDaylightDifferenceSec) / 1440;
  770. DateTimeParams.CurrentDaylightDifferenceSec *= 60;
  771. DateTimeParams.DaylightDifferenceSec = TZI.DaylightBias * 60;
  772. DateTimeParams.DaylightDifference = double(TZI.DaylightBias) / 1440;
  773. DateTimeParams.StandardDifferenceSec = TZI.StandardBias * 60;
  774. DateTimeParams.StandardDifference = double(TZI.StandardBias) / 1440;
  775. DateTimeParams.StandardDate = TZI.StandardDate;
  776. DateTimeParams.DaylightDate = TZI.DaylightDate;
  777. DateTimeParams.DaylightHack = !IsWin7() || IsExactly2008R2();
  778. DateTimeParamsInitialized = true;
  779. }
  780. }
  781. return &DateTimeParams;
  782. }
  783. //---------------------------------------------------------------------------
  784. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  785. TDateTime & Result)
  786. {
  787. if (Date.wYear == 0)
  788. {
  789. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  790. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  791. (7 * (Date.wDay - 1));
  792. if (Date.wDay == 5)
  793. {
  794. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  795. if (Month > 12)
  796. {
  797. Month = static_cast<unsigned short>(Month - 12);
  798. Year++;
  799. }
  800. if (Result >= EncodeDateVerbose(Year, Month, 1))
  801. {
  802. Result -= 7;
  803. }
  804. }
  805. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  806. Date.wMilliseconds);
  807. }
  808. else
  809. {
  810. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  811. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  812. }
  813. }
  814. //---------------------------------------------------------------------------
  815. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  816. {
  817. struct TDSTCache
  818. {
  819. bool Filled;
  820. unsigned short Year;
  821. TDateTime StandardDate;
  822. TDateTime DaylightDate;
  823. bool SummerDST;
  824. };
  825. static TDSTCache DSTCache[10];
  826. static int DSTCacheCount = 0;
  827. static TCriticalSection Section;
  828. TDateTimeParams * Params = GetDateTimeParams();
  829. bool Result;
  830. // On some systems it occurs that StandardDate is unset, while
  831. // DaylightDate is set. MSDN states that this is invalid and
  832. // should be treated as if there is no daylinght saving.
  833. // So check both.
  834. if ((Params->StandardDate.wMonth == 0) ||
  835. (Params->DaylightDate.wMonth == 0))
  836. {
  837. Result = false;
  838. }
  839. else
  840. {
  841. unsigned short Year, Month, Day;
  842. DecodeDate(DateTime, Year, Month, Day);
  843. TDSTCache * CurrentCache = &DSTCache[0];
  844. int CacheIndex = 0;
  845. while ((CacheIndex < DSTCacheCount) && (CacheIndex < LENOF(DSTCache)) &&
  846. CurrentCache->Filled && (CurrentCache->Year != Year))
  847. {
  848. CacheIndex++;
  849. CurrentCache++;
  850. }
  851. TDSTCache NewCache;
  852. if ((CacheIndex < DSTCacheCount) && (CacheIndex < LENOF(DSTCache)) &&
  853. CurrentCache->Filled)
  854. {
  855. assert(CurrentCache->Year == Year);
  856. }
  857. else
  858. {
  859. EncodeDSTMargin(Params->StandardDate, Year, NewCache.StandardDate);
  860. EncodeDSTMargin(Params->DaylightDate, Year, NewCache.DaylightDate);
  861. NewCache.SummerDST = (NewCache.DaylightDate < NewCache.StandardDate);
  862. if (DSTCacheCount < LENOF(DSTCache))
  863. {
  864. TGuard Guard(&Section);
  865. if (DSTCacheCount < LENOF(DSTCache))
  866. {
  867. NewCache.Year = Year;
  868. DSTCache[DSTCacheCount] = NewCache;
  869. DSTCache[DSTCacheCount].Filled = true;
  870. DSTCacheCount++;
  871. }
  872. }
  873. CurrentCache = &NewCache;
  874. }
  875. if (CurrentCache->SummerDST)
  876. {
  877. Result =
  878. (DateTime >= CurrentCache->DaylightDate) &&
  879. (DateTime < CurrentCache->StandardDate);
  880. }
  881. else
  882. {
  883. Result =
  884. (DateTime < CurrentCache->StandardDate) ||
  885. (DateTime >= CurrentCache->DaylightDate);
  886. }
  887. }
  888. return Result;
  889. }
  890. //---------------------------------------------------------------------------
  891. bool __fastcall UsesDaylightHack()
  892. {
  893. return GetDateTimeParams()->DaylightHack;
  894. }
  895. //---------------------------------------------------------------------------
  896. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  897. {
  898. TDateTimeParams * Params = GetDateTimeParams();
  899. TDateTime Result;
  900. Result = Params->UnixEpoch + (double(TimeStamp) / 86400);
  901. if (Params->DaylightHack)
  902. {
  903. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  904. {
  905. Result -= Params->CurrentDifference;
  906. }
  907. else if (DSTMode == dstmKeep)
  908. {
  909. Result -= Params->BaseDifference;
  910. }
  911. }
  912. else
  913. {
  914. Result -= Params->BaseDifference;
  915. }
  916. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  917. {
  918. Result -= (IsDateInDST(Result) ?
  919. Params->DaylightDifference : Params->StandardDifference);
  920. }
  921. return Result;
  922. }
  923. //---------------------------------------------------------------------------
  924. __int64 __fastcall Round(double Number)
  925. {
  926. double Floor = floor(Number);
  927. double Ceil = ceil(Number);
  928. return ((Number - Floor) > (Ceil - Number)) ? Ceil : Floor;
  929. }
  930. //---------------------------------------------------------------------------
  931. #define TIME_POSIX_TO_WIN(t, ft) (*(LONGLONG*)&(ft) = \
  932. ((LONGLONG) (t) + (LONGLONG) 11644473600) * (LONGLONG) 10000000)
  933. #define TIME_WIN_TO_POSIX(ft, t) ((t) = (__int64) \
  934. ((*(LONGLONG*)&(ft)) / (LONGLONG) 10000000 - (LONGLONG) 11644473600))
  935. //---------------------------------------------------------------------------
  936. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  937. {
  938. TDateTimeParams * Params = GetDateTimeParams();
  939. return Round(double(DateTime - Params->UnixEpoch) * 86400) +
  940. Params->CurrentDifferenceSec;
  941. }
  942. //---------------------------------------------------------------------------
  943. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  944. TDSTMode /*DSTMode*/)
  945. {
  946. FILETIME Result;
  947. __int64 UnixTimeStamp = DateTimeToUnix(DateTime);
  948. TDateTimeParams * Params = GetDateTimeParams();
  949. if (!Params->DaylightHack)
  950. {
  951. UnixTimeStamp += (IsDateInDST(DateTime) ?
  952. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  953. UnixTimeStamp -= Params->CurrentDaylightDifferenceSec;
  954. }
  955. TIME_POSIX_TO_WIN(UnixTimeStamp, Result);
  956. return Result;
  957. }
  958. //---------------------------------------------------------------------------
  959. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  960. {
  961. // duplicated in DirView.pas
  962. SYSTEMTIME SysTime;
  963. TDateTimeParams * Params = GetDateTimeParams();
  964. if (!Params->DaylightHack)
  965. {
  966. SYSTEMTIME UniverzalSysTime;
  967. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  968. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  969. }
  970. else
  971. {
  972. FILETIME LocalFileTime;
  973. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  974. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  975. }
  976. TDateTime Result = SystemTimeToDateTime(SysTime);
  977. return Result;
  978. }
  979. //---------------------------------------------------------------------------
  980. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  981. TDSTMode DSTMode)
  982. {
  983. __int64 Result;
  984. TIME_WIN_TO_POSIX(FileTime, Result);
  985. TDateTimeParams * Params = GetDateTimeParams();
  986. if (Params->DaylightHack)
  987. {
  988. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  989. {
  990. FILETIME LocalFileTime;
  991. SYSTEMTIME SystemTime;
  992. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  993. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  994. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  995. Result += (IsDateInDST(DateTime) ?
  996. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  997. if (DSTMode == dstmKeep)
  998. {
  999. Result -= Params->CurrentDaylightDifferenceSec;
  1000. }
  1001. }
  1002. }
  1003. else
  1004. {
  1005. if (DSTMode == dstmWin)
  1006. {
  1007. FILETIME LocalFileTime;
  1008. SYSTEMTIME SystemTime;
  1009. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1010. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1011. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1012. Result -= (IsDateInDST(DateTime) ?
  1013. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1014. }
  1015. }
  1016. return Result;
  1017. }
  1018. //---------------------------------------------------------------------------
  1019. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1020. {
  1021. TDateTimeParams * Params = GetDateTimeParams();
  1022. DateTime +=
  1023. (IsDateInDST(DateTime) ?
  1024. Params->DaylightDifference : Params->StandardDifference);
  1025. DateTime += Params->BaseDifference;
  1026. if (Params->DaylightHack)
  1027. {
  1028. const TDateTimeParams * CurrentParams = GetDateTimeParams();
  1029. DateTime += CurrentParams->CurrentDaylightDifference;
  1030. }
  1031. return DateTime;
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1035. TDSTMode DSTMode)
  1036. {
  1037. __int64 Result;
  1038. if ((FileTime.dwLowDateTime == 0) &&
  1039. (FileTime.dwHighDateTime == 0))
  1040. {
  1041. Result = DateTimeToUnix(Now());
  1042. }
  1043. else
  1044. {
  1045. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1046. }
  1047. return Result;
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1051. {
  1052. TDateTimeParams * Params = GetDateTimeParams();
  1053. if (Params->DaylightHack)
  1054. {
  1055. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1056. {
  1057. DateTime = DateTime - Params->CurrentDaylightDifference;
  1058. }
  1059. if (!IsDateInDST(DateTime))
  1060. {
  1061. if (DSTMode == dstmWin)
  1062. {
  1063. DateTime = DateTime - Params->DaylightDifference;
  1064. }
  1065. }
  1066. else
  1067. {
  1068. DateTime = DateTime - Params->StandardDifference;
  1069. }
  1070. }
  1071. else
  1072. {
  1073. if (DSTMode == dstmWin)
  1074. {
  1075. if (IsDateInDST(DateTime))
  1076. {
  1077. DateTime = DateTime + Params->DaylightDifference;
  1078. }
  1079. else
  1080. {
  1081. DateTime = DateTime + Params->StandardDifference;
  1082. }
  1083. }
  1084. }
  1085. return DateTime;
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. AnsiString __fastcall FixedLenDateTimeFormat(const AnsiString & Format)
  1089. {
  1090. AnsiString Result = Format;
  1091. bool AsIs = false;
  1092. int Index = 1;
  1093. while (Index <= Result.Length())
  1094. {
  1095. char F = Result[Index];
  1096. if ((F == '\'') || (F == '\"'))
  1097. {
  1098. AsIs = !AsIs;
  1099. Index++;
  1100. }
  1101. else if (!AsIs && ((F == 'a') || (F == 'A')))
  1102. {
  1103. if (Result.SubString(Index, 5).LowerCase() == "am/pm")
  1104. {
  1105. Index += 5;
  1106. }
  1107. else if (Result.SubString(Index, 3).LowerCase() == "a/p")
  1108. {
  1109. Index += 3;
  1110. }
  1111. else if (Result.SubString(Index, 4).LowerCase() == "ampm")
  1112. {
  1113. Index += 4;
  1114. }
  1115. else
  1116. {
  1117. Index++;
  1118. }
  1119. }
  1120. else
  1121. {
  1122. if (!AsIs && (strchr("dDeEmMhHnNsS", F) != NULL) &&
  1123. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1124. {
  1125. Result.Insert(F, Index);
  1126. }
  1127. while ((Index <= Result.Length()) && (F == Result[Index]))
  1128. {
  1129. Index++;
  1130. }
  1131. }
  1132. }
  1133. return Result;
  1134. }
  1135. //---------------------------------------------------------------------------
  1136. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1137. {
  1138. // "FAT" time precision
  1139. // (when one time is seconds-precision and other is millisecond-precision,
  1140. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1141. // be treated the same)
  1142. static TDateTime TwoSeconds(0, 0, 2, 0);
  1143. int Result;
  1144. if (T1 == T2)
  1145. {
  1146. // just optimalisation
  1147. Result = 0;
  1148. }
  1149. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1150. {
  1151. Result = -1;
  1152. }
  1153. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1154. {
  1155. Result = 1;
  1156. }
  1157. else
  1158. {
  1159. Result = 0;
  1160. }
  1161. return Result;
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. bool __fastcall RecursiveDeleteFile(const AnsiString FileName, bool ToRecycleBin)
  1165. {
  1166. SHFILEOPSTRUCT Data;
  1167. memset(&Data, 0, sizeof(Data));
  1168. Data.hwnd = NULL;
  1169. Data.wFunc = FO_DELETE;
  1170. AnsiString FileList(FileName);
  1171. FileList.SetLength(FileList.Length() + 2);
  1172. FileList[FileList.Length() - 1] = '\0';
  1173. FileList[FileList.Length()] = '\0';
  1174. Data.pFrom = FileList.c_str();
  1175. Data.pTo = "";
  1176. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1177. FOF_NOERRORUI | FOF_SILENT;
  1178. if (ToRecycleBin)
  1179. {
  1180. Data.fFlags |= FOF_ALLOWUNDO;
  1181. }
  1182. int ErrorCode = SHFileOperation(&Data);
  1183. bool Result = (ErrorCode == 0);
  1184. if (!Result)
  1185. {
  1186. // according to MSDN, SHFileOperation may return following non-Win32
  1187. // error codes
  1188. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  1189. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  1190. (ErrorCode == 0x10074))
  1191. {
  1192. ErrorCode = 0;
  1193. }
  1194. SetLastError(ErrorCode);
  1195. }
  1196. return Result;
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. int __fastcall CancelAnswer(int Answers)
  1200. {
  1201. int Result;
  1202. if ((Answers & qaCancel) != 0)
  1203. {
  1204. Result = qaCancel;
  1205. }
  1206. else if ((Answers & qaNo) != 0)
  1207. {
  1208. Result = qaNo;
  1209. }
  1210. else if ((Answers & qaAbort) != 0)
  1211. {
  1212. Result = qaAbort;
  1213. }
  1214. else if ((Answers & qaOK) != 0)
  1215. {
  1216. Result = qaOK;
  1217. }
  1218. else
  1219. {
  1220. assert(false);
  1221. Result = qaCancel;
  1222. }
  1223. return Result;
  1224. }
  1225. //---------------------------------------------------------------------------
  1226. int __fastcall AbortAnswer(int Answers)
  1227. {
  1228. int Result;
  1229. if (FLAGSET(Answers, qaAbort))
  1230. {
  1231. Result = qaAbort;
  1232. }
  1233. else
  1234. {
  1235. Result = CancelAnswer(Answers);
  1236. }
  1237. return Result;
  1238. }
  1239. //---------------------------------------------------------------------------
  1240. int __fastcall ContinueAnswer(int Answers)
  1241. {
  1242. int Result;
  1243. if (FLAGSET(Answers, qaSkip))
  1244. {
  1245. Result = qaSkip;
  1246. }
  1247. else if (FLAGSET(Answers, qaIgnore))
  1248. {
  1249. Result = qaIgnore;
  1250. }
  1251. else if (FLAGSET(Answers, qaYes))
  1252. {
  1253. Result = qaYes;
  1254. }
  1255. else if (FLAGSET(Answers, qaOK))
  1256. {
  1257. Result = qaOK;
  1258. }
  1259. else if (FLAGSET(Answers, qaRetry))
  1260. {
  1261. Result = qaRetry;
  1262. }
  1263. else
  1264. {
  1265. Result = CancelAnswer(Answers);
  1266. }
  1267. return Result;
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. TPasLibModule * __fastcall FindModule(void * Instance)
  1271. {
  1272. TPasLibModule * CurModule;
  1273. CurModule = reinterpret_cast<TPasLibModule*>(LibModuleList);
  1274. while (CurModule)
  1275. {
  1276. if (CurModule->Instance == Instance)
  1277. {
  1278. break;
  1279. }
  1280. else
  1281. {
  1282. CurModule = CurModule->Next;
  1283. }
  1284. }
  1285. return CurModule;
  1286. }
  1287. //---------------------------------------------------------------------------
  1288. AnsiString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  1289. {
  1290. TPasLibModule * MainModule = FindModule(HInstance);
  1291. assert(MainModule != NULL);
  1292. AnsiString Result;
  1293. Result.SetLength(MaxLength);
  1294. int Length = LoadString(MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  1295. Result.SetLength(Length);
  1296. return Result;
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. AnsiString __fastcall LoadStrPart(int Ident, int Part)
  1300. {
  1301. AnsiString Result;
  1302. AnsiString Str = LoadStr(Ident);
  1303. while (Part > 0)
  1304. {
  1305. Result = CutToChar(Str, '|', false);
  1306. Part--;
  1307. }
  1308. return Result;
  1309. }
  1310. //---------------------------------------------------------------------------
  1311. AnsiString __fastcall DecodeUrlChars(AnsiString S)
  1312. {
  1313. int i = 1;
  1314. while (i <= S.Length())
  1315. {
  1316. switch (S[i])
  1317. {
  1318. case '+':
  1319. S[i] = ' ';
  1320. break;
  1321. case '%':
  1322. if (i <= S.Length() - 2)
  1323. {
  1324. AnsiString C = HexToStr(S.SubString(i + 1, 2));
  1325. if (C.Length() == 1)
  1326. {
  1327. S[i] = C[1];
  1328. S.Delete(i + 1, 2);
  1329. }
  1330. }
  1331. break;
  1332. }
  1333. i++;
  1334. }
  1335. return S;
  1336. }
  1337. //---------------------------------------------------------------------------
  1338. AnsiString __fastcall DoEncodeUrl(AnsiString S, AnsiString Chars)
  1339. {
  1340. int i = 1;
  1341. while (i <= S.Length())
  1342. {
  1343. if (Chars.Pos(S[i]) > 0)
  1344. {
  1345. AnsiString H = CharToHex(S[i]);
  1346. S.Insert(H, i + 1);
  1347. S[i] = '%';
  1348. i += H.Length();
  1349. }
  1350. i++;
  1351. }
  1352. return S;
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. AnsiString __fastcall EncodeUrlChars(AnsiString S, AnsiString Ignore)
  1356. {
  1357. AnsiString Chars;
  1358. if (Ignore.Pos(' ') == 0)
  1359. {
  1360. Chars += ' ';
  1361. }
  1362. if (Ignore.Pos('/') == 0)
  1363. {
  1364. Chars += '/';
  1365. }
  1366. return DoEncodeUrl(S, Chars);
  1367. }
  1368. //---------------------------------------------------------------------------
  1369. AnsiString __fastcall NonUrlChars()
  1370. {
  1371. AnsiString S;
  1372. for (unsigned int I = 0; I <= 255; I++)
  1373. {
  1374. char C = static_cast<char>(I);
  1375. if (((C >= 'a') && (C <= 'z')) ||
  1376. ((C >= 'A') && (C <= 'Z')) ||
  1377. ((C >= '0') && (C <= '9')) ||
  1378. (C == '_') || (C == '-') || (C == '.'))
  1379. {
  1380. // noop
  1381. }
  1382. else
  1383. {
  1384. S += C;
  1385. }
  1386. }
  1387. return S;
  1388. }
  1389. //---------------------------------------------------------------------------
  1390. AnsiString __fastcall EncodeUrlString(AnsiString S)
  1391. {
  1392. return DoEncodeUrl(S, NonUrlChars());
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. void __fastcall OemToAnsi(AnsiString & Str)
  1396. {
  1397. if (!Str.IsEmpty())
  1398. {
  1399. Str.Unique();
  1400. OemToChar(Str.c_str(), Str.c_str());
  1401. }
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. void __fastcall AnsiToOem(AnsiString & Str)
  1405. {
  1406. if (!Str.IsEmpty())
  1407. {
  1408. Str.Unique();
  1409. CharToOem(Str.c_str(), Str.c_str());
  1410. }
  1411. }
  1412. //---------------------------------------------------------------------------
  1413. AnsiString __fastcall EscapeHotkey(const AnsiString & Caption)
  1414. {
  1415. return StringReplace(Caption, "&", "&&", TReplaceFlags() << rfReplaceAll);
  1416. }
  1417. //---------------------------------------------------------------------------
  1418. // duplicated in console's Main.cpp
  1419. bool __fastcall CutToken(AnsiString & Str, AnsiString & Token)
  1420. {
  1421. bool Result;
  1422. Token = "";
  1423. // inspired by Putty's sftp_getcmd() from PSFTP.C
  1424. int Index = 1;
  1425. while ((Index <= Str.Length()) &&
  1426. ((Str[Index] == ' ') || (Str[Index] == '\t')))
  1427. {
  1428. Index++;
  1429. }
  1430. if (Index <= Str.Length())
  1431. {
  1432. bool Quoting = false;
  1433. while (Index <= Str.Length())
  1434. {
  1435. if (!Quoting && ((Str[Index] == ' ') || (Str[Index] == '\t')))
  1436. {
  1437. break;
  1438. }
  1439. else if ((Str[Index] == '"') && (Index + 1 <= Str.Length()) &&
  1440. (Str[Index + 1] == '"'))
  1441. {
  1442. Index += 2;
  1443. Token += '"';
  1444. }
  1445. else if (Str[Index] == '"')
  1446. {
  1447. Index++;
  1448. Quoting = !Quoting;
  1449. }
  1450. else
  1451. {
  1452. Token += Str[Index];
  1453. Index++;
  1454. }
  1455. }
  1456. if (Index <= Str.Length())
  1457. {
  1458. Index++;
  1459. }
  1460. Str = Str.SubString(Index, Str.Length());
  1461. Result = true;
  1462. }
  1463. else
  1464. {
  1465. Result = false;
  1466. Str = "";
  1467. }
  1468. return Result;
  1469. }
  1470. //---------------------------------------------------------------------------
  1471. void __fastcall AddToList(AnsiString & List, const AnsiString & Value, char Delimiter)
  1472. {
  1473. if (!List.IsEmpty() && (List[List.Length()] != Delimiter))
  1474. {
  1475. List += Delimiter;
  1476. }
  1477. List += Value;
  1478. }
  1479. //---------------------------------------------------------------------------
  1480. bool __fastcall Is2000()
  1481. {
  1482. return (Win32MajorVersion >= 5);
  1483. }
  1484. //---------------------------------------------------------------------------
  1485. bool __fastcall IsWin7()
  1486. {
  1487. return
  1488. (Win32MajorVersion > 6) ||
  1489. ((Win32MajorVersion == 6) && (Win32MinorVersion >= 1));
  1490. }
  1491. //---------------------------------------------------------------------------
  1492. bool __fastcall IsExactly2008R2()
  1493. {
  1494. HANDLE Kernel32 = GetModuleHandle(kernel32);
  1495. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  1496. TGetProductInfo GetProductInfo =
  1497. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  1498. bool Result;
  1499. if (GetProductInfo == NULL)
  1500. {
  1501. Result = false;
  1502. }
  1503. else
  1504. {
  1505. DWORD Type;
  1506. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  1507. switch (Type)
  1508. {
  1509. case 0x0008 /*PRODUCT_DATACENTER_SERVER*/:
  1510. case 0x000C /*PRODUCT_DATACENTER_SERVER_CORE}*/:
  1511. case 0x0027 /*PRODUCT_DATACENTER_SERVER_CORE_V*/:
  1512. case 0x0025 /*PRODUCT_DATACENTER_SERVER_V*/:
  1513. case 0x000A /*PRODUCT_ENTERPRISE_SERVE*/:
  1514. case 0x000E /*PRODUCT_ENTERPRISE_SERVER_COR*/:
  1515. case 0x0029 /*PRODUCT_ENTERPRISE_SERVER_CORE_*/:
  1516. case 0x000F /*PRODUCT_ENTERPRISE_SERVER_IA6*/:
  1517. case 0x0026 /*PRODUCT_ENTERPRISE_SERVER_*/:
  1518. case 0x002A /*PRODUCT_HYPER*/:
  1519. case 0x001E /*PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMEN*/:
  1520. case 0x0020 /*PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGIN*/:
  1521. case 0x001F /*PRODUCT_MEDIUMBUSINESS_SERVER_SECURIT*/:
  1522. case 0x0018 /*PRODUCT_SERVER_FOR_SMALLBUSINES*/:
  1523. case 0x0023 /*PRODUCT_SERVER_FOR_SMALLBUSINESS_*/:
  1524. case 0x0021 /*PRODUCT_SERVER_FOUNDATIO*/:
  1525. case 0x0009 /*PRODUCT_SMALLBUSINESS_SERVE*/:
  1526. case 0x0038 /*PRODUCT_SOLUTION_EMBEDDEDSERVE*/:
  1527. case 0x0007 /*PRODUCT_STANDARD_SERVE*/:
  1528. case 0x000D /*PRODUCT_STANDARD_SERVER_COR*/:
  1529. case 0x0028 /*PRODUCT_STANDARD_SERVER_CORE_*/:
  1530. case 0x0024 /*PRODUCT_STANDARD_SERVER_*/:
  1531. case 0x0017 /*PRODUCT_STORAGE_ENTERPRISE_SERVE*/:
  1532. case 0x0014 /*PRODUCT_STORAGE_EXPRESS_SERVE*/:
  1533. case 0x0015 /*PRODUCT_STORAGE_STANDARD_SERVE*/:
  1534. case 0x0016 /*PRODUCT_STORAGE_WORKGROUP_SERVE*/:
  1535. case 0x0011 /*PRODUCT_WEB_SERVE*/:
  1536. case 0x001D /*PRODUCT_WEB_SERVER_COR*/:
  1537. Result = true;
  1538. break;
  1539. default:
  1540. Result = false;
  1541. break;
  1542. }
  1543. }
  1544. return Result;
  1545. }