Common.cpp 111 KB

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