Common.cpp 114 KB

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