1
0

Common.cpp 101 KB

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