Common.cpp 110 KB

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