Common.cpp 100 KB

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