Common.cpp 102 KB

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