Common.cpp 111 KB

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