Common.cpp 110 KB

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