1
0

Common.cpp 113 KB

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