Common.cpp 114 KB

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