Common.cpp 115 KB

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