Common.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "TextsCore.h"
  8. #include "Interface.h"
  9. #include <StrUtils.hpp>
  10. #include <DateUtils.hpp>
  11. #include <math.h>
  12. #include <shlobj.h>
  13. #include <limits>
  14. #include <shlwapi.h>
  15. #include <CoreMain.h>
  16. #include <openssl/pkcs12.h>
  17. #include <openssl/pem.h>
  18. #include <openssl/err.h>
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. const wchar_t * DSTModeNames = L"Win;Unix;Keep";
  23. //---------------------------------------------------------------------------
  24. //---------------------------------------------------------------------------
  25. const wchar_t EngShortMonthNames[12][4] =
  26. {L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
  27. L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"};
  28. const char Bom[3] = "\xEF\xBB\xBF";
  29. const wchar_t TokenPrefix = L'%';
  30. const wchar_t NoReplacement = wchar_t(false);
  31. const wchar_t TokenReplacement = wchar_t(true);
  32. const UnicodeString LocalInvalidChars = L"/\\:*?\"<>|";
  33. const UnicodeString PasswordMask = L"***";
  34. //---------------------------------------------------------------------------
  35. UnicodeString ReplaceChar(UnicodeString Str, wchar_t A, wchar_t B)
  36. {
  37. for (Integer Index = 0; Index < Str.Length(); Index++)
  38. if (Str[Index+1] == A) Str[Index+1] = B;
  39. return Str;
  40. }
  41. //---------------------------------------------------------------------------
  42. UnicodeString DeleteChar(UnicodeString Str, wchar_t C)
  43. {
  44. int P;
  45. while ((P = Str.Pos(C)) > 0)
  46. {
  47. Str.Delete(P, 1);
  48. }
  49. return Str;
  50. }
  51. //---------------------------------------------------------------------------
  52. int PosFrom(const UnicodeString & SubStr, const UnicodeString & Str, int Index)
  53. {
  54. UnicodeString S = Str.SubString(Index, Str.Length() - Index + 1);
  55. int Result = S.Pos(SubStr);
  56. if (Result > 0)
  57. {
  58. Result += Index - 1;
  59. }
  60. return Result;
  61. }
  62. //---------------------------------------------------------------------------
  63. template<typename T>
  64. void DoPackStr(T & Str)
  65. {
  66. // Following will free unnecessary bytes
  67. Str = Str.c_str();
  68. }
  69. //---------------------------------------------------------------------------
  70. void PackStr(UnicodeString & Str)
  71. {
  72. DoPackStr(Str);
  73. }
  74. //---------------------------------------------------------------------------
  75. void PackStr(RawByteString & Str)
  76. {
  77. DoPackStr(Str);
  78. }
  79. //---------------------------------------------------------------------------
  80. void PackStr(AnsiString & Str)
  81. {
  82. DoPackStr(Str);
  83. }
  84. //---------------------------------------------------------------------------
  85. template<typename T>
  86. void __fastcall DoShred(T & Str)
  87. {
  88. if (!Str.IsEmpty())
  89. {
  90. Str.Unique();
  91. memset(Str.c_str(), 0, Str.Length() * sizeof(*Str.c_str()));
  92. Str = L"";
  93. }
  94. }
  95. //---------------------------------------------------------------------------
  96. void __fastcall Shred(UnicodeString & Str)
  97. {
  98. DoShred(Str);
  99. }
  100. //---------------------------------------------------------------------------
  101. void __fastcall Shred(UTF8String & Str)
  102. {
  103. DoShred(Str);
  104. }
  105. //---------------------------------------------------------------------------
  106. void __fastcall Shred(AnsiString & Str)
  107. {
  108. DoShred(Str);
  109. }
  110. //---------------------------------------------------------------------------
  111. UnicodeString AnsiToString(const RawByteString & S)
  112. {
  113. return UnicodeString(AnsiString(S));
  114. }
  115. //---------------------------------------------------------------------------
  116. UnicodeString AnsiToString(const char * S, size_t Len)
  117. {
  118. return UnicodeString(AnsiString(S, Len));
  119. }
  120. //---------------------------------------------------------------------------
  121. UnicodeString MakeValidFileName(UnicodeString FileName)
  122. {
  123. UnicodeString IllegalChars = L":;,=+<>|\"[] \\/?*";
  124. for (int Index = 0; Index < IllegalChars.Length(); Index++)
  125. {
  126. FileName = ReplaceChar(FileName, IllegalChars[Index+1], L'-');
  127. }
  128. return FileName;
  129. }
  130. //---------------------------------------------------------------------------
  131. UnicodeString RootKeyToStr(HKEY RootKey)
  132. {
  133. if (RootKey == HKEY_USERS) return L"HKU";
  134. else
  135. if (RootKey == HKEY_LOCAL_MACHINE) return L"HKLM";
  136. else
  137. if (RootKey == HKEY_CURRENT_USER) return L"HKCU";
  138. else
  139. if (RootKey == HKEY_CLASSES_ROOT) return L"HKCR";
  140. else
  141. if (RootKey == HKEY_CURRENT_CONFIG) return L"HKCC";
  142. else
  143. if (RootKey == HKEY_DYN_DATA) return L"HKDD";
  144. else
  145. { Abort(); return L""; };
  146. }
  147. //---------------------------------------------------------------------------
  148. UnicodeString BooleanToEngStr(bool B)
  149. {
  150. if (B)
  151. {
  152. return L"Yes";
  153. }
  154. else
  155. {
  156. return L"No";
  157. }
  158. }
  159. //---------------------------------------------------------------------------
  160. UnicodeString BooleanToStr(bool B)
  161. {
  162. if (B)
  163. {
  164. return LoadStr(YES_STR);
  165. }
  166. else
  167. {
  168. return LoadStr(NO_STR);
  169. }
  170. }
  171. //---------------------------------------------------------------------------
  172. UnicodeString DefaultStr(const UnicodeString & Str, const UnicodeString & Default)
  173. {
  174. if (!Str.IsEmpty())
  175. {
  176. return Str;
  177. }
  178. else
  179. {
  180. return Default;
  181. }
  182. }
  183. //---------------------------------------------------------------------------
  184. UnicodeString CutToChar(UnicodeString &Str, wchar_t Ch, bool Trim)
  185. {
  186. Integer P = Str.Pos(Ch);
  187. UnicodeString Result;
  188. if (P)
  189. {
  190. Result = Str.SubString(1, P-1);
  191. Str.Delete(1, P);
  192. }
  193. else
  194. {
  195. Result = Str;
  196. Str = L"";
  197. }
  198. if (Trim)
  199. {
  200. Result = Result.TrimRight();
  201. Str = Str.TrimLeft();
  202. }
  203. return Result;
  204. }
  205. //---------------------------------------------------------------------------
  206. UnicodeString CopyToChars(const UnicodeString & Str, int & From, UnicodeString Chs, bool Trim,
  207. wchar_t * Delimiter, bool DoubleDelimiterEscapes)
  208. {
  209. UnicodeString Result;
  210. int P;
  211. for (P = From; P <= Str.Length(); P++)
  212. {
  213. if (IsDelimiter(Chs, Str, P))
  214. {
  215. if (DoubleDelimiterEscapes &&
  216. (P < Str.Length()) &&
  217. IsDelimiter(Chs, Str, P + 1))
  218. {
  219. Result += Str[P];
  220. P++;
  221. }
  222. else
  223. {
  224. break;
  225. }
  226. }
  227. else
  228. {
  229. Result += Str[P];
  230. }
  231. }
  232. if (P <= Str.Length())
  233. {
  234. if (Delimiter != NULL)
  235. {
  236. *Delimiter = Str[P];
  237. }
  238. }
  239. else
  240. {
  241. if (Delimiter != NULL)
  242. {
  243. *Delimiter = L'\0';
  244. }
  245. }
  246. // even if we reached the end, return index, as if there were the delimiter,
  247. // so caller can easily find index of the end of the piece by subtracting
  248. // 2 from From (as long as he did not asked for trimming)
  249. From = P+1;
  250. if (Trim)
  251. {
  252. Result = Result.TrimRight();
  253. while ((From <= Str.Length()) && (Str[From] == L' '))
  254. {
  255. From++;
  256. }
  257. }
  258. return Result;
  259. }
  260. //---------------------------------------------------------------------------
  261. UnicodeString CopyToChar(const UnicodeString & Str, wchar_t Ch, bool Trim)
  262. {
  263. int From = 1;
  264. return CopyToChars(Str, From, UnicodeString(Ch), Trim);
  265. }
  266. //---------------------------------------------------------------------------
  267. UnicodeString DelimitStr(UnicodeString Str, UnicodeString Chars)
  268. {
  269. for (int i = 1; i <= Str.Length(); i++)
  270. {
  271. if (Str.IsDelimiter(Chars, i))
  272. {
  273. Str.Insert(L"\\", i);
  274. i++;
  275. }
  276. }
  277. return Str;
  278. }
  279. //---------------------------------------------------------------------------
  280. UnicodeString ShellDelimitStr(UnicodeString Str, wchar_t Quote)
  281. {
  282. UnicodeString Chars = L"$\\";
  283. if (Quote == L'"')
  284. {
  285. Chars += L"`\"";
  286. }
  287. return DelimitStr(Str, Chars);
  288. }
  289. //---------------------------------------------------------------------------
  290. UnicodeString ExceptionLogString(Exception *E)
  291. {
  292. DebugAssert(E);
  293. if (E->InheritsFrom(__classid(Exception)))
  294. {
  295. UnicodeString Msg;
  296. Msg = FORMAT(L"(%s) %s", (E->ClassName(), E->Message));
  297. if (E->InheritsFrom(__classid(ExtException)))
  298. {
  299. TStrings * MoreMessages = ((ExtException*)E)->MoreMessages;
  300. if (MoreMessages)
  301. {
  302. Msg += L"\n" +
  303. ReplaceStr(MoreMessages->Text, L"\r", L"");
  304. }
  305. }
  306. return Msg;
  307. }
  308. else
  309. {
  310. wchar_t Buffer[1024];
  311. ExceptionErrorMessage(ExceptObject(), ExceptAddr(), Buffer, LENOF(Buffer));
  312. return UnicodeString(Buffer);
  313. }
  314. }
  315. //---------------------------------------------------------------------------
  316. UnicodeString __fastcall MainInstructions(const UnicodeString & S)
  317. {
  318. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  319. return MainMsgTag + S + MainMsgTag;
  320. }
  321. //---------------------------------------------------------------------------
  322. bool __fastcall HasParagraphs(const UnicodeString & S)
  323. {
  324. return (S.Pos(L"\n\n") > 0);
  325. }
  326. //---------------------------------------------------------------------------
  327. UnicodeString __fastcall MainInstructionsFirstParagraph(const UnicodeString & S)
  328. {
  329. // WORKAROUND, we consider it bad practice, the highlighting should better
  330. // be localized (but maybe we change our mind later)
  331. UnicodeString Result;
  332. int Pos = S.Pos(L"\n\n");
  333. // we would not be calling this on single paragraph message
  334. if (DebugAlwaysTrue(Pos > 0))
  335. {
  336. Result =
  337. MainInstructions(S.SubString(1, Pos - 1)) +
  338. S.SubString(Pos, S.Length() - Pos + 1);
  339. }
  340. else
  341. {
  342. Result = MainInstructions(S);
  343. }
  344. return Result;
  345. }
  346. //---------------------------------------------------------------------------
  347. bool ExtractMainInstructions(UnicodeString & S, UnicodeString & MainInstructions)
  348. {
  349. bool Result = false;
  350. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  351. if (StartsStr(MainMsgTag, S))
  352. {
  353. int EndTagPos =
  354. S.SubString(MainMsgTag.Length() + 1, S.Length() - MainMsgTag.Length()).Pos(MainMsgTag);
  355. if (EndTagPos > 0)
  356. {
  357. MainInstructions = S.SubString(MainMsgTag.Length() + 1, EndTagPos - 1);
  358. S.Delete(1, EndTagPos + (2 * MainMsgTag.Length()) - 1);
  359. Result = true;
  360. }
  361. }
  362. DebugAssert(MainInstructions.Pos(MainMsgTag) == 0);
  363. DebugAssert(S.Pos(MainMsgTag) == 0);
  364. return Result;
  365. }
  366. //---------------------------------------------------------------------------
  367. static int FindInteractiveMsgStart(const UnicodeString & S)
  368. {
  369. int Result = 0;
  370. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  371. if (EndsStr(InteractiveMsgTag, S) &&
  372. (S.Length() >= 2 * InteractiveMsgTag.Length()))
  373. {
  374. Result = S.Length() - 2 * InteractiveMsgTag.Length() + 1;
  375. while ((Result > 0) && (S.SubString(Result, InteractiveMsgTag.Length()) != InteractiveMsgTag))
  376. {
  377. Result--;
  378. }
  379. }
  380. return Result;
  381. }
  382. //---------------------------------------------------------------------------
  383. UnicodeString RemoveMainInstructionsTag(UnicodeString S)
  384. {
  385. UnicodeString MainInstruction;
  386. if (ExtractMainInstructions(S, MainInstruction))
  387. {
  388. S = MainInstruction + S;
  389. }
  390. return S;
  391. }
  392. //---------------------------------------------------------------------------
  393. UnicodeString UnformatMessage(UnicodeString S)
  394. {
  395. S = RemoveMainInstructionsTag(S);
  396. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  397. if (InteractiveMsgStart > 0)
  398. {
  399. S = S.SubString(1, InteractiveMsgStart - 1);
  400. }
  401. return S;
  402. }
  403. //---------------------------------------------------------------------------
  404. UnicodeString RemoveInteractiveMsgTag(UnicodeString S)
  405. {
  406. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  407. if (InteractiveMsgStart > 0)
  408. {
  409. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  410. S.Delete(InteractiveMsgStart, InteractiveMsgTag.Length());
  411. S.Delete(S.Length() - InteractiveMsgTag.Length() + 1, InteractiveMsgTag.Length());
  412. }
  413. return S;
  414. }
  415. //---------------------------------------------------------------------------
  416. UnicodeString RemoveEmptyLines(const UnicodeString & S)
  417. {
  418. return
  419. ReplaceStr(
  420. ReplaceStr(S.TrimRight(), L"\n\n", L"\n"),
  421. L"\n \n", L"\n");
  422. }
  423. //---------------------------------------------------------------------------
  424. bool IsNumber(const UnicodeString Str)
  425. {
  426. int Value;
  427. return TryStrToInt(Str, Value);
  428. }
  429. //---------------------------------------------------------------------------
  430. UnicodeString __fastcall SystemTemporaryDirectory()
  431. {
  432. UnicodeString TempDir;
  433. TempDir.SetLength(MAX_PATH);
  434. TempDir.SetLength(GetTempPath(MAX_PATH, TempDir.c_str()));
  435. return TempDir;
  436. }
  437. //---------------------------------------------------------------------------
  438. UnicodeString __fastcall GetShellFolderPath(int CSIdl)
  439. {
  440. UnicodeString Result;
  441. wchar_t Path[2 * MAX_PATH + 10] = L"\0";
  442. if (SUCCEEDED(SHGetFolderPath(NULL, CSIdl, NULL, SHGFP_TYPE_CURRENT, Path)))
  443. {
  444. Result = Path;
  445. }
  446. return Result;
  447. }
  448. //---------------------------------------------------------------------------
  449. // Particularly needed when using file name selected by TFilenameEdit,
  450. // as it wraps a path to double-quotes, when there is a space in the path.
  451. UnicodeString __fastcall StripPathQuotes(const UnicodeString Path)
  452. {
  453. if ((Path.Length() >= 2) &&
  454. (Path[1] == L'\"') && (Path[Path.Length()] == L'\"'))
  455. {
  456. return Path.SubString(2, Path.Length() - 2);
  457. }
  458. else
  459. {
  460. return Path;
  461. }
  462. }
  463. //---------------------------------------------------------------------------
  464. UnicodeString __fastcall AddQuotes(UnicodeString Str)
  465. {
  466. if (Str.Pos(L" ") > 0)
  467. {
  468. Str = L"\"" + Str + L"\"";
  469. }
  470. return Str;
  471. }
  472. //---------------------------------------------------------------------------
  473. UnicodeString __fastcall AddPathQuotes(UnicodeString Path)
  474. {
  475. Path = StripPathQuotes(Path);
  476. return AddQuotes(Path);
  477. }
  478. //---------------------------------------------------------------------------
  479. static wchar_t * __fastcall ReplaceChar(
  480. UnicodeString & FileName, wchar_t * InvalidChar, wchar_t InvalidCharsReplacement)
  481. {
  482. int Index = InvalidChar - FileName.c_str() + 1;
  483. if (InvalidCharsReplacement == TokenReplacement)
  484. {
  485. // currently we do not support unicode chars replacement
  486. if (FileName[Index] > 0xFF)
  487. {
  488. EXCEPTION;
  489. }
  490. FileName.Insert(ByteToHex(static_cast<unsigned char>(FileName[Index])), Index + 1);
  491. FileName[Index] = TokenPrefix;
  492. InvalidChar = FileName.c_str() + Index + 2;
  493. }
  494. else
  495. {
  496. FileName[Index] = InvalidCharsReplacement;
  497. InvalidChar = FileName.c_str() + Index;
  498. }
  499. return InvalidChar;
  500. }
  501. //---------------------------------------------------------------------------
  502. UnicodeString __fastcall ValidLocalFileName(UnicodeString FileName)
  503. {
  504. return ValidLocalFileName(FileName, L'_', L"", LocalInvalidChars);
  505. }
  506. //---------------------------------------------------------------------------
  507. UnicodeString __fastcall ValidLocalFileName(
  508. UnicodeString FileName, wchar_t InvalidCharsReplacement,
  509. const UnicodeString & TokenizibleChars, const UnicodeString & LocalInvalidChars)
  510. {
  511. if (InvalidCharsReplacement != NoReplacement)
  512. {
  513. bool ATokenReplacement = (InvalidCharsReplacement == TokenReplacement);
  514. const wchar_t * Chars =
  515. (ATokenReplacement ? TokenizibleChars : LocalInvalidChars).c_str();
  516. wchar_t * InvalidChar = FileName.c_str();
  517. while ((InvalidChar = wcspbrk(InvalidChar, Chars)) != NULL)
  518. {
  519. int Pos = (InvalidChar - FileName.c_str() + 1);
  520. wchar_t Char;
  521. if (ATokenReplacement &&
  522. (*InvalidChar == TokenPrefix) &&
  523. (((FileName.Length() - Pos) <= 1) ||
  524. (((Char = static_cast<wchar_t>(HexToByte(FileName.SubString(Pos + 1, 2)))) == L'\0') ||
  525. (TokenizibleChars.Pos(Char) == 0))))
  526. {
  527. InvalidChar++;
  528. }
  529. else
  530. {
  531. InvalidChar = ReplaceChar(FileName, InvalidChar, InvalidCharsReplacement);
  532. }
  533. }
  534. // Windows trim trailing space or dot, hence we must encode it to preserve it
  535. if (!FileName.IsEmpty() &&
  536. ((FileName[FileName.Length()] == L' ') ||
  537. (FileName[FileName.Length()] == L'.')))
  538. {
  539. ReplaceChar(FileName, FileName.c_str() + FileName.Length() - 1, InvalidCharsReplacement);
  540. }
  541. if (IsReservedName(FileName))
  542. {
  543. int P = FileName.Pos(".");
  544. if (P == 0)
  545. {
  546. P = FileName.Length() + 1;
  547. }
  548. FileName.Insert(L"%00", P);
  549. }
  550. }
  551. return FileName;
  552. }
  553. //---------------------------------------------------------------------------
  554. void __fastcall SplitCommand(UnicodeString Command, UnicodeString &Program,
  555. UnicodeString & Params, UnicodeString & Dir)
  556. {
  557. Command = Command.Trim();
  558. Params = L"";
  559. Dir = L"";
  560. if (!Command.IsEmpty() && (Command[1] == L'\"'))
  561. {
  562. Command.Delete(1, 1);
  563. int P = Command.Pos(L'"');
  564. if (P)
  565. {
  566. Program = Command.SubString(1, P-1).Trim();
  567. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  568. }
  569. else
  570. {
  571. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, (L"\"" + Command)));
  572. }
  573. }
  574. else
  575. {
  576. int P = Command.Pos(L" ");
  577. if (P)
  578. {
  579. Program = Command.SubString(1, P).Trim();
  580. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  581. }
  582. else
  583. {
  584. Program = Command;
  585. }
  586. }
  587. int B = Program.LastDelimiter(L"\\/");
  588. if (B)
  589. {
  590. Dir = Program.SubString(1, B).Trim();
  591. }
  592. }
  593. //---------------------------------------------------------------------------
  594. UnicodeString __fastcall ExtractProgram(UnicodeString Command)
  595. {
  596. UnicodeString Program;
  597. UnicodeString Params;
  598. UnicodeString Dir;
  599. SplitCommand(Command, Program, Params, Dir);
  600. return Program;
  601. }
  602. //---------------------------------------------------------------------------
  603. UnicodeString __fastcall ExtractProgramName(UnicodeString Command)
  604. {
  605. UnicodeString Name = ExtractFileName(ExtractProgram(Command));
  606. int Dot = Name.LastDelimiter(L".");
  607. if (Dot > 0)
  608. {
  609. Name = Name.SubString(1, Dot - 1);
  610. }
  611. return Name;
  612. }
  613. //---------------------------------------------------------------------------
  614. UnicodeString __fastcall FormatCommand(UnicodeString Program, UnicodeString Params)
  615. {
  616. Program = Program.Trim();
  617. Params = Params.Trim();
  618. if (!Params.IsEmpty()) Params = L" " + Params;
  619. Program = AddQuotes(Program);
  620. return Program + Params;
  621. }
  622. //---------------------------------------------------------------------------
  623. const wchar_t ShellCommandFileNamePattern[] = L"!.!";
  624. //---------------------------------------------------------------------------
  625. void __fastcall ReformatFileNameCommand(UnicodeString & Command)
  626. {
  627. if (!Command.IsEmpty())
  628. {
  629. UnicodeString Program, Params, Dir;
  630. SplitCommand(Command, Program, Params, Dir);
  631. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  632. {
  633. Params = Params + (Params.IsEmpty() ? L"" : L" ") + ShellCommandFileNamePattern;
  634. }
  635. Command = FormatCommand(Program, Params);
  636. }
  637. }
  638. //---------------------------------------------------------------------------
  639. UnicodeString __fastcall ExpandFileNameCommand(const UnicodeString Command,
  640. const UnicodeString FileName)
  641. {
  642. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  643. AddPathQuotes(FileName));
  644. }
  645. //---------------------------------------------------------------------------
  646. UnicodeString __fastcall EscapeParam(const UnicodeString & Param)
  647. {
  648. // Make sure this won't break RTF syntax
  649. return ReplaceStr(Param, L"\"", L"\"\"");
  650. }
  651. //---------------------------------------------------------------------------
  652. UnicodeString __fastcall EscapePuttyCommandParam(UnicodeString Param)
  653. {
  654. bool Space = false;
  655. for (int i = 1; i <= Param.Length(); i++)
  656. {
  657. switch (Param[i])
  658. {
  659. case L'"':
  660. Param.Insert(L"\\", i);
  661. i++;
  662. break;
  663. case L' ':
  664. Space = true;
  665. break;
  666. case L'\\':
  667. int i2 = i;
  668. while ((i2 <= Param.Length()) && (Param[i2] == L'\\'))
  669. {
  670. i2++;
  671. }
  672. if ((i2 <= Param.Length()) && (Param[i2] == L'"'))
  673. {
  674. while (Param[i] == L'\\')
  675. {
  676. Param.Insert(L"\\", i);
  677. i += 2;
  678. }
  679. i--;
  680. }
  681. break;
  682. }
  683. }
  684. if (Space)
  685. {
  686. Param = L"\"" + Param + L'"';
  687. }
  688. return Param;
  689. }
  690. //---------------------------------------------------------------------------
  691. UnicodeString __fastcall ExpandEnvironmentVariables(const UnicodeString & Str)
  692. {
  693. UnicodeString Buf;
  694. unsigned int Size = 1024;
  695. Buf.SetLength(Size);
  696. Buf.Unique();
  697. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  698. if (Len > Size)
  699. {
  700. Buf.SetLength(Len);
  701. Buf.Unique();
  702. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  703. }
  704. PackStr(Buf);
  705. return Buf;
  706. }
  707. //---------------------------------------------------------------------------
  708. bool __fastcall CompareFileName(const UnicodeString & Path1, const UnicodeString & Path2)
  709. {
  710. UnicodeString ShortPath1 = ExtractShortPathName(Path1);
  711. UnicodeString ShortPath2 = ExtractShortPathName(Path2);
  712. bool Result;
  713. // ExtractShortPathName returns empty string if file does not exist
  714. if (ShortPath1.IsEmpty() || ShortPath2.IsEmpty())
  715. {
  716. Result = AnsiSameText(Path1, Path2);
  717. }
  718. else
  719. {
  720. Result = AnsiSameText(ShortPath1, ShortPath2);
  721. }
  722. return Result;
  723. }
  724. //---------------------------------------------------------------------------
  725. bool __fastcall ComparePaths(const UnicodeString & Path1, const UnicodeString & Path2)
  726. {
  727. // TODO: ExpandUNCFileName
  728. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  729. }
  730. //---------------------------------------------------------------------------
  731. int __fastcall CompareLogicalText(const UnicodeString & S1, const UnicodeString & S2)
  732. {
  733. return StrCmpLogicalW(S1.c_str(), S2.c_str());
  734. }
  735. //---------------------------------------------------------------------------
  736. bool __fastcall IsReservedName(UnicodeString FileName)
  737. {
  738. int P = FileName.Pos(L".");
  739. int Len = (P > 0) ? P - 1 : FileName.Length();
  740. if ((Len == 3) || (Len == 4))
  741. {
  742. if (P > 0)
  743. {
  744. FileName.SetLength(P - 1);
  745. }
  746. static UnicodeString Reserved[] = {
  747. L"CON", L"PRN", L"AUX", L"NUL",
  748. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  749. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  750. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  751. {
  752. if (SameText(FileName, Reserved[Index]))
  753. {
  754. return true;
  755. }
  756. }
  757. }
  758. return false;
  759. }
  760. //---------------------------------------------------------------------------
  761. // ApiPath support functions
  762. // Inspired by
  763. // http://stackoverflow.com/questions/18580945/need-clarification-for-converting-paths-into-long-unicode-paths-or-the-ones-star
  764. // This can be reimplemented using PathCchCanonicalizeEx on Windows 8 and later
  765. enum PATH_PREFIX_TYPE
  766. {
  767. PPT_UNKNOWN,
  768. PPT_ABSOLUTE, //Found absolute path that is none of the other types
  769. PPT_UNC, //Found \\server\share\ prefix
  770. PPT_LONG_UNICODE, //Found \\?\ prefix
  771. PPT_LONG_UNICODE_UNC, //Found \\?\UNC\ prefix
  772. };
  773. //---------------------------------------------------------------------------
  774. static int __fastcall PathRootLength(UnicodeString Path)
  775. {
  776. // Correction for PathSkipRoot API
  777. // Replace all /'s with \'s because PathSkipRoot can't handle /'s
  778. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  779. // Now call the API
  780. LPCTSTR Buffer = PathSkipRoot(Result.c_str());
  781. return (Buffer != NULL) ? (Buffer - Result.c_str()) : -1;
  782. }
  783. //---------------------------------------------------------------------------
  784. static bool __fastcall PathIsRelative_CorrectedForMicrosoftStupidity(UnicodeString Path)
  785. {
  786. // Correction for PathIsRelative API
  787. // Replace all /'s with \'s because PathIsRelative can't handle /'s
  788. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  789. //Now call the API
  790. return PathIsRelative(Result.c_str());
  791. }
  792. //---------------------------------------------------------------------------
  793. static int __fastcall GetOffsetAfterPathRoot(UnicodeString Path, PATH_PREFIX_TYPE & PrefixType)
  794. {
  795. // Checks if 'pPath' begins with the drive, share, prefix, etc
  796. // EXAMPLES:
  797. // Path Return: Points at: PrefixType:
  798. // Relative\Folder\File.txt 0 Relative\Folder\File.txt PPT_UNKNOWN
  799. // \RelativeToRoot\Folder 1 RelativeToRoot\Folder PPT_ABSOLUTE
  800. // C:\Windows\Folder 3 Windows\Folder PPT_ABSOLUTE
  801. // \\server\share\Desktop 15 Desktop PPT_UNC
  802. // \\?\C:\Windows\Folder 7 Windows\Folder PPT_LONG_UNICODE
  803. // \\?\UNC\server\share\Desktop 21 Desktop PPT_LONG_UNICODE_UNC
  804. // RETURN:
  805. // = Index in 'pPath' after the root, or
  806. // = 0 if no root was found
  807. int Result = 0;
  808. PrefixType = PPT_UNKNOWN;
  809. if (!Path.IsEmpty())
  810. {
  811. int Len = Path.Length();
  812. bool WinXPOnly = !IsWinVista();
  813. // The PathSkipRoot() API doesn't work correctly on Windows XP
  814. if (!WinXPOnly)
  815. {
  816. // Works since Vista and up, but still needs correction :)
  817. int RootLength = PathRootLength(Path);
  818. if (RootLength >= 0)
  819. {
  820. Result = RootLength + 1;
  821. }
  822. }
  823. // Now determine the type of prefix
  824. int IndCheckUNC = -1;
  825. if ((Len >= 8) &&
  826. (Path[1] == L'\\' || Path[1] == L'/') &&
  827. (Path[2] == L'\\' || Path[2] == L'/') &&
  828. (Path[3] == L'?') &&
  829. (Path[4] == L'\\' || Path[4] == L'/') &&
  830. (Path[5] == L'U' || Path[5] == L'u') &&
  831. (Path[6] == L'N' || Path[6] == L'n') &&
  832. (Path[7] == L'C' || Path[7] == L'c') &&
  833. (Path[8] == L'\\' || Path[8] == L'/'))
  834. {
  835. // Found \\?\UNC\ prefix
  836. PrefixType = PPT_LONG_UNICODE_UNC;
  837. if (WinXPOnly)
  838. {
  839. //For older OS
  840. Result += 8;
  841. }
  842. //Check for UNC share later
  843. IndCheckUNC = 8;
  844. }
  845. else if ((Len >= 4) &&
  846. (Path[1] == L'\\' || Path[1] == L'/') &&
  847. (Path[2] == L'\\' || Path[2] == L'/') &&
  848. (Path[3] == L'?') &&
  849. (Path[4] == L'\\' || Path[4] == L'/'))
  850. {
  851. // Found \\?\ prefix
  852. PrefixType = PPT_LONG_UNICODE;
  853. if (WinXPOnly)
  854. {
  855. //For older OS
  856. Result += 4;
  857. }
  858. }
  859. else if ((Len >= 2) &&
  860. (Path[1] == L'\\' || Path[1] == L'/') &&
  861. (Path[2] == L'\\' || Path[2] == L'/'))
  862. {
  863. // Check for UNC share later
  864. IndCheckUNC = 2;
  865. }
  866. if (IndCheckUNC >= 0)
  867. {
  868. // Check for UNC, i.e. \\server\share\ part
  869. int Index = IndCheckUNC;
  870. for (int SkipSlashes = 2; SkipSlashes > 0; SkipSlashes--)
  871. {
  872. for(; Index <= Len; Index++)
  873. {
  874. TCHAR z = Path[Index];
  875. if ((z == L'\\') || (z == L'/') || (Index >= Len))
  876. {
  877. Index++;
  878. if (SkipSlashes == 1)
  879. {
  880. if (PrefixType == PPT_UNKNOWN)
  881. {
  882. PrefixType = PPT_UNC;
  883. }
  884. if (WinXPOnly)
  885. {
  886. //For older OS
  887. Result = Index;
  888. }
  889. }
  890. break;
  891. }
  892. }
  893. }
  894. }
  895. if (WinXPOnly)
  896. {
  897. // Only if we didn't determine any other type
  898. if (PrefixType == PPT_UNKNOWN)
  899. {
  900. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path.SubString(Result, Path.Length() - Result + 1)))
  901. {
  902. PrefixType = PPT_ABSOLUTE;
  903. }
  904. }
  905. // For older OS only
  906. int RootLength = PathRootLength(Path.SubString(Result, Path.Length() - Result + 1));
  907. if (RootLength >= 0)
  908. {
  909. Result = RootLength + 1;
  910. }
  911. }
  912. else
  913. {
  914. // Only if we didn't determine any other type
  915. if (PrefixType == PPT_UNKNOWN)
  916. {
  917. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path))
  918. {
  919. PrefixType = PPT_ABSOLUTE;
  920. }
  921. }
  922. }
  923. }
  924. return Result;
  925. }
  926. //---------------------------------------------------------------------------
  927. UnicodeString __fastcall MakeUnicodeLargePath(UnicodeString Path)
  928. {
  929. // Convert path from 'into a larger Unicode path, that allows up to 32,767 character length
  930. UnicodeString Result;
  931. if (!Path.IsEmpty())
  932. {
  933. // Determine the type of the existing prefix
  934. PATH_PREFIX_TYPE PrefixType;
  935. GetOffsetAfterPathRoot(Path, PrefixType);
  936. // Assume path to be without change
  937. Result = Path;
  938. switch (PrefixType)
  939. {
  940. case PPT_ABSOLUTE:
  941. {
  942. // First we need to check if its an absolute path relative to the root
  943. bool AddPrefix = true;
  944. if ((Path.Length() >= 1) &&
  945. ((Path[1] == L'\\') || (Path[1] == L'/')))
  946. {
  947. AddPrefix = FALSE;
  948. // Get current root path
  949. UnicodeString CurrentDir = GetCurrentDir();
  950. PATH_PREFIX_TYPE PrefixType2; // unused
  951. int Following = GetOffsetAfterPathRoot(CurrentDir, PrefixType2);
  952. if (Following > 0)
  953. {
  954. AddPrefix = true;
  955. Result = CurrentDir.SubString(1, Following - 1) + Result.SubString(2, Result.Length() - 1);
  956. }
  957. }
  958. if (AddPrefix)
  959. {
  960. // Add \\?\ prefix
  961. Result = L"\\\\?\\" + Result;
  962. }
  963. }
  964. break;
  965. case PPT_UNC:
  966. // First we need to remove the opening slashes for UNC share
  967. if ((Result.Length() >= 2) &&
  968. ((Result[1] == L'\\') || (Result[1] == L'/')) &&
  969. ((Result[2] == L'\\') || (Result[2] == L'/')))
  970. {
  971. Result = Result.SubString(3, Result.Length() - 2);
  972. }
  973. // Add \\?\UNC\ prefix
  974. Result = L"\\\\?\\UNC\\" + Result;
  975. break;
  976. case PPT_LONG_UNICODE:
  977. case PPT_LONG_UNICODE_UNC:
  978. // nothing to do
  979. break;
  980. }
  981. }
  982. return Result;
  983. }
  984. //---------------------------------------------------------------------------
  985. UnicodeString __fastcall ApiPath(UnicodeString Path)
  986. {
  987. if (Path.Length() >= MAX_PATH)
  988. {
  989. if (Configuration != NULL)
  990. {
  991. Configuration->Usage->Inc(L"LongPath");
  992. }
  993. Path = MakeUnicodeLargePath(Path);
  994. }
  995. return Path;
  996. }
  997. //---------------------------------------------------------------------------
  998. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  999. {
  1000. bool Displayable = true;
  1001. int Index = 1;
  1002. while ((Index <= Str.Length()) && Displayable)
  1003. {
  1004. if (((Str[Index] < '\x20') || (static_cast<unsigned char>(Str[Index]) >= static_cast<unsigned char>('\x80'))) &&
  1005. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  1006. {
  1007. Displayable = false;
  1008. }
  1009. Index++;
  1010. }
  1011. UnicodeString Result;
  1012. if (Displayable)
  1013. {
  1014. Result = L"\"";
  1015. for (int Index = 1; Index <= Str.Length(); Index++)
  1016. {
  1017. switch (Str[Index])
  1018. {
  1019. case '\n':
  1020. Result += L"\\n";
  1021. break;
  1022. case '\r':
  1023. Result += L"\\r";
  1024. break;
  1025. case '\t':
  1026. Result += L"\\t";
  1027. break;
  1028. case '\b':
  1029. Result += L"\\b";
  1030. break;
  1031. case '\\':
  1032. Result += L"\\\\";
  1033. break;
  1034. case '"':
  1035. Result += L"\\\"";
  1036. break;
  1037. default:
  1038. Result += wchar_t(Str[Index]);
  1039. break;
  1040. }
  1041. }
  1042. Result += L"\"";
  1043. }
  1044. else
  1045. {
  1046. Result = L"0x" + BytesToHex(Str);
  1047. }
  1048. return Result;
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  1052. {
  1053. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  1054. static wchar_t LowerDigits[] = L"0123456789abcdef";
  1055. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  1056. UnicodeString Result;
  1057. Result.SetLength(2);
  1058. Result[1] = Digits[(B & 0xF0) >> 4];
  1059. Result[2] = Digits[(B & 0x0F) >> 0];
  1060. return Result;
  1061. }
  1062. //---------------------------------------------------------------------------
  1063. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  1064. {
  1065. UnicodeString Result;
  1066. for (size_t i = 0; i < Length; i++)
  1067. {
  1068. Result += ByteToHex(B[i], UpperCase);
  1069. if ((Separator != L'\0') && (i < Length - 1))
  1070. {
  1071. Result += Separator;
  1072. }
  1073. }
  1074. return Result;
  1075. }
  1076. //---------------------------------------------------------------------------
  1077. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  1078. {
  1079. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  1083. {
  1084. return BytesToHex(reinterpret_cast<const unsigned char *>(&Ch), sizeof(Ch), UpperCase);
  1085. }
  1086. //---------------------------------------------------------------------------
  1087. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  1088. {
  1089. static UnicodeString Digits = L"0123456789ABCDEF";
  1090. RawByteString Result;
  1091. int L, P1, P2;
  1092. L = Hex.Length();
  1093. if (L % 2 == 0)
  1094. {
  1095. for (int i = 1; i <= Hex.Length(); i += 2)
  1096. {
  1097. P1 = Digits.Pos((wchar_t)toupper(Hex[i]));
  1098. P2 = Digits.Pos((wchar_t)toupper(Hex[i + 1]));
  1099. if (P1 <= 0 || P2 <= 0)
  1100. {
  1101. Result = L"";
  1102. break;
  1103. }
  1104. else
  1105. {
  1106. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  1107. }
  1108. }
  1109. }
  1110. return Result;
  1111. }
  1112. //---------------------------------------------------------------------------
  1113. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  1114. {
  1115. static UnicodeString Digits = L"0123456789ABCDEF";
  1116. DebugAssert(Hex.Length() == 2);
  1117. int P1 = Digits.Pos((wchar_t)toupper(Hex[1]));
  1118. int P2 = Digits.Pos((wchar_t)toupper(Hex[2]));
  1119. return
  1120. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  1121. }
  1122. //---------------------------------------------------------------------------
  1123. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  1124. {
  1125. return (Ch >= 'a') && (Ch <= 'z');
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  1129. {
  1130. return (Ch >= 'A') && (Ch <= 'Z');
  1131. }
  1132. //---------------------------------------------------------------------------
  1133. bool __fastcall IsLetter(wchar_t Ch)
  1134. {
  1135. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  1136. }
  1137. //---------------------------------------------------------------------------
  1138. bool __fastcall IsDigit(wchar_t Ch)
  1139. {
  1140. return (Ch >= '0') && (Ch <= '9');
  1141. }
  1142. //---------------------------------------------------------------------------
  1143. bool __fastcall IsHex(wchar_t Ch)
  1144. {
  1145. return
  1146. IsDigit(Ch) ||
  1147. ((Ch >= 'A') && (Ch <= 'F')) ||
  1148. ((Ch >= 'a') && (Ch <= 'f'));
  1149. }
  1150. //---------------------------------------------------------------------------
  1151. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  1152. {
  1153. if ((Result != ERROR_SUCCESS) &&
  1154. (Result != ERROR_FILE_NOT_FOUND) &&
  1155. (Result != ERROR_NO_MORE_FILES))
  1156. {
  1157. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  1158. }
  1159. return Result;
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1163. {
  1164. F.Path = Path;
  1165. return FindFirst(ApiPath(Path), Attr, F);
  1166. }
  1167. //---------------------------------------------------------------------------
  1168. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1169. {
  1170. int Result = FindFirstUnchecked(Path, Attr, F);
  1171. return FindCheck(Result, F.Path);
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. // Equivalent to FindNext, just to complement to FindFirstUnchecked
  1175. int __fastcall FindNextUnchecked(TSearchRecChecked & F)
  1176. {
  1177. return FindNext(F);
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  1181. // I.e. even if we do not care that FindFirst failed, if FindNext
  1182. // fails after successful FindFirst, it means some terrible problem
  1183. int __fastcall FindNextChecked(TSearchRecChecked & F)
  1184. {
  1185. return FindCheck(FindNextUnchecked(F), F.Path);
  1186. }
  1187. //---------------------------------------------------------------------------
  1188. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  1189. {
  1190. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1191. bool Result = (FindFirst(ApiPath(FileName), FindAttrs, Rec) == 0);
  1192. if (Result)
  1193. {
  1194. FindClose(Rec);
  1195. }
  1196. return Result;
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  1200. TProcessLocalFileEvent CallBackFunc, void * Param,
  1201. int FindAttrs)
  1202. {
  1203. DebugAssert(CallBackFunc);
  1204. if (FindAttrs < 0)
  1205. {
  1206. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1207. }
  1208. TSearchRecChecked SearchRec;
  1209. DirName = IncludeTrailingBackslash(DirName);
  1210. if (FindFirstChecked(DirName + L"*.*", FindAttrs, SearchRec) == 0)
  1211. {
  1212. try
  1213. {
  1214. do
  1215. {
  1216. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1217. {
  1218. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  1219. }
  1220. } while (FindNextChecked(SearchRec) == 0);
  1221. }
  1222. __finally
  1223. {
  1224. FindClose(SearchRec);
  1225. }
  1226. }
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. int __fastcall FileGetAttrFix(const UnicodeString FileName)
  1230. {
  1231. // The default for FileGetAttr is to follow links
  1232. bool FollowLink = true;
  1233. // But the FileGetAttr whe called for link with FollowLink set will always fail
  1234. // as its calls InternalGetFileNameFromSymLink, which test for CheckWin32Version(6, 0)
  1235. if (!IsWinVista())
  1236. {
  1237. FollowLink = false;
  1238. }
  1239. return FileGetAttr(FileName, FollowLink);
  1240. }
  1241. //---------------------------------------------------------------------------
  1242. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  1243. {
  1244. try
  1245. {
  1246. TDateTime DateTime = EncodeDate(Year, Month, Day);
  1247. return DateTime;
  1248. }
  1249. catch (EConvertError & E)
  1250. {
  1251. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  1252. }
  1253. }
  1254. //---------------------------------------------------------------------------
  1255. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  1256. {
  1257. try
  1258. {
  1259. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  1260. return DateTime;
  1261. }
  1262. catch (EConvertError & E)
  1263. {
  1264. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  1265. }
  1266. }
  1267. //---------------------------------------------------------------------------
  1268. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  1269. {
  1270. try
  1271. {
  1272. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1273. return DateTime;
  1274. }
  1275. catch (EConvertError & E)
  1276. {
  1277. 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))));
  1278. }
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. struct TDateTimeParams
  1282. {
  1283. TDateTime UnixEpoch;
  1284. double BaseDifference;
  1285. long BaseDifferenceSec;
  1286. // All Current* are actually global, not per-year and
  1287. // are valid for Year 0 (current) only
  1288. double CurrentDaylightDifference;
  1289. long CurrentDaylightDifferenceSec;
  1290. double CurrentDifference;
  1291. long CurrentDifferenceSec;
  1292. double StandardDifference;
  1293. long StandardDifferenceSec;
  1294. double DaylightDifference;
  1295. long DaylightDifferenceSec;
  1296. SYSTEMTIME SystemStandardDate;
  1297. SYSTEMTIME SystemDaylightDate;
  1298. TDateTime StandardDate;
  1299. TDateTime DaylightDate;
  1300. UnicodeString StandardName;
  1301. UnicodeString DaylightName;
  1302. // This is actually global, not per-year
  1303. bool DaylightHack;
  1304. bool HasDST() const
  1305. {
  1306. // On some systems it occurs that StandardDate is unset, while
  1307. // DaylightDate is set. MSDN states that this is invalid and
  1308. // should be treated as if there is no daylight saving.
  1309. // So check both.
  1310. return
  1311. (SystemStandardDate.wMonth != 0) &&
  1312. (SystemDaylightDate.wMonth != 0);
  1313. }
  1314. bool SummerDST() const
  1315. {
  1316. return HasDST() && (DaylightDate < StandardDate);
  1317. }
  1318. };
  1319. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  1320. static TYearlyDateTimeParams YearlyDateTimeParams;
  1321. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(new TCriticalSection());
  1322. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1323. TDateTime & Result);
  1324. //---------------------------------------------------------------------------
  1325. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  1326. {
  1327. unsigned short Year, Month, Day;
  1328. DecodeDate(DateTime, Year, Month, Day);
  1329. return Year;
  1330. }
  1331. //---------------------------------------------------------------------------
  1332. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  1333. {
  1334. TGuard Guard(DateTimeParamsSection.get());
  1335. TDateTimeParams * Result;
  1336. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  1337. if (i != YearlyDateTimeParams.end())
  1338. {
  1339. Result = &(*i).second;
  1340. }
  1341. else
  1342. {
  1343. // creates new entry as a side effect
  1344. Result = &YearlyDateTimeParams[Year];
  1345. TIME_ZONE_INFORMATION TZI;
  1346. unsigned long GTZI;
  1347. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1348. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  1349. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  1350. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  1351. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  1352. {
  1353. GTZI = GetTimeZoneInformation(&TZI);
  1354. }
  1355. else
  1356. {
  1357. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1358. GTZI = TIME_ZONE_ID_UNKNOWN;
  1359. }
  1360. switch (GTZI)
  1361. {
  1362. case TIME_ZONE_ID_UNKNOWN:
  1363. Result->CurrentDaylightDifferenceSec = 0;
  1364. break;
  1365. case TIME_ZONE_ID_STANDARD:
  1366. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1367. break;
  1368. case TIME_ZONE_ID_DAYLIGHT:
  1369. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1370. break;
  1371. case TIME_ZONE_ID_INVALID:
  1372. default:
  1373. throw Exception(TIMEZONE_ERROR);
  1374. }
  1375. Result->BaseDifferenceSec = TZI.Bias;
  1376. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1377. Result->BaseDifferenceSec *= SecsPerMin;
  1378. Result->CurrentDifferenceSec = TZI.Bias +
  1379. Result->CurrentDaylightDifferenceSec;
  1380. Result->CurrentDifference =
  1381. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1382. Result->CurrentDifferenceSec *= SecsPerMin;
  1383. Result->CurrentDaylightDifference =
  1384. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1385. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1386. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1387. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1388. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1389. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1390. Result->SystemStandardDate = TZI.StandardDate;
  1391. Result->SystemDaylightDate = TZI.DaylightDate;
  1392. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1393. if (Result->HasDST())
  1394. {
  1395. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1396. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1397. }
  1398. Result->StandardName = TZI.StandardName;
  1399. Result->DaylightName = TZI.DaylightName;
  1400. Result->DaylightHack = !IsWin7();
  1401. }
  1402. return Result;
  1403. }
  1404. //---------------------------------------------------------------------------
  1405. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1406. TDateTime & Result)
  1407. {
  1408. if (Date.wYear == 0)
  1409. {
  1410. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1411. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1412. (7 * (Date.wDay - 1));
  1413. // Day 5 means, the last occurence of day-of-week in month
  1414. if (Date.wDay == 5)
  1415. {
  1416. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1417. if (Month > 12)
  1418. {
  1419. Month = static_cast<unsigned short>(Month - 12);
  1420. Year++;
  1421. }
  1422. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1423. {
  1424. Result -= 7;
  1425. }
  1426. }
  1427. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1428. Date.wMilliseconds);
  1429. }
  1430. else
  1431. {
  1432. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1433. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1434. }
  1435. }
  1436. //---------------------------------------------------------------------------
  1437. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1438. {
  1439. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1440. bool Result;
  1441. // On some systems it occurs that StandardDate is unset, while
  1442. // DaylightDate is set. MSDN states that this is invalid and
  1443. // should be treated as if there is no daylight saving.
  1444. // So check both.
  1445. if (!Params->HasDST())
  1446. {
  1447. Result = false;
  1448. }
  1449. else
  1450. {
  1451. if (Params->SummerDST())
  1452. {
  1453. Result =
  1454. (DateTime >= Params->DaylightDate) &&
  1455. (DateTime < Params->StandardDate);
  1456. }
  1457. else
  1458. {
  1459. Result =
  1460. (DateTime < Params->StandardDate) ||
  1461. (DateTime >= Params->DaylightDate);
  1462. }
  1463. }
  1464. return Result;
  1465. }
  1466. //---------------------------------------------------------------------------
  1467. bool __fastcall UsesDaylightHack()
  1468. {
  1469. return GetDateTimeParams(0)->DaylightHack;
  1470. }
  1471. //---------------------------------------------------------------------------
  1472. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1473. {
  1474. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1475. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1476. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1477. if (Params->DaylightHack)
  1478. {
  1479. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1480. {
  1481. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1482. Result -= CurrentParams->CurrentDifference;
  1483. }
  1484. else if (DSTMode == dstmKeep)
  1485. {
  1486. Result -= Params->BaseDifference;
  1487. }
  1488. }
  1489. else
  1490. {
  1491. Result -= Params->BaseDifference;
  1492. }
  1493. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1494. {
  1495. Result -= DSTDifferenceForTime(Result);
  1496. }
  1497. return Result;
  1498. }
  1499. //---------------------------------------------------------------------------
  1500. __int64 __fastcall Round(double Number)
  1501. {
  1502. double Floor = floor(Number);
  1503. double Ceil = ceil(Number);
  1504. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1505. }
  1506. //---------------------------------------------------------------------------
  1507. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime)
  1508. {
  1509. S = S.Trim();
  1510. int Index = 1;
  1511. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1512. {
  1513. Index++;
  1514. }
  1515. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1516. int Number;
  1517. bool Result = TryStrToInt(NumberStr, Number);
  1518. if (Result)
  1519. {
  1520. S.Delete(1, Index - 1);
  1521. S = S.Trim().UpperCase();
  1522. DateTime = Now();
  1523. // These may not overlap with ParseSize (K, M and G)
  1524. if (S == "S")
  1525. {
  1526. DateTime = IncSecond(DateTime, -Number);
  1527. }
  1528. else if (S == "N")
  1529. {
  1530. DateTime = IncMinute(DateTime, -Number);
  1531. }
  1532. else if (S == "H")
  1533. {
  1534. DateTime = IncHour(DateTime, -Number);
  1535. }
  1536. else if (S == "D")
  1537. {
  1538. DateTime = IncDay(DateTime, -Number);
  1539. }
  1540. else if (S == "Y")
  1541. {
  1542. DateTime = IncYear(DateTime, -Number);
  1543. }
  1544. else
  1545. {
  1546. Result = false;
  1547. }
  1548. }
  1549. return Result;
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1553. {
  1554. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1555. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1556. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1557. CurrentParams->CurrentDifferenceSec;
  1558. }
  1559. //---------------------------------------------------------------------------
  1560. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1561. TDSTMode /*DSTMode*/)
  1562. {
  1563. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1564. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1565. if (!Params->DaylightHack)
  1566. {
  1567. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  1568. // We are incrementing and decrementing BaseDifferenceSec because it
  1569. // can actually change between years
  1570. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  1571. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1572. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  1573. Params->BaseDifferenceSec;
  1574. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1575. UnixTimeStamp -=
  1576. CurrentParams->CurrentDaylightDifferenceSec +
  1577. CurrentParams->BaseDifferenceSec;
  1578. }
  1579. FILETIME Result;
  1580. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1581. return Result;
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1585. {
  1586. // duplicated in DirView.pas
  1587. TDateTime Result;
  1588. // The 0xFFF... is sometime seen for invalid timestamps,
  1589. // it would cause failure in SystemTimeToDateTime below
  1590. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  1591. {
  1592. Result = MinDateTime;
  1593. }
  1594. else
  1595. {
  1596. SYSTEMTIME SysTime;
  1597. if (!UsesDaylightHack())
  1598. {
  1599. SYSTEMTIME UniverzalSysTime;
  1600. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1601. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1602. }
  1603. else
  1604. {
  1605. FILETIME LocalFileTime;
  1606. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1607. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1608. }
  1609. Result = SystemTimeToDateTimeVerbose(SysTime);
  1610. }
  1611. return Result;
  1612. }
  1613. //---------------------------------------------------------------------------
  1614. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1615. TDSTMode DSTMode)
  1616. {
  1617. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1618. if (UsesDaylightHack())
  1619. {
  1620. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1621. {
  1622. FILETIME LocalFileTime;
  1623. SYSTEMTIME SystemTime;
  1624. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1625. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1626. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1627. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1628. Result += (IsDateInDST(DateTime) ?
  1629. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1630. if (DSTMode == dstmKeep)
  1631. {
  1632. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1633. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1634. }
  1635. }
  1636. }
  1637. else
  1638. {
  1639. if (DSTMode == dstmWin)
  1640. {
  1641. FILETIME LocalFileTime;
  1642. SYSTEMTIME SystemTime;
  1643. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1644. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1645. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1646. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1647. Result -= (IsDateInDST(DateTime) ?
  1648. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1649. }
  1650. }
  1651. return Result;
  1652. }
  1653. //---------------------------------------------------------------------------
  1654. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1655. {
  1656. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1657. DateTime += DSTDifferenceForTime(DateTime);
  1658. DateTime += Params->BaseDifference;
  1659. if (Params->DaylightHack)
  1660. {
  1661. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1662. DateTime += CurrentParams->CurrentDaylightDifference;
  1663. }
  1664. return DateTime;
  1665. }
  1666. //---------------------------------------------------------------------------
  1667. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1668. {
  1669. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1670. DateTime -= DSTDifferenceForTime(DateTime);
  1671. DateTime -= Params->BaseDifference;
  1672. if (Params->DaylightHack)
  1673. {
  1674. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1675. DateTime -= CurrentParams->CurrentDaylightDifference;
  1676. }
  1677. return DateTime;
  1678. }
  1679. //---------------------------------------------------------------------------
  1680. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1681. TDSTMode DSTMode)
  1682. {
  1683. __int64 Result;
  1684. if ((FileTime.dwLowDateTime == 0) &&
  1685. (FileTime.dwHighDateTime == 0))
  1686. {
  1687. Result = ::DateTimeToUnix(Now());
  1688. }
  1689. else
  1690. {
  1691. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  1692. }
  1693. return Result;
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. double __fastcall DSTDifferenceForTime(TDateTime DateTime)
  1697. {
  1698. double Result;
  1699. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1700. if (IsDateInDST(DateTime))
  1701. {
  1702. Result = Params->DaylightDifference;
  1703. }
  1704. else
  1705. {
  1706. Result = Params->StandardDifference;
  1707. }
  1708. return Result;
  1709. }
  1710. //---------------------------------------------------------------------------
  1711. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  1712. {
  1713. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1714. if (Params->DaylightHack)
  1715. {
  1716. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1717. {
  1718. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1719. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  1720. }
  1721. if (!IsDateInDST(DateTime))
  1722. {
  1723. if (DSTMode == dstmWin)
  1724. {
  1725. DateTime = DateTime - Params->DaylightDifference;
  1726. }
  1727. }
  1728. else
  1729. {
  1730. DateTime = DateTime - Params->StandardDifference;
  1731. }
  1732. }
  1733. else
  1734. {
  1735. if (DSTMode == dstmWin)
  1736. {
  1737. DateTime = DateTime + DSTDifferenceForTime(DateTime);
  1738. }
  1739. }
  1740. return DateTime;
  1741. }
  1742. //---------------------------------------------------------------------------
  1743. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  1744. {
  1745. UnicodeString Result = Format;
  1746. bool AsIs = false;
  1747. int Index = 1;
  1748. while (Index <= Result.Length())
  1749. {
  1750. wchar_t F = Result[Index];
  1751. if ((F == L'\'') || (F == L'\"'))
  1752. {
  1753. AsIs = !AsIs;
  1754. Index++;
  1755. }
  1756. else if (!AsIs && ((F == L'a') || (F == L'A')))
  1757. {
  1758. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  1759. {
  1760. Index += 5;
  1761. }
  1762. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  1763. {
  1764. Index += 3;
  1765. }
  1766. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  1767. {
  1768. Index += 4;
  1769. }
  1770. else
  1771. {
  1772. Index++;
  1773. }
  1774. }
  1775. else
  1776. {
  1777. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  1778. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  1779. {
  1780. Result.Insert(F, Index);
  1781. }
  1782. while ((Index <= Result.Length()) && (F == Result[Index]))
  1783. {
  1784. Index++;
  1785. }
  1786. }
  1787. }
  1788. return Result;
  1789. }
  1790. //---------------------------------------------------------------------------
  1791. UnicodeString __fastcall FormatTimeZone(long Sec)
  1792. {
  1793. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  1794. UnicodeString Str;
  1795. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  1796. {
  1797. Str = FORMAT(L"%d", (-Span.Hours));
  1798. }
  1799. else if (Span.Seconds == 0)
  1800. {
  1801. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  1802. }
  1803. else
  1804. {
  1805. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  1806. }
  1807. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  1808. return Str;
  1809. }
  1810. //---------------------------------------------------------------------------
  1811. UnicodeString __fastcall GetTimeZoneLogString()
  1812. {
  1813. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1814. UnicodeString Result =
  1815. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  1816. if (!CurrentParams->HasDST())
  1817. {
  1818. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  1819. }
  1820. else
  1821. {
  1822. Result +=
  1823. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  1824. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  1825. CurrentParams->StandardName,
  1826. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  1827. CurrentParams->DaylightName,
  1828. CurrentParams->DaylightDate.DateString(),
  1829. CurrentParams->StandardDate.DateString()));
  1830. }
  1831. return Result;
  1832. }
  1833. //---------------------------------------------------------------------------
  1834. bool __fastcall AdjustClockForDSTEnabled()
  1835. {
  1836. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  1837. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  1838. bool DynamicDaylightTimeDisabled = false;
  1839. TRegistry * Registry = new TRegistry(KEY_READ);
  1840. try
  1841. {
  1842. Registry->RootKey = HKEY_LOCAL_MACHINE;
  1843. if (Registry->OpenKey(L"SYSTEM", false) &&
  1844. Registry->OpenKey(L"CurrentControlSet", false) &&
  1845. Registry->OpenKey(L"Control", false) &&
  1846. Registry->OpenKey(L"TimeZoneInformation", false))
  1847. {
  1848. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  1849. {
  1850. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  1851. }
  1852. // WORKAROUND
  1853. // Windows XP equivalent
  1854. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  1855. {
  1856. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  1857. }
  1858. }
  1859. delete Registry;
  1860. }
  1861. catch(...)
  1862. {
  1863. }
  1864. return !DynamicDaylightTimeDisabled;
  1865. }
  1866. //---------------------------------------------------------------------------
  1867. UnicodeString __fastcall StandardDatestamp()
  1868. {
  1869. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  1870. }
  1871. //---------------------------------------------------------------------------
  1872. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  1873. {
  1874. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  1875. }
  1876. //---------------------------------------------------------------------------
  1877. UnicodeString __fastcall StandardTimestamp()
  1878. {
  1879. return StandardTimestamp(Now());
  1880. }
  1881. //---------------------------------------------------------------------------
  1882. static TDateTime TwoSeconds(0, 0, 2, 0);
  1883. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  1884. {
  1885. // "FAT" time precision
  1886. // (when one time is seconds-precision and other is millisecond-precision,
  1887. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  1888. // be treated the same)
  1889. int Result;
  1890. if (T1 == T2)
  1891. {
  1892. // just optimization
  1893. Result = 0;
  1894. }
  1895. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  1896. {
  1897. Result = -1;
  1898. }
  1899. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  1900. {
  1901. Result = 1;
  1902. }
  1903. else
  1904. {
  1905. Result = 0;
  1906. }
  1907. return Result;
  1908. }
  1909. //---------------------------------------------------------------------------
  1910. int __fastcall TimeToMSec(TDateTime T)
  1911. {
  1912. return int(Round(double(T) * double(MSecsPerDay)));
  1913. }
  1914. //---------------------------------------------------------------------------
  1915. int __fastcall TimeToSeconds(TDateTime T)
  1916. {
  1917. return TimeToMSec(T) / MSecsPerSec;
  1918. }
  1919. //---------------------------------------------------------------------------
  1920. int __fastcall TimeToMinutes(TDateTime T)
  1921. {
  1922. return TimeToSeconds(T) / SecsPerMin;
  1923. }
  1924. //---------------------------------------------------------------------------
  1925. static bool __fastcall DoRecursiveDeleteFile(const UnicodeString FileName, bool ToRecycleBin, UnicodeString & ErrorPath)
  1926. {
  1927. bool Result;
  1928. UnicodeString AErrorPath = FileName;
  1929. if (!ToRecycleBin)
  1930. {
  1931. TSearchRecChecked SearchRec;
  1932. Result = FileSearchRec(FileName, SearchRec);
  1933. if (Result)
  1934. {
  1935. if (FLAGCLEAR(SearchRec.Attr, faDirectory))
  1936. {
  1937. Result = DeleteFile(ApiPath(FileName));
  1938. }
  1939. else
  1940. {
  1941. Result = (FindFirstUnchecked(FileName + L"\\*", faAnyFile, SearchRec) == 0);
  1942. if (Result)
  1943. {
  1944. try
  1945. {
  1946. do
  1947. {
  1948. UnicodeString FileName2 = FileName + L"\\" + SearchRec.Name;
  1949. if (FLAGSET(SearchRec.Attr, faDirectory))
  1950. {
  1951. if ((SearchRec.Name != L".") && (SearchRec.Name != L".."))
  1952. {
  1953. Result = DoRecursiveDeleteFile(FileName2, DebugAlwaysFalse(ToRecycleBin), AErrorPath);
  1954. }
  1955. }
  1956. else
  1957. {
  1958. Result = DeleteFile(ApiPath(FileName2));
  1959. if (!Result)
  1960. {
  1961. AErrorPath = FileName2;
  1962. }
  1963. }
  1964. }
  1965. while (Result && (FindNextUnchecked(SearchRec) == 0));
  1966. }
  1967. __finally
  1968. {
  1969. FindClose(SearchRec);
  1970. }
  1971. if (Result)
  1972. {
  1973. Result = RemoveDir(ApiPath(FileName));
  1974. }
  1975. }
  1976. }
  1977. }
  1978. }
  1979. else
  1980. {
  1981. SHFILEOPSTRUCT Data;
  1982. memset(&Data, 0, sizeof(Data));
  1983. Data.hwnd = NULL;
  1984. Data.wFunc = FO_DELETE;
  1985. // SHFileOperation does not support long paths anyway
  1986. UnicodeString FileList(ApiPath(FileName));
  1987. FileList.SetLength(FileList.Length() + 2);
  1988. FileList[FileList.Length() - 1] = L'\0';
  1989. FileList[FileList.Length()] = L'\0';
  1990. Data.pFrom = FileList.c_str();
  1991. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  1992. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  1993. FOF_NOERRORUI | FOF_SILENT;
  1994. if (DebugAlwaysTrue(ToRecycleBin))
  1995. {
  1996. Data.fFlags |= FOF_ALLOWUNDO;
  1997. }
  1998. int ErrorCode = SHFileOperation(&Data);
  1999. Result = (ErrorCode == 0);
  2000. if (!Result)
  2001. {
  2002. // according to MSDN, SHFileOperation may return following non-Win32
  2003. // error codes
  2004. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  2005. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  2006. (ErrorCode == 0x10074))
  2007. {
  2008. ErrorCode = 0;
  2009. }
  2010. SetLastError(ErrorCode);
  2011. }
  2012. }
  2013. if (!Result)
  2014. {
  2015. ErrorPath = AErrorPath;
  2016. }
  2017. return Result;
  2018. }
  2019. //---------------------------------------------------------------------------
  2020. bool __fastcall RecursiveDeleteFile(const UnicodeString & FileName, bool ToRecycleBin)
  2021. {
  2022. UnicodeString ErrorPath; // unused
  2023. return DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath);
  2024. }
  2025. //---------------------------------------------------------------------------
  2026. void __fastcall RecursiveDeleteFileChecked(const UnicodeString & FileName, bool ToRecycleBin)
  2027. {
  2028. UnicodeString ErrorPath;
  2029. if (!DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath))
  2030. {
  2031. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (ErrorPath)));
  2032. }
  2033. }
  2034. //---------------------------------------------------------------------------
  2035. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  2036. {
  2037. if (!DeleteFile(ApiPath(FileName)))
  2038. {
  2039. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  2040. }
  2041. }
  2042. //---------------------------------------------------------------------------
  2043. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  2044. {
  2045. unsigned int Result;
  2046. if ((Answers & qaCancel) != 0)
  2047. {
  2048. Result = qaCancel;
  2049. }
  2050. else if ((Answers & qaNo) != 0)
  2051. {
  2052. Result = qaNo;
  2053. }
  2054. else if ((Answers & qaAbort) != 0)
  2055. {
  2056. Result = qaAbort;
  2057. }
  2058. else if ((Answers & qaOK) != 0)
  2059. {
  2060. Result = qaOK;
  2061. }
  2062. else
  2063. {
  2064. DebugFail();
  2065. Result = qaCancel;
  2066. }
  2067. return Result;
  2068. }
  2069. //---------------------------------------------------------------------------
  2070. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  2071. {
  2072. unsigned int Result;
  2073. if (FLAGSET(Answers, qaAbort))
  2074. {
  2075. Result = qaAbort;
  2076. }
  2077. else
  2078. {
  2079. Result = CancelAnswer(Answers);
  2080. }
  2081. return Result;
  2082. }
  2083. //---------------------------------------------------------------------------
  2084. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  2085. {
  2086. unsigned int Result;
  2087. if (FLAGSET(Answers, qaSkip))
  2088. {
  2089. Result = qaSkip;
  2090. }
  2091. else if (FLAGSET(Answers, qaIgnore))
  2092. {
  2093. Result = qaIgnore;
  2094. }
  2095. else if (FLAGSET(Answers, qaYes))
  2096. {
  2097. Result = qaYes;
  2098. }
  2099. else if (FLAGSET(Answers, qaOK))
  2100. {
  2101. Result = qaOK;
  2102. }
  2103. else if (FLAGSET(Answers, qaRetry))
  2104. {
  2105. Result = qaRetry;
  2106. }
  2107. else
  2108. {
  2109. Result = CancelAnswer(Answers);
  2110. }
  2111. return Result;
  2112. }
  2113. //---------------------------------------------------------------------------
  2114. TLibModule * __fastcall FindModule(void * Instance)
  2115. {
  2116. TLibModule * CurModule;
  2117. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  2118. while (CurModule)
  2119. {
  2120. if (CurModule->Instance == (unsigned)Instance)
  2121. {
  2122. break;
  2123. }
  2124. else
  2125. {
  2126. CurModule = CurModule->Next;
  2127. }
  2128. }
  2129. return CurModule;
  2130. }
  2131. //---------------------------------------------------------------------------
  2132. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  2133. {
  2134. TLibModule * MainModule = FindModule(HInstance);
  2135. DebugAssert(MainModule != NULL);
  2136. UnicodeString Result;
  2137. Result.SetLength(MaxLength);
  2138. int Length = LoadString((HINSTANCE)MainModule->ResInstance, Ident, Result.c_str(), MaxLength);
  2139. Result.SetLength(Length);
  2140. return Result;
  2141. }
  2142. //---------------------------------------------------------------------------
  2143. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  2144. {
  2145. UnicodeString Result;
  2146. UnicodeString Str = LoadStr(Ident);
  2147. while (Part > 0)
  2148. {
  2149. Result = CutToChar(Str, L'|', false);
  2150. Part--;
  2151. }
  2152. return Result;
  2153. }
  2154. //---------------------------------------------------------------------------
  2155. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  2156. {
  2157. int i = 1;
  2158. while (i <= S.Length())
  2159. {
  2160. switch (S[i])
  2161. {
  2162. case L'+':
  2163. S[i] = ' ';
  2164. break;
  2165. case L'%':
  2166. {
  2167. UnicodeString Hex;
  2168. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2169. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2170. {
  2171. Hex += S.SubString(i + 1, 2);
  2172. S.Delete(i, 3);
  2173. }
  2174. if (!Hex.IsEmpty())
  2175. {
  2176. RawByteString Bytes = HexToBytes(Hex);
  2177. UnicodeString Chars(UTF8ToString(Bytes));
  2178. S.Insert(Chars, i);
  2179. i += Chars.Length() - 1;
  2180. }
  2181. }
  2182. break;
  2183. }
  2184. i++;
  2185. }
  2186. return S;
  2187. }
  2188. //---------------------------------------------------------------------------
  2189. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, bool EncodeSlash)
  2190. {
  2191. int Index = 1;
  2192. while (Index <= S.Length())
  2193. {
  2194. wchar_t C = S[Index];
  2195. if (IsLetter(C) ||
  2196. IsDigit(C) ||
  2197. (C == L'_') || (C == L'-') || (C == L'.') ||
  2198. ((C == L'/') && !EncodeSlash))
  2199. {
  2200. Index++;
  2201. }
  2202. else
  2203. {
  2204. UTF8String UtfS(S.SubString(Index, 1));
  2205. UnicodeString H;
  2206. for (int Index2 = 1; Index2 <= UtfS.Length(); Index2++)
  2207. {
  2208. H += L"%" + ByteToHex(static_cast<unsigned char>(UtfS[Index2]));
  2209. }
  2210. S.Delete(Index, 1);
  2211. S.Insert(H, Index);
  2212. Index += H.Length();
  2213. }
  2214. }
  2215. return S;
  2216. }
  2217. //---------------------------------------------------------------------------
  2218. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  2219. {
  2220. return DoEncodeUrl(S, true);
  2221. }
  2222. //---------------------------------------------------------------------------
  2223. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2224. {
  2225. return DoEncodeUrl(S, false);
  2226. }
  2227. //---------------------------------------------------------------------------
  2228. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2229. {
  2230. // see also TWebHelpSystem::ShowHelp
  2231. const wchar_t FragmentSeparator = L'#';
  2232. UnicodeString URL = CutToChar(AURL, FragmentSeparator, false);
  2233. if (URL.Pos(L"?") == 0)
  2234. {
  2235. URL += L"?";
  2236. }
  2237. else
  2238. {
  2239. URL += L"&";
  2240. }
  2241. URL += Params;
  2242. AddToList(URL, AURL, FragmentSeparator);
  2243. return URL;
  2244. }
  2245. //---------------------------------------------------------------------------
  2246. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2247. {
  2248. return ReplaceStr(Caption, L"&", L"&&");
  2249. }
  2250. //---------------------------------------------------------------------------
  2251. // duplicated in console's Main.cpp
  2252. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2253. UnicodeString * RawToken, UnicodeString * Separator)
  2254. {
  2255. bool Result;
  2256. Token = L"";
  2257. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2258. int Index = 1;
  2259. while ((Index <= Str.Length()) &&
  2260. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2261. {
  2262. Index++;
  2263. }
  2264. if (Index <= Str.Length())
  2265. {
  2266. bool Quoting = false;
  2267. while (Index <= Str.Length())
  2268. {
  2269. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2270. {
  2271. break;
  2272. }
  2273. // We should escape quotes only within quotes
  2274. // otherwise the "" means " (quote), but it should mean empty string.
  2275. // Or have a special case for bare "".
  2276. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2277. (Str[Index + 1] == L'"'))
  2278. {
  2279. Index += 2;
  2280. Token += L'"';
  2281. }
  2282. else if (Str[Index] == L'"')
  2283. {
  2284. Index++;
  2285. Quoting = !Quoting;
  2286. }
  2287. else
  2288. {
  2289. Token += Str[Index];
  2290. Index++;
  2291. }
  2292. }
  2293. if (RawToken != NULL)
  2294. {
  2295. (*RawToken) = Str.SubString(1, Index - 1);
  2296. }
  2297. if (Index <= Str.Length())
  2298. {
  2299. if (Separator != NULL)
  2300. {
  2301. *Separator = Str.SubString(Index, 1);
  2302. }
  2303. Index++;
  2304. }
  2305. else
  2306. {
  2307. if (Separator != NULL)
  2308. {
  2309. *Separator = UnicodeString();
  2310. }
  2311. }
  2312. Str = Str.SubString(Index, Str.Length());
  2313. Result = true;
  2314. }
  2315. else
  2316. {
  2317. Result = false;
  2318. Str = L"";
  2319. }
  2320. return Result;
  2321. }
  2322. //---------------------------------------------------------------------------
  2323. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2324. {
  2325. if (!Value.IsEmpty())
  2326. {
  2327. if (!List.IsEmpty() &&
  2328. ((List.Length() < Delimiter.Length()) ||
  2329. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2330. {
  2331. List += Delimiter;
  2332. }
  2333. List += Value;
  2334. }
  2335. }
  2336. //---------------------------------------------------------------------------
  2337. bool __fastcall IsWinVista()
  2338. {
  2339. // Vista is 6.0
  2340. // Win XP is 5.1
  2341. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  2342. // (we consider it WinXP for now)
  2343. return CheckWin32Version(6, 0);
  2344. }
  2345. //---------------------------------------------------------------------------
  2346. bool __fastcall IsWin7()
  2347. {
  2348. return CheckWin32Version(6, 1);
  2349. }
  2350. //---------------------------------------------------------------------------
  2351. bool __fastcall IsWin8()
  2352. {
  2353. return CheckWin32Version(6, 2);
  2354. }
  2355. //---------------------------------------------------------------------------
  2356. bool __fastcall IsWin10()
  2357. {
  2358. return CheckWin32Version(10, 0);
  2359. }
  2360. //---------------------------------------------------------------------------
  2361. bool __fastcall IsWine()
  2362. {
  2363. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2364. return
  2365. DebugAlwaysTrue(NtDll != NULL) &&
  2366. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2367. }
  2368. //---------------------------------------------------------------------------
  2369. LCID __fastcall GetDefaultLCID()
  2370. {
  2371. return GetUserDefaultLCID();
  2372. }
  2373. //---------------------------------------------------------------------------
  2374. static UnicodeString ADefaultEncodingName;
  2375. UnicodeString __fastcall DefaultEncodingName()
  2376. {
  2377. if (ADefaultEncodingName.IsEmpty())
  2378. {
  2379. CPINFOEX Info;
  2380. GetCPInfoEx(CP_ACP, 0, &Info);
  2381. ADefaultEncodingName = Info.CodePageName;
  2382. }
  2383. return ADefaultEncodingName;
  2384. }
  2385. //---------------------------------------------------------------------------
  2386. bool _fastcall GetWindowsProductType(DWORD & Type)
  2387. {
  2388. bool Result;
  2389. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2390. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  2391. TGetProductInfo GetProductInfo =
  2392. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  2393. if (GetProductInfo == NULL)
  2394. {
  2395. Result = false;
  2396. }
  2397. else
  2398. {
  2399. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  2400. Result = true;
  2401. }
  2402. return Result;
  2403. }
  2404. //---------------------------------------------------------------------------
  2405. UnicodeString __fastcall WindowsProductName()
  2406. {
  2407. UnicodeString Result;
  2408. TRegistry * Registry = new TRegistry(KEY_READ);
  2409. try
  2410. {
  2411. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2412. if (Registry->OpenKey(L"SOFTWARE", false) &&
  2413. Registry->OpenKey(L"Microsoft", false) &&
  2414. Registry->OpenKey(L"Windows NT", false) &&
  2415. Registry->OpenKey(L"CurrentVersion", false))
  2416. {
  2417. Result = Registry->ReadString(L"ProductName");
  2418. }
  2419. delete Registry;
  2420. }
  2421. catch(...)
  2422. {
  2423. }
  2424. return Result;
  2425. }
  2426. //---------------------------------------------------------------------------
  2427. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  2428. {
  2429. UnicodeString FileName =
  2430. IncludeTrailingPathDelimiter(Path) +
  2431. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  2432. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  2433. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  2434. bool Result = (Handle != INVALID_HANDLE_VALUE);
  2435. if (Result)
  2436. {
  2437. CloseHandle(Handle);
  2438. }
  2439. return Result;
  2440. }
  2441. //---------------------------------------------------------------------------
  2442. UnicodeString __fastcall FormatNumber(__int64 Number)
  2443. {
  2444. return FormatFloat(L"#,##0", Number);
  2445. }
  2446. //---------------------------------------------------------------------------
  2447. // simple alternative to FormatBytes
  2448. UnicodeString __fastcall FormatSize(__int64 Size)
  2449. {
  2450. return FormatNumber(Size);
  2451. }
  2452. //---------------------------------------------------------------------------
  2453. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  2454. {
  2455. return ChangeFileExt(ExtractFileName(Path), L"");
  2456. }
  2457. //---------------------------------------------------------------------------
  2458. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  2459. {
  2460. std::unique_ptr<TStringList> List(new TStringList());
  2461. List->Text = Text;
  2462. return List.release();
  2463. }
  2464. //---------------------------------------------------------------------------
  2465. UnicodeString __fastcall StringsToText(TStrings * Strings)
  2466. {
  2467. UnicodeString Result;
  2468. if (Strings->Count == 1)
  2469. {
  2470. Result = Strings->Strings[0];
  2471. }
  2472. else
  2473. {
  2474. Result = Strings->Text;
  2475. }
  2476. return Result;
  2477. }
  2478. //---------------------------------------------------------------------------
  2479. TStrings * __fastcall CloneStrings(TStrings * Strings)
  2480. {
  2481. std::unique_ptr<TStringList> List(new TStringList());
  2482. List->AddStrings(Strings);
  2483. return List.release();
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  2487. {
  2488. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  2489. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  2490. {
  2491. Version.SetLength(Version.Length() - 2);
  2492. }
  2493. return Version;
  2494. }
  2495. //---------------------------------------------------------------------------
  2496. UnicodeString __fastcall FormatVersion(int MajovVersion, int MinorVersion, int Release)
  2497. {
  2498. return
  2499. TrimVersion(FORMAT(L"%d.%d.%d",
  2500. (MajovVersion, MinorVersion, Release)));
  2501. }
  2502. //---------------------------------------------------------------------------
  2503. TFormatSettings __fastcall GetEngFormatSettings()
  2504. {
  2505. return TFormatSettings::Create((TLocaleID)1033);
  2506. }
  2507. //---------------------------------------------------------------------------
  2508. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  2509. {
  2510. TFormatSettings FormatSettings = GetEngFormatSettings();
  2511. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  2512. }
  2513. //---------------------------------------------------------------------------
  2514. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  2515. {
  2516. TStringList * Result = new TStringList();
  2517. Result->CaseSensitive = CaseSensitive;
  2518. Result->Sorted = true;
  2519. Result->Duplicates = Duplicates;
  2520. return Result;
  2521. }
  2522. //---------------------------------------------------------------------------
  2523. static UnicodeString __fastcall NormalizeIdent(UnicodeString Ident)
  2524. {
  2525. int Index = 1;
  2526. while (Index <= Ident.Length())
  2527. {
  2528. if (Ident[Index] == L'-')
  2529. {
  2530. Ident.Delete(Index, 1);
  2531. }
  2532. else
  2533. {
  2534. Index++;
  2535. }
  2536. }
  2537. return Ident;
  2538. }
  2539. //---------------------------------------------------------------------------
  2540. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  2541. {
  2542. UnicodeString NormalizedIdent(NormalizeIdent(Ident));
  2543. for (int Index = 0; Index < Idents->Count; Index++)
  2544. {
  2545. if (SameText(NormalizedIdent, NormalizeIdent(Idents->Strings[Index])))
  2546. {
  2547. return Idents->Strings[Index];
  2548. }
  2549. }
  2550. return Ident;
  2551. }
  2552. //---------------------------------------------------------------------------
  2553. static UnicodeString __fastcall GetTlsErrorStr(int Err)
  2554. {
  2555. char * Buffer = new char[512];
  2556. ERR_error_string(Err, Buffer);
  2557. // not sure about the UTF8
  2558. return UnicodeString(UTF8String(Buffer));
  2559. }
  2560. //---------------------------------------------------------------------------
  2561. static FILE * __fastcall OpenCertificate(const UnicodeString & Path)
  2562. {
  2563. FILE * Result = _wfopen(ApiPath(Path).c_str(), L"rb");
  2564. if (Result == NULL)
  2565. {
  2566. int Error = errno;
  2567. throw EOSExtException(MainInstructions(FMTLOAD(CERTIFICATE_OPEN_ERROR, (Path))), Error);
  2568. }
  2569. return Result;
  2570. }
  2571. //---------------------------------------------------------------------------
  2572. struct TPemPasswordCallbackData
  2573. {
  2574. UnicodeString * Passphrase;
  2575. };
  2576. //---------------------------------------------------------------------------
  2577. static int PemPasswordCallback(char * Buf, int Size, int /*RWFlag*/, void * UserData)
  2578. {
  2579. TPemPasswordCallbackData & Data = *reinterpret_cast<TPemPasswordCallbackData *>(UserData);
  2580. UTF8String UtfPassphrase = UTF8String(*Data.Passphrase);
  2581. strncpy(Buf, UtfPassphrase.c_str(), Size);
  2582. Shred(UtfPassphrase);
  2583. Buf[Size - 1] = '\0';
  2584. return strlen(Buf);
  2585. }
  2586. //---------------------------------------------------------------------------
  2587. static bool __fastcall IsTlsPassphraseError(int Error, bool HasPassphrase)
  2588. {
  2589. int ErrorLib = ERR_GET_LIB(Error);
  2590. int ErrorReason = ERR_GET_REASON(Error);
  2591. bool Result =
  2592. ((ErrorLib == ERR_LIB_PKCS12) &&
  2593. (ErrorReason == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  2594. ((ErrorLib == ERR_LIB_PEM) &&
  2595. (ErrorReason == PEM_R_BAD_PASSWORD_READ)) ||
  2596. (HasPassphrase && (ERR_LIB_EVP == ERR_LIB_EVP) &&
  2597. ((ErrorReason == PEM_R_BAD_DECRYPT) || (ErrorReason == PEM_R_BAD_BASE64_DECODE)));
  2598. return Result;
  2599. }
  2600. //---------------------------------------------------------------------------
  2601. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path, bool HasPassphrase)
  2602. {
  2603. int Error = ERR_get_error();
  2604. if (!IsTlsPassphraseError(Error, HasPassphrase))
  2605. {
  2606. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  2607. }
  2608. }
  2609. //---------------------------------------------------------------------------
  2610. void __fastcall ParseCertificate(const UnicodeString & Path,
  2611. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  2612. bool & WrongPassphrase)
  2613. {
  2614. Certificate = NULL;
  2615. PrivateKey = NULL;
  2616. bool HasPassphrase = !Passphrase.IsEmpty();
  2617. FILE * File;
  2618. // Inspired by neon's ne_ssl_clicert_read
  2619. File = OpenCertificate(Path);
  2620. // openssl pkcs12 -inkey cert.pem -in cert.crt -export -out cert.pfx
  2621. // Binary file
  2622. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  2623. fclose(File);
  2624. if (Pkcs12 != NULL)
  2625. {
  2626. // Not sure about the UTF-8 encoding, but there's no wchar_t API
  2627. bool Result =
  2628. (PKCS12_parse(Pkcs12, UTF8String(Passphrase).c_str(), &PrivateKey, &Certificate, NULL) == 1);
  2629. PKCS12_free(Pkcs12);
  2630. if (!Result)
  2631. {
  2632. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  2633. WrongPassphrase = true;
  2634. }
  2635. }
  2636. else
  2637. {
  2638. ERR_clear_error();
  2639. TPemPasswordCallbackData CallbackUserData;
  2640. // PemPasswordCallback never writes to the .Passphrase
  2641. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  2642. File = OpenCertificate(Path);
  2643. // Encrypted:
  2644. // openssl req -x509 -newkey rsa:2048 -keyout cert.pem -out cert.crt
  2645. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  2646. // ...
  2647. // -----END ENCRYPTED PRIVATE KEY-----
  2648. // Not encrypted (add -nodes):
  2649. // -----BEGIN PRIVATE KEY-----
  2650. // ...
  2651. // -----END PRIVATE KEY-----
  2652. // Or (openssl genrsa -out client.key 1024 # used for certificate signing request)
  2653. // -----BEGIN RSA PRIVATE KEY-----
  2654. // ...
  2655. // -----END RSA PRIVATE KEY-----
  2656. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  2657. fclose(File);
  2658. try
  2659. {
  2660. if (PrivateKey == NULL)
  2661. {
  2662. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  2663. WrongPassphrase = true;
  2664. }
  2665. File = OpenCertificate(Path);
  2666. // The file can contain both private and public key
  2667. // (basically cert.pem and cert.crt appended one to each other)
  2668. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  2669. // ...
  2670. // -----END ENCRYPTED PRIVATE KEY-----
  2671. // -----BEGIN CERTIFICATE-----
  2672. // ...
  2673. // -----END CERTIFICATE-----
  2674. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2675. fclose(File);
  2676. if (Certificate == NULL)
  2677. {
  2678. int Error = ERR_get_error();
  2679. // unlikely
  2680. if (IsTlsPassphraseError(Error, HasPassphrase))
  2681. {
  2682. WrongPassphrase = true;
  2683. }
  2684. else
  2685. {
  2686. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  2687. if (!FileExists(CertificatePath))
  2688. {
  2689. CertificatePath = ChangeFileExt(Path, L".crt");
  2690. }
  2691. if (!FileExists(CertificatePath))
  2692. {
  2693. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  2694. }
  2695. else
  2696. {
  2697. File = OpenCertificate(CertificatePath);
  2698. // -----BEGIN CERTIFICATE-----
  2699. // ...
  2700. // -----END CERTIFICATE-----
  2701. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  2702. fclose(File);
  2703. if (Certificate == NULL)
  2704. {
  2705. int Base64Error = ERR_get_error();
  2706. File = OpenCertificate(CertificatePath);
  2707. // Binary DER-encoded certificate
  2708. // (as above, with BEGIN/END removed, and decoded from Base64 to binary)
  2709. // openssl x509 -in cert.crt -out client.der.crt -outform DER
  2710. Certificate = d2i_X509_fp(File, NULL);
  2711. fclose(File);
  2712. if (Certificate == NULL)
  2713. {
  2714. int DERError = ERR_get_error();
  2715. UnicodeString Message = MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (CertificatePath)));
  2716. UnicodeString MoreMessages =
  2717. FORMAT(L"Base64: %s\nDER: %s", (GetTlsErrorStr(Base64Error), GetTlsErrorStr(DERError)));
  2718. throw ExtException(Message, MoreMessages);
  2719. }
  2720. }
  2721. }
  2722. }
  2723. }
  2724. }
  2725. __finally
  2726. {
  2727. // We loaded private key, but failed to load certificate, discard the certificate
  2728. // (either exception was thrown or WrongPassphrase)
  2729. if ((PrivateKey != NULL) && (Certificate == NULL))
  2730. {
  2731. EVP_PKEY_free(PrivateKey);
  2732. PrivateKey = NULL;
  2733. }
  2734. // Certificate was verified, but passphrase was wrong when loading private key,
  2735. // so discard the certificate
  2736. else if ((Certificate != NULL) && (PrivateKey == NULL))
  2737. {
  2738. X509_free(Certificate);
  2739. Certificate = NULL;
  2740. }
  2741. }
  2742. }
  2743. }
  2744. //---------------------------------------------------------------------------
  2745. void __fastcall CheckCertificate(const UnicodeString & Path)
  2746. {
  2747. X509 * Certificate;
  2748. EVP_PKEY * PrivateKey;
  2749. bool WrongPassphrase;
  2750. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  2751. if (PrivateKey != NULL)
  2752. {
  2753. EVP_PKEY_free(PrivateKey);
  2754. }
  2755. if (Certificate != NULL)
  2756. {
  2757. X509_free(Certificate);
  2758. }
  2759. }
  2760. //---------------------------------------------------------------------------
  2761. bool __fastcall IsHttpUrl(const UnicodeString & S)
  2762. {
  2763. return SameText(S.SubString(1, 4), L"http");
  2764. }
  2765. //---------------------------------------------------------------------------
  2766. const UnicodeString RtfPara = L"\\par\n";
  2767. const UnicodeString RtfHyperlinkField = L"HYPERLINK";
  2768. const UnicodeString RtfHyperlinkFieldPrefix = RtfHyperlinkField + L" \"";
  2769. const UnicodeString RtfHyperlinkFieldSuffix = L"\" ";
  2770. //---------------------------------------------------------------------
  2771. UnicodeString __fastcall RtfColor(int Index)
  2772. {
  2773. return FORMAT(L"\\cf%d", (Index));
  2774. }
  2775. //---------------------------------------------------------------------
  2776. UnicodeString __fastcall RtfText(const UnicodeString & Text)
  2777. {
  2778. UnicodeString Result = Text;
  2779. int Index = 1;
  2780. while (Index <= Result.Length())
  2781. {
  2782. UnicodeString Replacement;
  2783. wchar_t Ch = Result[Index];
  2784. if ((Ch == L'\\') || (Ch == L'{') || (Ch == L'}'))
  2785. {
  2786. Replacement = FORMAT(L"\\%s", (Ch));
  2787. }
  2788. else if (Ch >= 0x0080)
  2789. {
  2790. Replacement = FORMAT(L"\\u%d?", (int(Ch)));
  2791. }
  2792. if (!Replacement.IsEmpty())
  2793. {
  2794. Result.Delete(Index, 1);
  2795. Result.Insert(Replacement, Index);
  2796. Index += Replacement.Length();
  2797. }
  2798. else
  2799. {
  2800. Index++;
  2801. }
  2802. }
  2803. return Result;
  2804. }
  2805. //---------------------------------------------------------------------
  2806. UnicodeString __fastcall RtfColorText(int Color, const UnicodeString & Text)
  2807. {
  2808. return RtfColor(Color) + L" " + RtfText(Text) + RtfColor(0) + L" ";
  2809. }
  2810. //---------------------------------------------------------------------
  2811. UnicodeString __fastcall RtfColorItalicText(int Color, const UnicodeString & Text)
  2812. {
  2813. return RtfColor(Color) + L"\\i " + RtfText(Text) + L"\\i0" + RtfColor(0) + L" ";
  2814. }
  2815. //---------------------------------------------------------------------
  2816. UnicodeString __fastcall RtfOverrideColorText(const UnicodeString & Text)
  2817. {
  2818. return RtfColorText(1, Text);
  2819. }
  2820. //---------------------------------------------------------------------
  2821. UnicodeString __fastcall RtfKeyword(const UnicodeString & Text)
  2822. {
  2823. return RtfColorText(5, Text);
  2824. }
  2825. //---------------------------------------------------------------------
  2826. UnicodeString __fastcall RtfParameter(const UnicodeString & Text)
  2827. {
  2828. return RtfColorText(6, Text);
  2829. }
  2830. //---------------------------------------------------------------------
  2831. UnicodeString __fastcall RtfString(const UnicodeString & Text)
  2832. {
  2833. return RtfColorText(4, Text);
  2834. }
  2835. //---------------------------------------------------------------------
  2836. UnicodeString __fastcall RtfLink(const UnicodeString & Link, const UnicodeString & RtfText)
  2837. {
  2838. return
  2839. L"{\\field{\\*\\fldinst{" + RtfHyperlinkFieldPrefix + Link + RtfHyperlinkFieldSuffix + L"}}{\\fldrslt{" +
  2840. RtfText + L"}}}";
  2841. }
  2842. //---------------------------------------------------------------------
  2843. UnicodeString __fastcall ScriptCommandLink(const UnicodeString & Command)
  2844. {
  2845. return L"scriptcommand_" + Command;
  2846. }
  2847. //---------------------------------------------------------------------
  2848. UnicodeString __fastcall RtfSwitch(const UnicodeString & Switch, const UnicodeString & Link)
  2849. {
  2850. return RtfText(L" ") + RtfLink(Link + L"#" + Switch.LowerCase(), RtfParameter(FORMAT(L"-%s", (Switch))));
  2851. }
  2852. //---------------------------------------------------------------------
  2853. UnicodeString __fastcall RtfSwitchValue(const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value)
  2854. {
  2855. return RtfSwitch(Name, Link) + L"=" + Value;
  2856. }
  2857. //---------------------------------------------------------------------
  2858. UnicodeString __fastcall RtfSwitch(const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value)
  2859. {
  2860. return RtfSwitchValue(Name, Link, RtfText(FORMAT("\"%s\"", (EscapeParam(Value)))));
  2861. }
  2862. //---------------------------------------------------------------------
  2863. UnicodeString __fastcall RtfSwitch(const UnicodeString & Name, const UnicodeString & Link, int Value)
  2864. {
  2865. return RtfSwitchValue(Name, Link, RtfText(IntToStr(Value)));
  2866. }
  2867. //---------------------------------------------------------------------
  2868. UnicodeString __fastcall RtfRemoveHyperlinks(UnicodeString Text)
  2869. {
  2870. // Remove all tags HYPERLINK "http://www.example.com".
  2871. // See also RtfEscapeParam
  2872. int Index = 1;
  2873. int P;
  2874. while ((P = PosFrom(RtfHyperlinkFieldPrefix, Text, Index)) > 0)
  2875. {
  2876. int Index2 = P + RtfHyperlinkFieldPrefix.Length();
  2877. int P2 = PosFrom(RtfHyperlinkFieldSuffix, Text, Index2);
  2878. if (P2 > 0)
  2879. {
  2880. Text.Delete(P, P2 - P + RtfHyperlinkFieldSuffix.Length());
  2881. }
  2882. else
  2883. {
  2884. Index = Index2;
  2885. }
  2886. }
  2887. return Text;
  2888. }
  2889. //---------------------------------------------------------------------
  2890. UnicodeString __fastcall RtfEscapeParam(UnicodeString Param)
  2891. {
  2892. const UnicodeString Quote(L"\"");
  2893. // Equivalent of EscapeParam, except that it does not double quotes in HYPERLINK.
  2894. // See also RtfRemoveHyperlinks.
  2895. int Index = 1;
  2896. while (true)
  2897. {
  2898. int P1 = PosFrom(Quote, Param, Index);
  2899. if (P1 == 0)
  2900. {
  2901. // no more quotes
  2902. break;
  2903. }
  2904. else
  2905. {
  2906. int P2 = PosFrom(RtfHyperlinkFieldPrefix, Param, Index);
  2907. int P3;
  2908. if ((P2 > 0) && (P2 < P1) && ((P3 = PosFrom(RtfHyperlinkFieldSuffix, Param, P2)) > 0))
  2909. {
  2910. // skip HYPERLINK
  2911. Index = P3 + RtfHyperlinkFieldSuffix.Length();
  2912. }
  2913. else
  2914. {
  2915. Param.Insert(Quote, P1);
  2916. Index = P1 + (Quote.Length() * 2);
  2917. }
  2918. }
  2919. }
  2920. return Param;
  2921. }