1
0

Common.cpp 109 KB

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