Common.cpp 112 KB

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