GUITools.cpp 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlobj.h>
  5. #include <mshtmhst.h>
  6. #include <Common.h>
  7. #include "GUITools.h"
  8. #include "WinConfiguration.h"
  9. #include <TextsCore.h>
  10. #include <TextsWin.h>
  11. #include <CoreMain.h>
  12. #include <SessionData.h>
  13. #include <WinInterface.h>
  14. #include <TbxUtils.hpp>
  15. #include <Math.hpp>
  16. #include <Tools.h>
  17. #include "PngImageList.hpp"
  18. #include <StrUtils.hpp>
  19. #include <limits>
  20. #include <Glyphs.h>
  21. #include <PasTools.hpp>
  22. #include <VCLCommon.h>
  23. #include <WinApi.h>
  24. #include <HistoryComboBox.hpp>
  25. #include <vssym32.h>
  26. #include <DateUtils.hpp>
  27. #include <IOUtils.hpp>
  28. #include <Queue.h>
  29. #include "Animations96.h"
  30. #include "Animations120.h"
  31. #include "Animations144.h"
  32. #include "Animations192.h"
  33. //---------------------------------------------------------------------------
  34. #pragma package(smart_init)
  35. //---------------------------------------------------------------------------
  36. extern const UnicodeString PageantTool = L"pageant.exe";
  37. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  38. //---------------------------------------------------------------------------
  39. bool __fastcall FindFile(UnicodeString & Path)
  40. {
  41. bool Result = FileExistsFix(Path);
  42. if (!Result)
  43. {
  44. UnicodeString ProgramFiles32 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramFiles"));
  45. UnicodeString ProgramFiles64 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramW6432"));
  46. if (!ProgramFiles32.IsEmpty() &&
  47. SameText(Path.SubString(1, ProgramFiles32.Length()), ProgramFiles32) &&
  48. !ProgramFiles64.IsEmpty())
  49. {
  50. UnicodeString Path64 =
  51. ProgramFiles64 + Path.SubString(ProgramFiles32.Length() + 1, Path.Length() - ProgramFiles32.Length());
  52. if (FileExists(ApiPath(Path64)))
  53. {
  54. Path = Path64;
  55. Result = true;
  56. }
  57. }
  58. }
  59. if (!Result && SameText(ExtractFileName(Path), Path))
  60. {
  61. UnicodeString Paths = GetEnvironmentVariable(L"PATH");
  62. if (!Paths.IsEmpty())
  63. {
  64. UnicodeString NewPath = FileSearch(Path, Paths);
  65. Result = !NewPath.IsEmpty();
  66. if (Result)
  67. {
  68. Path = NewPath;
  69. }
  70. else
  71. {
  72. // Basically the same what FileSearch does, except for FileExistsFix.
  73. // Once this proves working, we can ged rid of the FileSearch call.
  74. while (!Result && !Paths.IsEmpty())
  75. {
  76. UnicodeString P = CutToChar(Paths, L';', false);
  77. // Not using CombinePaths as it throws on an invalid path and PATH is not under our control
  78. NewPath = IncludeTrailingBackslash(P) + Path;
  79. Result = FileExistsFix(NewPath);
  80. if (Result)
  81. {
  82. Path = NewPath;
  83. }
  84. }
  85. }
  86. }
  87. }
  88. return Result;
  89. }
  90. //---------------------------------------------------------------------------
  91. bool DoesSessionExistInPutty(const UnicodeString & StorageKey)
  92. {
  93. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(Configuration->PuttySessionsKey));
  94. Storage->ConfigureForPutty();
  95. return Storage->OpenRootKey(true) && Storage->KeyExists(StorageKey);
  96. }
  97. //---------------------------------------------------------------------------
  98. bool __fastcall ExportSessionToPutty(TSessionData * SessionData, bool ReuseExisting, const UnicodeString & SessionName)
  99. {
  100. bool Result = true;
  101. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(Configuration->PuttySessionsKey));
  102. Storage->AccessMode = smReadWrite;
  103. Storage->ConfigureForPutty();
  104. if (Storage->OpenRootKey(true))
  105. {
  106. Result = ReuseExisting && Storage->KeyExists(SessionData->StorageKey);
  107. if (Result)
  108. {
  109. AppLogFmt(L"Reusing existing PuTTY session: %s", (SessionData->StorageKey));
  110. }
  111. else
  112. {
  113. std::unique_ptr<TRegistryStorage> SourceStorage(new TRegistryStorage(Configuration->PuttySessionsKey));
  114. SourceStorage->ConfigureForPutty();
  115. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  116. Storage->OpenSubKey(SessionName, true))
  117. {
  118. Storage->Copy(SourceStorage.get());
  119. Storage->CloseSubKey();
  120. }
  121. std::unique_ptr<TSessionData> ExportData(new TSessionData(L""));
  122. ExportData->Assign(SessionData);
  123. ExportData->Modified = true;
  124. ExportData->Name = SessionName;
  125. ExportData->WinTitle = SessionData->SessionName;
  126. ExportData->Password = L"";
  127. if (SessionData->FSProtocol == fsFTP)
  128. {
  129. if (GUIConfiguration->TelnetForFtpInPutty)
  130. {
  131. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  132. ExportData->PortNumber = TelnetPortNumber;
  133. }
  134. else
  135. {
  136. ExportData->PuttyProtocol = PuttySshProtocol;
  137. ExportData->PortNumber = SshPortNumber;
  138. }
  139. }
  140. ExportData->Save(Storage.get(), true);
  141. AppLogFmt(L"Exported site settings to PuTTY session: %s", (SessionName));
  142. }
  143. }
  144. return Result;
  145. }
  146. //---------------------------------------------------------------------------
  147. class TPuttyCleanupThread : public TSimpleThread
  148. {
  149. public:
  150. static void Schedule();
  151. static void Finalize();
  152. protected:
  153. virtual void __fastcall Execute();
  154. virtual void __fastcall Terminate();
  155. bool __fastcall Finished();
  156. void DoSchedule();
  157. private:
  158. TDateTime FTimer;
  159. static TPuttyCleanupThread * FInstance;
  160. static std::unique_ptr<TCriticalSection> FSection;
  161. };
  162. //---------------------------------------------------------------------------
  163. std::unique_ptr<TCriticalSection> TPuttyCleanupThread::FSection(TraceInitPtr(new TCriticalSection()));
  164. TPuttyCleanupThread * TPuttyCleanupThread::FInstance;
  165. //---------------------------------------------------------------------------
  166. void TPuttyCleanupThread::Schedule()
  167. {
  168. TGuard Guard(FSection.get());
  169. if (FInstance == NULL)
  170. {
  171. FInstance = new TPuttyCleanupThread();
  172. FInstance->DoSchedule();
  173. FInstance->Start();
  174. }
  175. else
  176. {
  177. FInstance->DoSchedule();
  178. }
  179. }
  180. //---------------------------------------------------------------------------
  181. void TPuttyCleanupThread::Finalize()
  182. {
  183. while (true)
  184. {
  185. {
  186. TGuard Guard(FSection.get());
  187. if (FInstance == NULL)
  188. {
  189. return;
  190. }
  191. }
  192. Sleep(100);
  193. }
  194. }
  195. //---------------------------------------------------------------------------
  196. void __fastcall TPuttyCleanupThread::Execute()
  197. {
  198. try
  199. {
  200. std::unique_ptr<TStrings> Sessions(new TStringList());
  201. bool Continue = true;
  202. do
  203. {
  204. {
  205. TGuard Guard(FSection.get());
  206. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(Configuration->PuttySessionsKey));
  207. Storage->AccessMode = smReadWrite;
  208. Storage->ConfigureForPutty();
  209. std::unique_ptr<TStringList> Sessions2(new TStringList());
  210. if (Storage->OpenRootKey(true))
  211. {
  212. std::unique_ptr<TStrings> SubKeys(new TStringList());
  213. Storage->GetSubKeyNames(SubKeys.get());
  214. for (int Index = 0; Index < SubKeys->Count; Index++)
  215. {
  216. UnicodeString SessionName = SubKeys->Strings[Index];
  217. if (StartsStr(GUIConfiguration->PuttySession, SessionName))
  218. {
  219. Sessions2->Add(SessionName);
  220. }
  221. }
  222. Sessions2->Sort();
  223. if (!Sessions->Equals(Sessions2.get()))
  224. {
  225. // Just in case new sessions from another WinSCP instance are added, delay the cleanup
  226. // (to avoid having to implement some inter-process communication).
  227. // Both instances will attempt to do the cleanup, but that not a problem
  228. Sessions->Assign(Sessions2.get());
  229. DoSchedule();
  230. }
  231. }
  232. if (FTimer < Now())
  233. {
  234. for (int Index = 0; Index < Sessions->Count; Index++)
  235. {
  236. UnicodeString SessionName = Sessions->Strings[Index];
  237. Storage->RecursiveDeleteSubKey(SessionName);
  238. }
  239. Continue = false;
  240. }
  241. }
  242. if (Continue)
  243. {
  244. Sleep(1000);
  245. }
  246. }
  247. while (Continue);
  248. }
  249. __finally
  250. {
  251. TGuard Guard(FSection.get());
  252. FInstance = NULL;
  253. }
  254. }
  255. //---------------------------------------------------------------------------
  256. void __fastcall TPuttyCleanupThread::Terminate()
  257. {
  258. DebugFail();
  259. }
  260. //---------------------------------------------------------------------------
  261. bool __fastcall TPuttyCleanupThread::Finished()
  262. {
  263. // self-destroy
  264. return TSimpleThread::Finished() || true;
  265. }
  266. //---------------------------------------------------------------------------
  267. void TPuttyCleanupThread::DoSchedule()
  268. {
  269. FTimer = IncSecond(Now(), 10);
  270. }
  271. //---------------------------------------------------------------------------
  272. class TPuttyPasswordThread : public TSimpleThread
  273. {
  274. public:
  275. TPuttyPasswordThread(const UnicodeString & Password, const UnicodeString & PipeName);
  276. virtual __fastcall ~TPuttyPasswordThread();
  277. protected:
  278. virtual void __fastcall Execute();
  279. virtual void __fastcall Terminate();
  280. virtual bool __fastcall Finished();
  281. private:
  282. HANDLE FPipe;
  283. AnsiString FPassword;
  284. void DoSleep(int & Timeout);
  285. };
  286. //---------------------------------------------------------------------------
  287. TPuttyPasswordThread::TPuttyPasswordThread(const UnicodeString & Password, const UnicodeString & PipeName)
  288. {
  289. DWORD OpenMode = PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE;
  290. DWORD PipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT | PIPE_REJECT_REMOTE_CLIENTS;
  291. DWORD BufferSize = 16 * 1024;
  292. FPipe = CreateNamedPipe(PipeName.c_str(), OpenMode, PipeMode, 1, BufferSize, BufferSize, NMPWAIT_USE_DEFAULT_WAIT, NULL);
  293. if (FPipe == INVALID_HANDLE_VALUE)
  294. {
  295. throw EOSExtException(L"Cannot create password pipe");
  296. }
  297. FPassword = AnsiString(Password);
  298. Start();
  299. }
  300. //---------------------------------------------------------------------------
  301. __fastcall TPuttyPasswordThread::~TPuttyPasswordThread()
  302. {
  303. DebugAlwaysTrue(FFinished);
  304. AppLog(L"Disconnecting and closing password pipe");
  305. DisconnectNamedPipe(FPipe);
  306. CloseHandle(FPipe);
  307. }
  308. //---------------------------------------------------------------------------
  309. void __fastcall TPuttyPasswordThread::Terminate()
  310. {
  311. // noop - the thread always self-terminates
  312. }
  313. //---------------------------------------------------------------------------
  314. bool __fastcall TPuttyPasswordThread::Finished()
  315. {
  316. return true;
  317. }
  318. //---------------------------------------------------------------------------
  319. void TPuttyPasswordThread::DoSleep(int & Timeout)
  320. {
  321. unsigned int Step = 50;
  322. Sleep(Step);
  323. Timeout -= Step;
  324. if (Timeout <= 0)
  325. {
  326. AppLog(L"Timeout waiting for PuTTY");
  327. }
  328. }
  329. //---------------------------------------------------------------------------
  330. void __fastcall TPuttyPasswordThread::Execute()
  331. {
  332. AppLog(L"Waiting for PuTTY to connect to password pipe");
  333. int Timeout = MSecsPerSec * SecsPerMin;
  334. while (Timeout > 0)
  335. {
  336. if (ConnectNamedPipe(FPipe, NULL))
  337. {
  338. AppLog(L"Password pipe is ready");
  339. }
  340. else
  341. {
  342. int Error = GetLastError();
  343. if (Error == ERROR_PIPE_CONNECTED)
  344. {
  345. AppLog(L"PuTTY has connected to password pipe");
  346. int Pos = 0;
  347. while ((Timeout > 0) && (Pos < FPassword.Length()))
  348. {
  349. DWORD Written = 0;
  350. if (!WriteFile(FPipe, FPassword.c_str() + Pos, FPassword.Length() - Pos, &Written, NULL))
  351. {
  352. AppLog(L"Error writting password pipe");
  353. Timeout = 0;
  354. }
  355. else
  356. {
  357. Pos += Written;
  358. if (Pos >= FPassword.Length())
  359. {
  360. FlushFileBuffers(FPipe);
  361. AppLog(L"Complete password was written to pipe");
  362. Timeout = 0;
  363. }
  364. else
  365. {
  366. AppLog(L"Part of password was written to pipe");
  367. DoSleep(Timeout);
  368. }
  369. }
  370. }
  371. }
  372. else if (Error == ERROR_PIPE_LISTENING)
  373. {
  374. DoSleep(Timeout);
  375. }
  376. else
  377. {
  378. AppLogFmt(L"Password pipe error %d", (Error));
  379. Timeout = 0;
  380. }
  381. }
  382. }
  383. }
  384. //---------------------------------------------------------------------------
  385. void SplitPuttyCommand(UnicodeString & Program, UnicodeString & Params)
  386. {
  387. // See also TSiteAdvancedDialog::PuttySettingsButtonClick
  388. UnicodeString Dir;
  389. SplitCommand(GUIConfiguration->PuttyPath, Program, Params, Dir);
  390. Program = ExpandEnvironmentVariables(Program);
  391. Params = ExpandEnvironmentVariables(Params);
  392. }
  393. //---------------------------------------------------------------------------
  394. UnicodeString FindPuttyPath()
  395. {
  396. UnicodeString Program, Params;
  397. SplitPuttyCommand(Program, Params);
  398. if (!FindFile(Program))
  399. {
  400. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  401. }
  402. return Program;
  403. }
  404. //---------------------------------------------------------------------------
  405. unsigned int PipeCounter = 0;
  406. //---------------------------------------------------------------------------
  407. void OpenSessionInPutty(TSessionData * SessionData)
  408. {
  409. // putty does not support resolving environment variables in session settings
  410. SessionData->ExpandEnvironmentVariables();
  411. UnicodeString Program, AParams;
  412. SplitPuttyCommand(Program, AParams);
  413. AppLogFmt(L"PuTTY program: %s", (Program));
  414. AppLogFmt(L"Params: %s", (AParams));
  415. if (FindFile(Program))
  416. {
  417. UnicodeString Password;
  418. if (GUIConfiguration->PuttyPassword)
  419. {
  420. // Passphrase has precendence, as it's more likely entered by user during authentication, hence more likely really needed.
  421. if (!SessionData->Passphrase.IsEmpty())
  422. {
  423. Password = SessionData->Passphrase;
  424. }
  425. else if (!SessionData->Password.IsEmpty())
  426. {
  427. Password = SessionData->Password;
  428. }
  429. }
  430. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  431. TLocalCustomCommand LocalCustomCommand(Data, SessionData->RemoteDirectory, SessionData->LocalDirectory);
  432. TWinInteractiveCustomCommand InteractiveCustomCommand(
  433. &LocalCustomCommand, L"PuTTY", UnicodeString());
  434. UnicodeString Params =
  435. LocalCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  436. UnicodeString PuttyParams;
  437. AppLogFmt(L"Expanded params: %s", (Params));
  438. if (!LocalCustomCommand.IsSiteCommand(AParams))
  439. {
  440. {
  441. bool SessionList = false;
  442. std::unique_ptr<THierarchicalStorage> SourceHostKeyStorage(Configuration->CreateScpStorage(SessionList));
  443. std::unique_ptr<THierarchicalStorage> TargetHostKeyStorage(new TRegistryStorage(Configuration->PuttyRegistryStorageKey));
  444. TargetHostKeyStorage->Explicit = true;
  445. TargetHostKeyStorage->AccessMode = smReadWrite;
  446. std::unique_ptr<TStoredSessionList> HostKeySessionList(new TStoredSessionList());
  447. HostKeySessionList->OwnsObjects = false;
  448. HostKeySessionList->Add(SessionData);
  449. int Imported = TStoredSessionList::ImportHostKeys(SourceHostKeyStorage.get(), TargetHostKeyStorage.get(), HostKeySessionList.get(), false);
  450. AppLogFmt(L"Imported host keys: %d", (Imported));
  451. }
  452. if (IsUWP())
  453. {
  454. bool Telnet = (SessionData->FSProtocol == fsFTP) && GUIConfiguration->TelnetForFtpInPutty;
  455. if (Telnet)
  456. {
  457. AddToList(PuttyParams, L"-telnet", L" ");
  458. // PuTTY does not allow -pw for telnet
  459. Password = L"";
  460. }
  461. AddToList(PuttyParams, EscapePuttyCommandParam(SessionData->HostName), L" ");
  462. if (!SessionData->UserName.IsEmpty())
  463. {
  464. AddToList(PuttyParams, FORMAT(L"-l %s", (EscapePuttyCommandParam(SessionData->UserName))), L" ");
  465. }
  466. if ((SessionData->FSProtocol != fsFTP) && (SessionData->PortNumber != SshPortNumber))
  467. {
  468. AddToList(PuttyParams, FORMAT(L"-P %d", (SessionData->PortNumber)), L" ");
  469. }
  470. if (!Telnet)
  471. {
  472. UnicodeString PublicKeyFile = SessionData->ResolvePublicKeyFile();
  473. if (!PublicKeyFile.IsEmpty())
  474. {
  475. AddToList(PuttyParams, FORMAT(L"-i \"%s\"", (PublicKeyFile)), L" ");
  476. }
  477. AddToList(PuttyParams, (SessionData->TryAgent ? L"-agent" : L"-noagent"), L" ");
  478. if (SessionData->TryAgent)
  479. {
  480. AddToList(PuttyParams, (SessionData->AgentFwd ? L"-A" : L"-a"), L" ");
  481. }
  482. if (SessionData->Compression)
  483. {
  484. AddToList(PuttyParams, L"-C", L" ");
  485. }
  486. AddToList(PuttyParams, L"-2", L" ");
  487. if (!SessionData->LogicalHostName.IsEmpty())
  488. {
  489. AddToList(PuttyParams, FORMAT(L"-loghost \"%s\"", (SessionData->LogicalHostName)), L" ");
  490. }
  491. }
  492. if (SessionData->AddressFamily == afIPv4)
  493. {
  494. AddToList(PuttyParams, L"-4", L" ");
  495. }
  496. else if (SessionData->AddressFamily == afIPv6)
  497. {
  498. AddToList(PuttyParams, L"-6", L" ");
  499. }
  500. AppLogFmt(L"Using command-line instead of stored session in UWP: %s", (PuttyParams));
  501. }
  502. else
  503. {
  504. UnicodeString SessionName;
  505. UnicodeString PuttySession = GUIConfiguration->PuttySession;
  506. int Uniq = 1;
  507. while (DoesSessionExistInPutty(PuttySession))
  508. {
  509. Uniq++;
  510. PuttySession = FORMAT(L"%s (%d)", (GUIConfiguration->PuttySession, Uniq));
  511. }
  512. if (ExportSessionToPutty(SessionData, true, PuttySession))
  513. {
  514. SessionName = SessionData->SessionName;
  515. }
  516. else
  517. {
  518. SessionName = PuttySession;
  519. TPuttyCleanupThread::Schedule();
  520. if ((SessionData->FSProtocol == fsFTP) &&
  521. GUIConfiguration->TelnetForFtpInPutty)
  522. {
  523. // PuTTY does not allow -pw for telnet
  524. Password = L"";
  525. }
  526. }
  527. UnicodeString LoadSwitch = L"-load";
  528. int P = Params.LowerCase().Pos(LoadSwitch + L" ");
  529. if ((P == 0) || ((P > 1) && (Params[P - 1] != L' ')))
  530. {
  531. AddToList(PuttyParams, FORMAT(L"%s %s", (LoadSwitch, EscapePuttyCommandParam(SessionName))), L" ");
  532. }
  533. }
  534. }
  535. if (!Password.IsEmpty() && !LocalCustomCommand.IsPasswordCommand(AParams))
  536. {
  537. Password = NormalizeString(Password); // if password is empty, we should quote it always
  538. bool UsePuttyPwFile;
  539. if (GUIConfiguration->UsePuttyPwFile == asAuto)
  540. {
  541. UsePuttyPwFile = false;
  542. if (SameText(ExtractFileName(Program), OriginalPuttyExecutable))
  543. {
  544. unsigned int Version = GetFileVersion(Program);
  545. if (Version != static_cast<unsigned int>(-1))
  546. {
  547. int MajorVersion = HIWORD(Version);
  548. int MinorVersion = LOWORD(Version);
  549. if (CalculateCompoundVersion(MajorVersion, MinorVersion) >= CalculateCompoundVersion(0, 77))
  550. {
  551. UsePuttyPwFile = true;
  552. }
  553. }
  554. }
  555. }
  556. else
  557. {
  558. UsePuttyPwFile = (GUIConfiguration->UsePuttyPwFile == asOn);
  559. }
  560. UnicodeString PasswordParam;
  561. if (UsePuttyPwFile)
  562. {
  563. PipeCounter++;
  564. UnicodeString PipeName = FORMAT(L"\\\\.\\PIPE\\WinSCPPuTTYPassword.%.8x.%.8x.%.4x", (GetCurrentProcessId(), PipeCounter, rand()));
  565. new TPuttyPasswordThread(Password, PipeName);
  566. PasswordParam = FORMAT(L"-pwfile \"%s\"", (PipeName));
  567. }
  568. else
  569. {
  570. PasswordParam = FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password)));
  571. }
  572. AddToList(PuttyParams, PasswordParam, L" ");
  573. }
  574. AddToList(PuttyParams, Params, L" ");
  575. // PuTTY is started in its binary directory to allow relative paths in private key,
  576. // when opening PuTTY's own stored session.
  577. ExecuteShellChecked(Program, PuttyParams, true);
  578. }
  579. else
  580. {
  581. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  582. }
  583. }
  584. //---------------------------------------------------------------------------
  585. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  586. {
  587. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  588. Path = AppPath + Name;
  589. bool Result = true;
  590. if (!FileExists(ApiPath(Path)))
  591. {
  592. Path = AppPath + L"PuTTY\\" + Name;
  593. if (!FileExists(ApiPath(Path)))
  594. {
  595. Path = Name;
  596. if (!FindFile(Path))
  597. {
  598. Result = false;
  599. }
  600. }
  601. }
  602. return Result;
  603. }
  604. //---------------------------------------------------------------------------
  605. void __fastcall ExecuteTool(const UnicodeString & Name)
  606. {
  607. UnicodeString Path;
  608. if (!FindTool(Name, Path))
  609. {
  610. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Name)));
  611. }
  612. ExecuteShellChecked(Path, L"");
  613. }
  614. //---------------------------------------------------------------------------
  615. TObjectList * StartCreationDirectoryMonitorsOnEachDrive(unsigned int Filter, TFileChangedEvent OnChanged)
  616. {
  617. std::unique_ptr<TStrings> Drives(new TStringList());
  618. std::unique_ptr<TStrings> DDDrives(CommaTextToStringList(WinConfiguration->DDDrives));
  619. UnicodeString ExcludedDrives;
  620. for (int Index = 0; Index < DDDrives->Count; Index++)
  621. {
  622. UnicodeString S = Trim(DDDrives->Strings[Index]);
  623. if (!S.IsEmpty() && (S[1] == L'-'))
  624. {
  625. S = Trim(S.SubString(2, S.Length() - 1));
  626. if (!S.IsEmpty())
  627. {
  628. ExcludedDrives += S[1];
  629. }
  630. }
  631. else
  632. {
  633. Drives->Add(S);
  634. }
  635. }
  636. for (char Drive = FirstDrive; Drive <= LastDrive; Drive++)
  637. {
  638. if (ExcludedDrives.Pos(Drive) == 0)
  639. {
  640. // Not calling ReadDriveStatus(... dsSize), relying on drive ready status cached by the background thread
  641. TDriveInfoRec * DriveInfoRec = DriveInfo->Get(Drive);
  642. if (DriveInfoRec->Valid && DriveInfoRec->DriveReady &&
  643. (DriveInfoRec->DriveType != DRIVE_CDROM) &&
  644. ((DriveInfoRec->DriveType != DRIVE_REMOVABLE) || (Drive >= DriveInfo->FirstFixedDrive)))
  645. {
  646. Drives->Add(Drive);
  647. }
  648. }
  649. }
  650. std::unique_ptr<TObjectList> Result(new TObjectList());
  651. for (int Index = 0; Index < Drives->Count; Index++)
  652. {
  653. UnicodeString Drive = Drives->Strings[Index];
  654. std::unique_ptr<TDirectoryMonitor> Monitor(new TDirectoryMonitor(Application));
  655. try
  656. {
  657. Monitor->Path = DriveInfo->GetDriveRoot(Drive);
  658. Monitor->WatchSubtree = true;
  659. Monitor->WatchFilters = Filter;
  660. Monitor->OnCreated = OnChanged;
  661. Monitor->OnModified = OnChanged;
  662. Monitor->Active = true;
  663. Result->Add(Monitor.release());
  664. }
  665. catch (Exception & E)
  666. {
  667. // Ignore errors watching not-ready drives
  668. }
  669. }
  670. return Result.release();
  671. }
  672. //---------------------------------------------------------------------------
  673. bool DontCopyCommandToClipboard = false;
  674. //---------------------------------------------------------------------------
  675. bool __fastcall CopyCommandToClipboard(const UnicodeString & Command)
  676. {
  677. bool Result = !DontCopyCommandToClipboard && UseAlternativeFunction() && IsKeyPressed(VK_CONTROL);
  678. if (Result)
  679. {
  680. TInstantOperationVisualizer Visualizer;
  681. AppLogFmt(L"Copied command to the clipboard: %s", (Command));
  682. CopyToClipboard(Command);
  683. }
  684. return Result;
  685. }
  686. //---------------------------------------------------------------------------
  687. static bool __fastcall DoExecuteShell(const UnicodeString Path, const UnicodeString Params,
  688. bool ChangeWorkingDirectory, HANDLE * Handle)
  689. {
  690. bool Result = CopyCommandToClipboard(FormatCommand(Path, Params));
  691. if (Result)
  692. {
  693. if (Handle != NULL)
  694. {
  695. *Handle = NULL;
  696. }
  697. }
  698. else
  699. {
  700. UnicodeString Directory = ExtractFilePath(Path);
  701. TShellExecuteInfoW ExecuteInfo;
  702. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  703. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  704. ExecuteInfo.fMask =
  705. SEE_MASK_FLAG_NO_UI |
  706. FLAGMASK((Handle != NULL), SEE_MASK_NOCLOSEPROCESS);
  707. ExecuteInfo.hwnd = Application->Handle;
  708. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  709. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  710. ExecuteInfo.lpDirectory = (ChangeWorkingDirectory ? Directory.c_str() : NULL);
  711. ExecuteInfo.nShow = SW_SHOW;
  712. AppLogFmt(L"Executing program \"%s\" with params: %s", (Path, Params));
  713. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  714. if (Result)
  715. {
  716. if (Handle != NULL)
  717. {
  718. *Handle = ExecuteInfo.hProcess;
  719. }
  720. }
  721. }
  722. return Result;
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall ExecuteShellChecked(const UnicodeString Path, const UnicodeString Params, bool ChangeWorkingDirectory)
  726. {
  727. if (!DoExecuteShell(Path, Params, ChangeWorkingDirectory, NULL))
  728. {
  729. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Path)));
  730. }
  731. }
  732. //---------------------------------------------------------------------------
  733. void __fastcall ExecuteShellChecked(const UnicodeString Command)
  734. {
  735. UnicodeString Program, Params, Dir;
  736. SplitCommand(Command, Program, Params, Dir);
  737. ExecuteShellChecked(Program, Params);
  738. }
  739. //---------------------------------------------------------------------------
  740. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  741. HANDLE & Handle)
  742. {
  743. return DoExecuteShell(Path, Params, false, &Handle);
  744. }
  745. //---------------------------------------------------------------------------
  746. void __fastcall ExecuteShellCheckedAndWait(const UnicodeString Command,
  747. TProcessMessagesEvent ProcessMessages)
  748. {
  749. UnicodeString Program, Params, Dir;
  750. SplitCommand(Command, Program, Params, Dir);
  751. HANDLE ProcessHandle;
  752. bool Result = DoExecuteShell(Program, Params, false, &ProcessHandle);
  753. if (!Result)
  754. {
  755. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  756. }
  757. else
  758. {
  759. if (ProcessHandle != NULL) // only if command was copied to clipboard only
  760. {
  761. if (ProcessMessages != NULL)
  762. {
  763. unsigned long WaitResult;
  764. do
  765. {
  766. // Same as in ExecuteProcessAndReadOutput
  767. WaitResult = WaitForSingleObject(ProcessHandle, 50);
  768. if (WaitResult == WAIT_FAILED)
  769. {
  770. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  771. }
  772. ProcessMessages();
  773. }
  774. while (WaitResult == WAIT_TIMEOUT);
  775. }
  776. else
  777. {
  778. WaitForSingleObject(ProcessHandle, INFINITE);
  779. }
  780. }
  781. }
  782. }
  783. //---------------------------------------------------------------------------
  784. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  785. {
  786. LPITEMIDLIST Pidl;
  787. wchar_t Buf[256];
  788. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  789. SHGetPathFromIDList(Pidl, Buf))
  790. {
  791. Path = UnicodeString(Buf);
  792. return true;
  793. }
  794. return false;
  795. }
  796. //---------------------------------------------------------------------------
  797. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  798. bool Mask)
  799. {
  800. DebugAssert(!BaseDir.IsEmpty());
  801. UnicodeString TempDir;
  802. do
  803. {
  804. TempDir = IncludeTrailingBackslash(BaseDir) + Identity;
  805. if (Mask)
  806. {
  807. TempDir += L"?????";
  808. }
  809. else
  810. {
  811. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  812. }
  813. }
  814. while (!Mask && DirectoryExists(ApiPath(TempDir)));
  815. return TempDir;
  816. }
  817. //---------------------------------------------------------------------------
  818. class TSessionColors : public TComponent
  819. {
  820. public:
  821. __fastcall TSessionColors(TComponent * Owner) : TComponent(Owner)
  822. {
  823. Name = QualifiedClassName();
  824. }
  825. static TSessionColors * __fastcall Retrieve(TComponent * Component)
  826. {
  827. TSessionColors * SessionColors = dynamic_cast<TSessionColors *>(Component->FindComponent(QualifiedClassName()));
  828. if (SessionColors == NULL)
  829. {
  830. SessionColors = new TSessionColors(Component);
  831. }
  832. return SessionColors;
  833. }
  834. typedef std::map<TColor, int> TColorMap;
  835. TColorMap ColorMap;
  836. };
  837. //---------------------------------------------------------------------------
  838. int __fastcall GetSessionColorImage(
  839. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  840. {
  841. TSessionColors * SessionColors = TSessionColors::Retrieve(ImageList);
  842. int Result;
  843. TSessionColors::TColorMap::const_iterator I = SessionColors->ColorMap.find(Color);
  844. if (I != SessionColors->ColorMap.end())
  845. {
  846. Result = I->second;
  847. }
  848. else
  849. {
  850. // This overly complex drawing is here to support color button on SiteAdvanced
  851. // dialog. There we use plain TImageList, instead of TPngImageList,
  852. // TButton does not work with transparent images
  853. // (not even TBitmap with Transparent = true)
  854. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  855. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  856. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  857. MaskImage->Assign(MaskBitmap.get());
  858. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  859. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  860. TColor TransparentColor = MaskTransparentColor;
  861. // Expecting that the color to be replaced is in the centre of the image (HACK)
  862. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  863. for (int Y = 0; Y < ImageList->Height; Y++)
  864. {
  865. for (int X = 0; X < ImageList->Width; X++)
  866. {
  867. TColor SourceColor = MaskImage->Pixels[X][Y];
  868. TColor DestColor;
  869. // this branch is pointless as long as MaskTransparentColor and
  870. // TransparentColor are the same
  871. if (SourceColor == MaskTransparentColor)
  872. {
  873. DestColor = TransparentColor;
  874. }
  875. else if (SourceColor == MaskColor)
  876. {
  877. DestColor = Color;
  878. }
  879. else
  880. {
  881. DestColor = SourceColor;
  882. }
  883. ColorImage->Pixels[X][Y] = DestColor;
  884. }
  885. }
  886. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  887. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  888. ColorImage->AssignTo(Bitmap.get());
  889. Result = ImageList->AddMasked(Bitmap.get(), TransparentColor);
  890. SessionColors->ColorMap.insert(std::make_pair(Color, Result));
  891. }
  892. return Result;
  893. }
  894. //---------------------------------------------------------------------------
  895. void __fastcall RegenerateSessionColorsImageList(TCustomImageList * ImageList, int MaskIndex)
  896. {
  897. TSessionColors * SessionColors = TSessionColors::Retrieve(ImageList);
  898. std::vector<TColor> Colors;
  899. size_t FixedImages = static_cast<size_t>(ImageList->Count);
  900. Colors.resize(FixedImages + SessionColors->ColorMap.size());
  901. TSessionColors::TColorMap::const_iterator I = SessionColors->ColorMap.begin();
  902. while (I != SessionColors->ColorMap.end())
  903. {
  904. DebugAssert(Colors[I->second] == TColor());
  905. Colors[I->second] = I->first;
  906. I++;
  907. }
  908. TSessionColors::TColorMap ColorMap = SessionColors->ColorMap;
  909. SessionColors->ColorMap.clear();
  910. for (size_t Index = 0; Index < Colors.size(); Index++)
  911. {
  912. bool IsFixedImageIndex = (Index < FixedImages);
  913. DebugAssert((Colors[Index] == TColor()) == IsFixedImageIndex);
  914. if (!IsFixedImageIndex)
  915. {
  916. GetSessionColorImage(ImageList, Colors[Index], MaskIndex);
  917. }
  918. }
  919. DebugAssert(SessionColors->ColorMap == ColorMap);
  920. }
  921. //---------------------------------------------------------------------------
  922. void __fastcall SetSubmenu(TTBXCustomItem * Item, bool Enable)
  923. {
  924. class TTBXPublicItem : public TTBXCustomItem
  925. {
  926. public:
  927. __property ItemStyle;
  928. };
  929. TTBXPublicItem * PublicItem = reinterpret_cast<TTBXPublicItem *>(Item);
  930. DebugAssert(PublicItem != NULL);
  931. // See TTBItemViewer.IsPtInButtonPart (called from TTBItemViewer.MouseDown)
  932. if (Enable)
  933. {
  934. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  935. }
  936. else
  937. {
  938. PublicItem->ItemStyle = PublicItem->ItemStyle >> tbisSubmenu;
  939. }
  940. }
  941. //---------------------------------------------------------------------------
  942. bool __fastcall IsEligibleForApplyingTabs(
  943. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  944. {
  945. bool Result = false;
  946. TabPos = Line.Pos(L"\t");
  947. if (TabPos > 0)
  948. {
  949. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  950. // WORKAROUND
  951. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  952. // Delete these, so that the following check does not fail on this
  953. while (Remaining.SubString(1, 1) == L"\t")
  954. {
  955. Remaining.Delete(1, 1);
  956. }
  957. // We do not have, not support, mutiple tabs on a single line
  958. if (DebugAlwaysTrue(Remaining.Pos(L"\t") == 0))
  959. {
  960. Start = Line.SubString(1, TabPos - 1);
  961. // WORKAROUND
  962. // Previously we padded the string before tab with spaces,
  963. // to aling the contents across multiple lines
  964. Start = Start.TrimRight();
  965. // at least two normal spaces for separation
  966. Start += L" ";
  967. Result = true;
  968. }
  969. }
  970. return Result;
  971. }
  972. //---------------------------------------------------------------------------
  973. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  974. {
  975. return Text.Length();
  976. }
  977. //---------------------------------------------------------------------------
  978. void __fastcall ApplyTabs(
  979. UnicodeString & Text, wchar_t Padding,
  980. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  981. {
  982. if (CalculateWidth == NULL)
  983. {
  984. DebugAssert(CalculateWidthArg == NULL);
  985. CalculateWidth = CalculateWidthByLength;
  986. }
  987. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  988. int MaxWidth = -1;
  989. for (int Index = 0; Index < Lines->Count; Index++)
  990. {
  991. UnicodeString Line = Lines->Strings[Index];
  992. int TabPos;
  993. UnicodeString Start;
  994. UnicodeString Remaining;
  995. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  996. {
  997. int Width = CalculateWidth(Start, CalculateWidthArg);
  998. MaxWidth = Max(MaxWidth, Width);
  999. }
  1000. }
  1001. // Optimization and also to prevent potential regression for texts without tabs
  1002. if (MaxWidth >= 0)
  1003. {
  1004. for (int Index = 0; Index < Lines->Count; Index++)
  1005. {
  1006. UnicodeString Line = Lines->Strings[Index];
  1007. int TabPos;
  1008. UnicodeString Start;
  1009. UnicodeString Remaining;
  1010. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  1011. {
  1012. int Width;
  1013. int Iterations = 0;
  1014. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  1015. {
  1016. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  1017. // If padded string is wider than max width by more pixels
  1018. // than non-padded string is shorter than max width
  1019. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  1020. {
  1021. break;
  1022. }
  1023. Start += Padding;
  1024. Iterations++;
  1025. // In rare case a tab is zero-width with some strange font (like HYLE)
  1026. if (Iterations > 100)
  1027. {
  1028. break;
  1029. }
  1030. }
  1031. Lines->Strings[Index] = Start + Remaining;
  1032. }
  1033. }
  1034. Text = Lines->Text;
  1035. // remove trailing newline
  1036. Text = Text.TrimRight();
  1037. }
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. static void __fastcall DoSelectScaledImageList(TImageList * ImageList)
  1041. {
  1042. TImageList * MatchingList = NULL;
  1043. int MachingPixelsPerInch = 0;
  1044. int PixelsPerInch = LargerPixelsPerInch(GetComponentPixelsPerInch(ImageList), WinConfiguration->LargerToolbar);
  1045. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  1046. {
  1047. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  1048. if ((OtherList != NULL) &&
  1049. (OtherList != ImageList) &&
  1050. StartsStr(ImageList->Name, OtherList->Name))
  1051. {
  1052. UnicodeString OtherListPixelsPerInchStr =
  1053. OtherList->Name.SubString(
  1054. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  1055. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  1056. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  1057. ((MatchingList == NULL) ||
  1058. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  1059. {
  1060. MatchingList = OtherList;
  1061. MachingPixelsPerInch = OtherListPixelsPerInch;
  1062. }
  1063. }
  1064. }
  1065. if (MatchingList != NULL)
  1066. {
  1067. UnicodeString ImageListBackupName = ImageList->Name + IntToStr(USER_DEFAULT_SCREEN_DPI);
  1068. if (ImageList->Owner->FindComponent(ImageListBackupName) == NULL)
  1069. {
  1070. TImageList * ImageListBackup;
  1071. TPngImageList * PngImageList = dynamic_cast<TPngImageList *>(ImageList);
  1072. if (PngImageList != NULL)
  1073. {
  1074. ImageListBackup = new TPngImageList(ImageList->Owner);
  1075. }
  1076. else
  1077. {
  1078. ImageListBackup = new TImageList(ImageList->Owner);
  1079. }
  1080. ImageListBackup->Name = ImageListBackupName;
  1081. ImageList->Owner->InsertComponent(ImageListBackup);
  1082. CopyImageList(ImageListBackup, ImageList);
  1083. }
  1084. CopyImageList(ImageList, MatchingList);
  1085. }
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. static void __fastcall ImageListRescale(TComponent * Sender, TObject * /*Token*/)
  1089. {
  1090. TImageList * ImageList = DebugNotNull(dynamic_cast<TImageList *>(Sender));
  1091. DoSelectScaledImageList(ImageList);
  1092. }
  1093. //---------------------------------------------------------------------------
  1094. void __fastcall SelectScaledImageList(TImageList * ImageList)
  1095. {
  1096. DoSelectScaledImageList(ImageList);
  1097. SetRescaleFunction(ImageList, ImageListRescale);
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  1101. {
  1102. // Maybe this is not necessary, once the TPngImageList::Assign was fixed
  1103. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  1104. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  1105. TargetList->Clear();
  1106. TargetList->Height = SourceList->Height;
  1107. TargetList->Width = SourceList->Width;
  1108. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  1109. {
  1110. // AddImages won't copy the names and we need them for
  1111. // LoadDialogImage and TFrameAnimation
  1112. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  1113. }
  1114. else
  1115. {
  1116. TargetList->AddImages(SourceList);
  1117. }
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. static bool __fastcall DoLoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  1121. {
  1122. bool Result = false;
  1123. if (GlyphsModule != NULL)
  1124. {
  1125. TPngImageList * DialogImages = GetDialogImages(Image);
  1126. int Index;
  1127. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  1128. {
  1129. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  1130. if (SameText(PngItem->Name, ImageName))
  1131. {
  1132. Image->Picture->Assign(PngItem->PngImage);
  1133. break;
  1134. }
  1135. }
  1136. DebugAssert(Index < DialogImages->PngImages->Count);
  1137. Result = true;
  1138. }
  1139. // When showing an exception from wWinMain, the images are released already.
  1140. // Non-existence of the glyphs module is just a good indication of that.
  1141. // We expect errors only.
  1142. else if (ImageName == L"Error")
  1143. {
  1144. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  1145. }
  1146. // For showing an information about trace files
  1147. else if (DebugAlwaysTrue(ImageName == L"Information"))
  1148. {
  1149. Image->Picture->Icon->Handle = LoadIcon(0, IDI_APPLICATION);
  1150. }
  1151. return Result;
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. class TDialogImageName : public TObject
  1155. {
  1156. public:
  1157. UnicodeString ImageName;
  1158. };
  1159. //---------------------------------------------------------------------------
  1160. static void __fastcall DialogImageRescale(TComponent * Sender, TObject * Token)
  1161. {
  1162. TImage * Image = DebugNotNull(dynamic_cast<TImage *>(Sender));
  1163. TDialogImageName * DialogImageName = DebugNotNull(dynamic_cast<TDialogImageName *>(Token));
  1164. DoLoadDialogImage(Image, DialogImageName->ImageName);
  1165. }
  1166. //---------------------------------------------------------------------------
  1167. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  1168. {
  1169. if (DoLoadDialogImage(Image, ImageName))
  1170. {
  1171. TDialogImageName * DialogImageName = new TDialogImageName();
  1172. DialogImageName->ImageName = ImageName;
  1173. SetRescaleFunction(Image, DialogImageRescale, DialogImageName, true);
  1174. }
  1175. }
  1176. //---------------------------------------------------------------------------
  1177. int __fastcall DialogImageSize(TForm * Form)
  1178. {
  1179. return ScaleByPixelsPerInch(32, Form);
  1180. }
  1181. //---------------------------------------------------------------------------
  1182. void __fastcall HideComponentsPanel(TForm * Form)
  1183. {
  1184. TComponent * Component = DebugNotNull(Form->FindComponent(L"ComponentsPanel"));
  1185. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Component));
  1186. DebugAssert(Panel->Align == alBottom);
  1187. int Offset = Panel->Height;
  1188. Panel->Visible = false;
  1189. Panel->Height = 0;
  1190. Form->Height -= Offset;
  1191. for (int Index = 0; Index < Form->ControlCount; Index++)
  1192. {
  1193. TControl * Control = Form->Controls[Index];
  1194. // Shift back bottom-anchored controls
  1195. // (needed for toolbar panel on Progress window and buttons on Preferences dialog),
  1196. if ((Control->Align == alNone) &&
  1197. Control->Anchors.Contains(akBottom) &&
  1198. !Control->Anchors.Contains(akTop))
  1199. {
  1200. Control->Top += Offset;
  1201. }
  1202. // Resize back all-anchored controls
  1203. // (needed for main panel on Preferences dialog),
  1204. if (Control->Anchors.Contains(akBottom) &&
  1205. Control->Anchors.Contains(akTop))
  1206. {
  1207. Control->Height += Offset;
  1208. }
  1209. }
  1210. }
  1211. //---------------------------------------------------------------------------
  1212. TIncrementalSearchState::TIncrementalSearchState()
  1213. {
  1214. Reset();
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. void TIncrementalSearchState::Reset()
  1218. {
  1219. Searching = false;
  1220. Text = EmptyStr;
  1221. HaveNext = false;
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. UnicodeString FormatIncrementalSearchStatus(const TIncrementalSearchState & SearchState)
  1225. {
  1226. UnicodeString Result =
  1227. FMTLOAD(INC_SEARCH, (DefaultStr(SearchState.Text, LoadStr(INC_SEARCH_TYPE)))) +
  1228. ((SearchState.HaveNext && DebugAlwaysTrue(!SearchState.Text.IsEmpty())) ? L" " + LoadStr(INC_NEXT_SEARCH) : EmptyStr);
  1229. return Result;
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. class TCustomDocHandler : public TComponent, public ::IDocHostUIHandler
  1233. {
  1234. public:
  1235. __fastcall TCustomDocHandler(TComponent * Owner, ICustomDoc * CustomDoc) :
  1236. TComponent(Owner), FCustomDoc(CustomDoc)
  1237. {
  1238. }
  1239. virtual __fastcall ~TCustomDocHandler()
  1240. {
  1241. // Something keeps the reference behind otherwise and calls it on WM_SETTINGCHANGE.
  1242. // Would make sense with TWebBrowserEx, which leaks. But it happens even with TWebBrowser.
  1243. FCustomDoc->SetUIHandler(NULL);
  1244. FCustomDoc->Release();
  1245. }
  1246. protected:
  1247. ICustomDoc * FCustomDoc;
  1248. #pragma warn -hid
  1249. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID ClassId, void ** Intf)
  1250. {
  1251. HRESULT Result = S_OK;
  1252. if (ClassId == IID_IUnknown)
  1253. {
  1254. *Intf = (IUnknown *)this;
  1255. }
  1256. else if (ClassId == ::IID_IDocHostUIHandler)
  1257. {
  1258. *Intf = (::IDocHostUIHandler *)this;
  1259. }
  1260. else
  1261. {
  1262. Result = E_NOINTERFACE;
  1263. }
  1264. return Result;
  1265. }
  1266. #pragma warn .hid
  1267. virtual ULONG STDMETHODCALLTYPE AddRef()
  1268. {
  1269. return -1;
  1270. }
  1271. virtual ULONG STDMETHODCALLTYPE Release()
  1272. {
  1273. return -1;
  1274. }
  1275. virtual HRESULT STDMETHODCALLTYPE ShowContextMenu(
  1276. DWORD dwID, POINT * ppt, IUnknown * pcmdtReserved, IDispatch * pdispReserved)
  1277. {
  1278. // No context menu
  1279. // (implementing IDocHostUIHandler reenabled context menu disabled by TBrowserViewer::DoContextPopup)
  1280. return S_OK;
  1281. }
  1282. virtual HRESULT STDMETHODCALLTYPE GetHostInfo(::_DOCHOSTUIINFO * Info)
  1283. {
  1284. // Setting ControlBorder is ignored with IDocHostUIHandler.
  1285. // DOCHOSTUIFLAG_DPI_AWARE does not seem to have any effect
  1286. Info->dwFlags |= DOCHOSTUIFLAG_SCROLL_NO | DOCHOSTUIFLAG_NO3DBORDER | DOCHOSTUIFLAG_DPI_AWARE;
  1287. return S_OK;
  1288. }
  1289. virtual HRESULT STDMETHODCALLTYPE ShowUI(
  1290. DWORD dwID, IOleInPlaceActiveObject * pActiveObject, IOleCommandTarget * pCommandTarget, IOleInPlaceFrame * pFrame,
  1291. IOleInPlaceUIWindow * pDoc)
  1292. {
  1293. return E_NOTIMPL;
  1294. }
  1295. virtual HRESULT STDMETHODCALLTYPE HideUI()
  1296. {
  1297. return E_NOTIMPL;
  1298. }
  1299. virtual HRESULT STDMETHODCALLTYPE UpdateUI()
  1300. {
  1301. return E_NOTIMPL;
  1302. }
  1303. virtual HRESULT STDMETHODCALLTYPE EnableModeless(BOOL fEnable)
  1304. {
  1305. return E_NOTIMPL;
  1306. }
  1307. virtual HRESULT STDMETHODCALLTYPE OnDocWindowActivate(BOOL fActivate)
  1308. {
  1309. return E_NOTIMPL;
  1310. }
  1311. virtual HRESULT STDMETHODCALLTYPE OnFrameWindowActivate(BOOL fActivate)
  1312. {
  1313. return E_NOTIMPL;
  1314. }
  1315. virtual HRESULT STDMETHODCALLTYPE ResizeBorder(LPCRECT prcBorder, IOleInPlaceUIWindow * pUIWindow, BOOL fRameWindow)
  1316. {
  1317. return E_NOTIMPL;
  1318. }
  1319. virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(LPMSG lpMsg, const GUID * pguidCmdGroup, DWORD nCmdID)
  1320. {
  1321. return E_NOTIMPL;
  1322. }
  1323. virtual HRESULT STDMETHODCALLTYPE GetOptionKeyPath(LPOLESTR * pchKey, DWORD dw)
  1324. {
  1325. return E_NOTIMPL;
  1326. }
  1327. virtual HRESULT STDMETHODCALLTYPE GetDropTarget(IDropTarget * pDropTarget, IDropTarget ** ppDropTarget)
  1328. {
  1329. return E_NOTIMPL;
  1330. }
  1331. virtual HRESULT STDMETHODCALLTYPE GetExternal(IDispatch ** ppDispatch)
  1332. {
  1333. return E_NOTIMPL;
  1334. }
  1335. virtual HRESULT STDMETHODCALLTYPE TranslateUrl(DWORD dwTranslate, OLECHAR * pchURLIn, OLECHAR ** ppchURLOut)
  1336. {
  1337. return E_NOTIMPL;
  1338. }
  1339. virtual HRESULT STDMETHODCALLTYPE FilterDataObject(IDataObject * pDO, IDataObject ** ppDORet)
  1340. {
  1341. return E_NOTIMPL;
  1342. }
  1343. };
  1344. //---------------------------------------------------------------------------
  1345. // Included only here as it defines ambiguous LONG_PTR, causing INVALID_HANDLE_VALUE to be unusable
  1346. #include <WebBrowserEx.hpp>
  1347. //---------------------------------------------------------------------------
  1348. class TBrowserViewer : public TWebBrowserEx
  1349. {
  1350. public:
  1351. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  1352. void __fastcall AddLinkHandler(
  1353. const UnicodeString & Url, TNotifyEvent Handler);
  1354. void __fastcall NavigateToUrl(const UnicodeString & Url);
  1355. TControl * LoadingPanel;
  1356. protected:
  1357. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  1358. void __fastcall DocumentComplete(
  1359. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  1360. void __fastcall BeforeNavigate2(
  1361. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  1362. const OleVariant & Flags, const OleVariant & TargetFrameName,
  1363. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  1364. bool FComplete;
  1365. std::map<UnicodeString, TNotifyEvent> FHandlers;
  1366. };
  1367. //---------------------------------------------------------------------------
  1368. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  1369. TWebBrowserEx(AOwner)
  1370. {
  1371. FComplete = false;
  1372. OnDocumentComplete = DocumentComplete;
  1373. OnBeforeNavigate2 = BeforeNavigate2;
  1374. LoadingPanel = NULL;
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. void __fastcall TBrowserViewer::AddLinkHandler(
  1378. const UnicodeString & Url, TNotifyEvent Handler)
  1379. {
  1380. FHandlers.insert(std::make_pair(Url, Handler));
  1381. }
  1382. //---------------------------------------------------------------------------
  1383. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  1384. {
  1385. // Suppress built-in context menu.
  1386. // Is ignored with IDocHostUIHandler. Needs to be overriden by ShowContextMenu.
  1387. Handled = true;
  1388. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  1389. }
  1390. //---------------------------------------------------------------------------
  1391. void __fastcall TBrowserViewer::DocumentComplete(
  1392. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  1393. {
  1394. SetBrowserDesignModeOff(this);
  1395. FComplete = true;
  1396. if (LoadingPanel != NULL)
  1397. {
  1398. LoadingPanel->Visible = false;
  1399. }
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. void __fastcall TBrowserViewer::BeforeNavigate2(
  1403. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  1404. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  1405. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  1406. {
  1407. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  1408. // opened using TWebBrowserEx::Navigate(), allow it.
  1409. // Otherwise it's user navigating, block that and open link
  1410. // in an external browser, possibly adding campaign parameters on the way.
  1411. if (FComplete)
  1412. {
  1413. Cancel = 1;
  1414. UnicodeString URL = AURL;
  1415. if (FHandlers.count(URL) > 0)
  1416. {
  1417. FHandlers[URL](this);
  1418. }
  1419. else
  1420. {
  1421. OpenBrowser(URL);
  1422. }
  1423. }
  1424. }
  1425. //---------------------------------------------------------------------------
  1426. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  1427. {
  1428. FComplete = false;
  1429. Navigate(Url.c_str());
  1430. }
  1431. //---------------------------------------------------------------------------
  1432. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  1433. {
  1434. TPanel * Result = CreateBlankPanel(Parent);
  1435. Result->Parent = Parent;
  1436. Result->Align = alClient;
  1437. Result->Caption = Label;
  1438. return Result;
  1439. }
  1440. //---------------------------------------------------------------------------
  1441. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  1442. {
  1443. TBrowserViewer * Result = new TBrowserViewer(Parent);
  1444. // TWebBrowserEx has its own unrelated Name and Parent properties.
  1445. // The name is used in DownloadUpdate().
  1446. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  1447. static_cast<TWinControl *>(Result)->Parent = Parent;
  1448. Result->Align = alClient;
  1449. // Is ignored with IDocHostUIHandler. Needs to be overriden by DOCHOSTUIFLAG_NO3DBORDER in GetHostInfo.
  1450. Result->ControlBorder = cbNone;
  1451. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  1452. return Result;
  1453. }
  1454. //---------------------------------------------------------------------------
  1455. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  1456. {
  1457. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  1458. {
  1459. WebBrowser->Document2->designMode = L"Off";
  1460. }
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  1464. const UnicodeString & Url, TNotifyEvent Handler)
  1465. {
  1466. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  1467. if (DebugAlwaysTrue(BrowserViewer != NULL))
  1468. {
  1469. BrowserViewer->AddLinkHandler(Url, Handler);
  1470. }
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  1474. {
  1475. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  1476. if (DebugAlwaysTrue(BrowserViewer != NULL))
  1477. {
  1478. BrowserViewer->NavigateToUrl(Url);
  1479. }
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. void ReadyBrowserForStreaming(TWebBrowserEx * WebBrowser)
  1483. {
  1484. // This creates TWebBrowserEx::Document, which we need to stream in an in-memory document
  1485. NavigateBrowserToUrl(WebBrowser, L"about:blank");
  1486. // Needs to be followed by WaitBrowserToIdle
  1487. }
  1488. //---------------------------------------------------------------------------
  1489. void WaitBrowserToIdle(TWebBrowserEx * WebBrowser)
  1490. {
  1491. while (WebBrowser->ReadyState < ::READYSTATE_INTERACTIVE)
  1492. {
  1493. Application->ProcessMessages();
  1494. }
  1495. }
  1496. //---------------------------------------------------------------------------
  1497. void HideBrowserScrollbars(TWebBrowserEx * WebBrowser)
  1498. {
  1499. ICustomDoc * CustomDoc = NULL;
  1500. if (DebugAlwaysTrue(WebBrowser->Document != NULL) &&
  1501. SUCCEEDED(WebBrowser->Document->QueryInterface(&CustomDoc)) &&
  1502. DebugAlwaysTrue(CustomDoc != NULL))
  1503. {
  1504. TCustomDocHandler * Handler = new TCustomDocHandler(WebBrowser, CustomDoc);
  1505. CustomDoc->SetUIHandler(Handler);
  1506. }
  1507. }
  1508. //---------------------------------------------------------------------------
  1509. bool CopyTextFromBrowser(TWebBrowserEx * WebBrowser, UnicodeString & Text)
  1510. {
  1511. WebBrowser->SelectAll();
  1512. WebBrowser->CopyToClipBoard();
  1513. bool Result = NonEmptyTextFromClipboard(Text);
  1514. WebBrowser->DoCommand(L"UNSELECT");
  1515. return Result;
  1516. }
  1517. //---------------------------------------------------------------------------
  1518. UnicodeString GenerateAppHtmlPage(TFont * Font, TPanel * Parent, const UnicodeString & Body, bool Seamless)
  1519. {
  1520. UnicodeString Result =
  1521. L"<!DOCTYPE html>\n"
  1522. L"<meta charset=\"utf-8\">\n"
  1523. L"<html>\n"
  1524. L"<head>\n"
  1525. L"<style>\n"
  1526. L"\n"
  1527. L"body\n"
  1528. L"{\n"
  1529. L" font-family: '" + Font->Name + L"';\n"
  1530. L" margin: " + UnicodeString(Seamless ? L"0" : L"0.5em") + L";\n"
  1531. L" background-color: " + ColorToWebColorStr(Parent->Color) + L";\n" +
  1532. UnicodeString(Seamless ? L" overflow: hidden;\n" : L"") +
  1533. L"}\n"
  1534. L"\n"
  1535. L"body\n"
  1536. L"{\n"
  1537. L" font-size: " + IntToStr(Font->Size) + L"pt;\n"
  1538. L"}\n"
  1539. L"\n"
  1540. L"p\n"
  1541. L"{\n"
  1542. L" margin-top: 0;\n"
  1543. L" margin-bottom: 1em;\n"
  1544. L"}\n"
  1545. L"\n"
  1546. L"a, a:visited, a:hover, a:visited, a:current\n"
  1547. L"{\n"
  1548. L" color: " + ColorToWebColorStr(LinkColor) + L";\n"
  1549. L"}\n"
  1550. L"</style>\n"
  1551. L"</head>\n"
  1552. L"<body>\n" +
  1553. Body +
  1554. L"</body>\n"
  1555. L"</html>\n";
  1556. return Result;
  1557. }
  1558. //---------------------------------------------------------------------------
  1559. void LoadBrowserDocument(TWebBrowserEx * WebBrowser, const UnicodeString & Document)
  1560. {
  1561. std::unique_ptr<TMemoryStream> DocumentStream(new TMemoryStream());
  1562. UTF8String DocumentUTF8 = UTF8String(Document);
  1563. DocumentStream->Write(DocumentUTF8.c_str(), DocumentUTF8.Length());
  1564. DocumentStream->Seek(0, 0);
  1565. // For stream-loaded document, when set only after loading from OnDocumentComplete,
  1566. // browser stops working
  1567. SetBrowserDesignModeOff(WebBrowser);
  1568. TStreamAdapter * DocumentStreamAdapter = new TStreamAdapter(DocumentStream.get(), soReference);
  1569. IPersistStreamInit * PersistStreamInit = NULL;
  1570. if (DebugAlwaysTrue(WebBrowser->Document != NULL) &&
  1571. SUCCEEDED(WebBrowser->Document->QueryInterface(IID_IPersistStreamInit, (void **)&PersistStreamInit)) &&
  1572. DebugAlwaysTrue(PersistStreamInit != NULL))
  1573. {
  1574. PersistStreamInit->Load(static_cast<_di_IStream>(*DocumentStreamAdapter));
  1575. PersistStreamInit->Release();
  1576. }
  1577. }
  1578. //---------------------------------------------------------------------------
  1579. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  1580. {
  1581. for (int Index = 0; Index < Root->ComponentCount; Index++)
  1582. {
  1583. TComponent * Component = Root->Components[Index];
  1584. if (CompareText(Component->Name, Name) == 0)
  1585. {
  1586. return Component;
  1587. }
  1588. Component = FindComponentRecursively(Component, Name);
  1589. if (Component != NULL)
  1590. {
  1591. return Component;
  1592. }
  1593. }
  1594. return NULL;
  1595. }
  1596. //---------------------------------------------------------------------------
  1597. void __fastcall GetInstrutionsTheme(
  1598. TColor & MainInstructionColor, HFONT & MainInstructionFont, HFONT & InstructionFont)
  1599. {
  1600. MainInstructionColor = Graphics::clNone;
  1601. MainInstructionFont = 0;
  1602. InstructionFont = 0;
  1603. HTHEME Theme = OpenThemeData(0, L"TEXTSTYLE");
  1604. if (Theme != NULL)
  1605. {
  1606. LOGFONT AFont;
  1607. COLORREF AColor;
  1608. memset(&AFont, 0, sizeof(AFont));
  1609. // Using Canvas->Handle in the 2nd argument we can get scaled font,
  1610. // but at this point the form is sometime not scaled yet (difference is particularly for standalone messages like
  1611. // /UninstallCleanup), so the results are inconsistent.
  1612. if (GetThemeFont(Theme, NULL, TEXT_MAININSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1613. {
  1614. MainInstructionFont = CreateFontIndirect(&AFont);
  1615. }
  1616. if (GetThemeColor(Theme, TEXT_MAININSTRUCTION, 0, TMT_TEXTCOLOR, &AColor) == S_OK)
  1617. {
  1618. MainInstructionColor = (TColor)AColor;
  1619. }
  1620. memset(&AFont, 0, sizeof(AFont));
  1621. if (GetThemeFont(Theme, NULL, TEXT_INSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1622. {
  1623. InstructionFont = CreateFontIndirect(&AFont);
  1624. }
  1625. CloseThemeData(Theme);
  1626. }
  1627. }
  1628. //---------------------------------------------------------------------------
  1629. TLocalCustomCommand::TLocalCustomCommand()
  1630. {
  1631. }
  1632. //---------------------------------------------------------------------------
  1633. TLocalCustomCommand::TLocalCustomCommand(
  1634. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  1635. TFileCustomCommand(Data, RemotePath)
  1636. {
  1637. FLocalPath = LocalPath;
  1638. }
  1639. //---------------------------------------------------------------------------
  1640. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  1641. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  1642. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  1643. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  1644. {
  1645. FLocalPath = LocalPath;
  1646. FLocalFileName = LocalFileName;
  1647. }
  1648. //---------------------------------------------------------------------------
  1649. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  1650. {
  1651. int Len;
  1652. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  1653. {
  1654. Len = 2;
  1655. }
  1656. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  1657. {
  1658. Len = 3;
  1659. }
  1660. else
  1661. {
  1662. Len = TFileCustomCommand::PatternLen(Command, Index);
  1663. }
  1664. return Len;
  1665. }
  1666. //---------------------------------------------------------------------------
  1667. bool __fastcall TLocalCustomCommand::PatternReplacement(
  1668. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  1669. {
  1670. bool Result;
  1671. if (Pattern == L"!\\")
  1672. {
  1673. // When used as "!\" in an argument to PowerShell, the trailing \ would escape the ",
  1674. // so we exclude it
  1675. Replacement = ExcludeTrailingBackslash(FLocalPath);
  1676. Result = true;
  1677. }
  1678. else if (Pattern == L"!^!")
  1679. {
  1680. Replacement = FLocalFileName;
  1681. Result = true;
  1682. }
  1683. else
  1684. {
  1685. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  1686. }
  1687. return Result;
  1688. }
  1689. //---------------------------------------------------------------------------
  1690. void __fastcall TLocalCustomCommand::DelimitReplacement(
  1691. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  1692. {
  1693. // never delimit local commands
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  1697. {
  1698. return FindPattern(Command, L'^');
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  1702. {
  1703. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. //---------------------------------------------------------------------------
  1707. typedef std::set<TDataModule *> TImagesModules;
  1708. static TImagesModules ImagesModules;
  1709. static std::map<int, TPngImageList *> AnimationsImages;
  1710. static std::map<int, TImageList *> ButtonImages;
  1711. static std::map<int, TPngImageList *> DialogImages;
  1712. //---------------------------------------------------------------------------
  1713. int __fastcall DoNormalizePixelsPerInch(int PixelsPerInch, bool Larger)
  1714. {
  1715. if (PixelsPerInch >= 192)
  1716. {
  1717. PixelsPerInch = 192;
  1718. }
  1719. else if (PixelsPerInch >= 144)
  1720. {
  1721. PixelsPerInch = Larger ? 192 : 144;
  1722. }
  1723. else if (PixelsPerInch >= 120)
  1724. {
  1725. PixelsPerInch = Larger ? 144 : 120;
  1726. }
  1727. else
  1728. {
  1729. PixelsPerInch = Larger ? 120 : 96;
  1730. }
  1731. return PixelsPerInch;
  1732. }
  1733. //---------------------------------------------------------------------------
  1734. int NormalizePixelsPerInch(int PixelsPerInch)
  1735. {
  1736. return DoNormalizePixelsPerInch(PixelsPerInch, false);
  1737. }
  1738. //---------------------------------------------------------------------------
  1739. int LargerPixelsPerInch(int PixelsPerInch, int Larger)
  1740. {
  1741. int Result = PixelsPerInch;
  1742. while (Larger > 0)
  1743. {
  1744. Result = DoNormalizePixelsPerInch(Result, true);
  1745. Larger--;
  1746. }
  1747. return Result;
  1748. }
  1749. //---------------------------------------------------------------------------
  1750. static int __fastcall NeedImagesModule(TControl * Control)
  1751. {
  1752. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  1753. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  1754. {
  1755. TDataModule * ImagesModule;
  1756. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  1757. try
  1758. {
  1759. if (PixelsPerInch == 192)
  1760. {
  1761. ImagesModule = new TAnimations192Module(Application);
  1762. }
  1763. else if (PixelsPerInch == 144)
  1764. {
  1765. ImagesModule = new TAnimations144Module(Application);
  1766. }
  1767. else if (PixelsPerInch == 120)
  1768. {
  1769. ImagesModule = new TAnimations120Module(Application);
  1770. }
  1771. else
  1772. {
  1773. DebugAssert(PixelsPerInch == 96);
  1774. ImagesModule = new TAnimations96Module(Application);
  1775. }
  1776. ImagesModules.insert(ImagesModule);
  1777. TPngImageList * AAnimationImages =
  1778. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  1779. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  1780. TImageList * AButtonImages =
  1781. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  1782. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  1783. TPngImageList * ADialogImages =
  1784. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  1785. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  1786. }
  1787. __finally
  1788. {
  1789. GUIConfiguration->ChangeResourceModule(ResourceModule);
  1790. }
  1791. }
  1792. return PixelsPerInch;
  1793. }
  1794. //---------------------------------------------------------------------------
  1795. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  1796. {
  1797. int PixelsPerInch = NeedImagesModule(Control);
  1798. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  1799. }
  1800. //---------------------------------------------------------------------------
  1801. TImageList * __fastcall GetButtonImages(TControl * Control)
  1802. {
  1803. int PixelsPerInch = NeedImagesModule(Control);
  1804. return DebugNotNull(ButtonImages[PixelsPerInch]);
  1805. }
  1806. //---------------------------------------------------------------------------
  1807. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  1808. {
  1809. int PixelsPerInch = NeedImagesModule(Control);
  1810. return DebugNotNull(DialogImages[PixelsPerInch]);
  1811. }
  1812. //---------------------------------------------------------------------------
  1813. void __fastcall ReleaseImagesModules()
  1814. {
  1815. TImagesModules::iterator i = ImagesModules.begin();
  1816. while (i != ImagesModules.end())
  1817. {
  1818. delete (*i);
  1819. i++;
  1820. }
  1821. ImagesModules.clear();
  1822. }
  1823. //---------------------------------------------------------------------------
  1824. __fastcall TFrameAnimation::TFrameAnimation()
  1825. {
  1826. FFirstFrame = -1;
  1827. }
  1828. //---------------------------------------------------------------------------
  1829. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1830. {
  1831. FName = Name;
  1832. FPaintBox = PaintBox;
  1833. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1834. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1835. FPaintBox->OnPaint = PaintBoxPaint;
  1836. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1837. DoInit();
  1838. }
  1839. //---------------------------------------------------------------------------
  1840. void __fastcall TFrameAnimation::DoInit()
  1841. {
  1842. FImageList = GetAnimationsImages(FPaintBox);
  1843. FFirstFrame = -1;
  1844. FFirstLoopFrame = -1;
  1845. FPaintBox->Width = FImageList->Width;
  1846. FPaintBox->Height = FImageList->Height;
  1847. if (!FName.IsEmpty())
  1848. {
  1849. int Frame = 0;
  1850. while (Frame < FImageList->PngImages->Count)
  1851. {
  1852. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1853. UnicodeString FrameName;
  1854. FrameName = CutToChar(FrameData, L'_', false);
  1855. if (SameText(FName, FrameName))
  1856. {
  1857. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1858. if (FFirstFrame < 0)
  1859. {
  1860. FFirstFrame = Frame;
  1861. }
  1862. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1863. {
  1864. FFirstLoopFrame = Frame;
  1865. }
  1866. FLastFrame = Frame;
  1867. }
  1868. else
  1869. {
  1870. if (FFirstFrame >= 0)
  1871. {
  1872. // optimization
  1873. break;
  1874. }
  1875. }
  1876. Frame++;
  1877. }
  1878. DebugAssert(FFirstFrame >= 0);
  1879. DebugAssert(FFirstLoopFrame >= 0);
  1880. }
  1881. Stop();
  1882. }
  1883. //---------------------------------------------------------------------------
  1884. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1885. {
  1886. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1887. FrameAnimation->Rescale();
  1888. }
  1889. //---------------------------------------------------------------------------
  1890. void __fastcall TFrameAnimation::Rescale()
  1891. {
  1892. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1893. DoInit();
  1894. if (Started)
  1895. {
  1896. Start();
  1897. }
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. void __fastcall TFrameAnimation::Start()
  1901. {
  1902. if (FFirstFrame >= 0)
  1903. {
  1904. FNextFrameTick = GetTickCount();
  1905. CalculateNextFrameTick();
  1906. if (FTimer == NULL)
  1907. {
  1908. FTimer = new TTimer(GetParentForm(FPaintBox));
  1909. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1910. FTimer->OnTimer = Timer;
  1911. }
  1912. else
  1913. {
  1914. // reset timer
  1915. FTimer->Enabled = false;
  1916. FTimer->Enabled = true;
  1917. }
  1918. }
  1919. }
  1920. //---------------------------------------------------------------------------
  1921. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1922. {
  1923. Animate();
  1924. }
  1925. //---------------------------------------------------------------------------
  1926. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1927. {
  1928. if (FFirstFrame >= 0)
  1929. {
  1930. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1931. DebugUsedParam(Sender);
  1932. DebugAssert(FPaintBox == Sender);
  1933. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1934. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1935. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1936. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1937. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1938. Bitmap->Canvas->FillRect(Rect);
  1939. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1940. DebugAssert(Graphic->Width == FPaintBox->Width);
  1941. DebugAssert(Graphic->Height == FPaintBox->Height);
  1942. Bitmap->Canvas->Draw(0, 0, Graphic);
  1943. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1944. }
  1945. FPainted = true;
  1946. }
  1947. //---------------------------------------------------------------------------
  1948. void __fastcall TFrameAnimation::Repaint()
  1949. {
  1950. FPainted = false;
  1951. // If the form is not showing yet, the Paint() is not even called
  1952. FPaintBox->Repaint();
  1953. if (!FPainted)
  1954. {
  1955. // Paint later, alternatively we may keep trying Repaint() in Animate().
  1956. // See also a hack in TAuthenticateForm::Log.
  1957. FPaintBox->Invalidate();
  1958. }
  1959. }
  1960. //---------------------------------------------------------------------------
  1961. void __fastcall TFrameAnimation::Stop()
  1962. {
  1963. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1964. FCurrentFrame = FFirstFrame;
  1965. Repaint();
  1966. if (FTimer != NULL)
  1967. {
  1968. FTimer->Enabled = false;
  1969. }
  1970. }
  1971. //---------------------------------------------------------------------------
  1972. void __fastcall TFrameAnimation::Animate()
  1973. {
  1974. if (FFirstFrame >= 0)
  1975. {
  1976. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1977. DWORD TickCount = GetTickCount();
  1978. // Keep in sync with an opposite condition at the end of the loop.
  1979. // We may skip some frames if we got stalled for a while
  1980. while (TickCount >= FNextFrameTick)
  1981. {
  1982. if (FCurrentFrame >= FLastFrame)
  1983. {
  1984. FCurrentFrame = FFirstLoopFrame;
  1985. }
  1986. else
  1987. {
  1988. FCurrentFrame++;
  1989. }
  1990. CalculateNextFrameTick();
  1991. Repaint();
  1992. }
  1993. }
  1994. }
  1995. //---------------------------------------------------------------------------
  1996. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1997. {
  1998. return FImageList->PngImages->Items[FCurrentFrame];
  1999. }
  2000. //---------------------------------------------------------------------------
  2001. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  2002. {
  2003. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  2004. UnicodeString Duration = ImageItem->Name;
  2005. CutToChar(Duration, L'_', false);
  2006. // skip index (is not really used)
  2007. CutToChar(Duration, L'_', false);
  2008. // This should overflow, when tick count wraps.
  2009. FNextFrameTick += StrToInt(Duration) * 10;
  2010. }
  2011. //---------------------------------------------------------------------------
  2012. //---------------------------------------------------------------------------
  2013. // Hints use:
  2014. // - Cleanup list tooltip (multi line)
  2015. // - Combo edit button
  2016. // - Transfer settings label (multi line, follows label size and font)
  2017. // - HintLabel (hint and persistent hint, multi line)
  2018. // - status bar hints
  2019. //---------------------------------------------------------------------------
  2020. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  2021. THintWindow(Owner)
  2022. {
  2023. FParentPainting = false;
  2024. }
  2025. //---------------------------------------------------------------------------
  2026. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  2027. {
  2028. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  2029. }
  2030. //---------------------------------------------------------------------------
  2031. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  2032. {
  2033. return
  2034. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  2035. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL) ||
  2036. (HintControl->Perform(WM_WANTS_SCREEN_TIPS, 0, 0) == 1);
  2037. }
  2038. //---------------------------------------------------------------------------
  2039. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  2040. {
  2041. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  2042. }
  2043. //---------------------------------------------------------------------------
  2044. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  2045. {
  2046. int Result;
  2047. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  2048. {
  2049. Result = 3;
  2050. }
  2051. else
  2052. {
  2053. Result = 6;
  2054. }
  2055. Result = ScaleByTextHeight(HintControl, Result);
  2056. return Result;
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  2060. {
  2061. TFont * Result;
  2062. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  2063. {
  2064. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  2065. }
  2066. else
  2067. {
  2068. FScaledHintFont.reset(new TFont());
  2069. FScaledHintFont->Assign(Screen->HintFont);
  2070. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  2071. Result = FScaledHintFont.get();
  2072. }
  2073. return Result;
  2074. }
  2075. //---------------------------------------------------------------------------
  2076. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  2077. {
  2078. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  2079. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  2080. }
  2081. //---------------------------------------------------------------------------
  2082. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  2083. {
  2084. TControl * HintControl = GetHintControl(AData);
  2085. int Margin = GetMargin(HintControl, AHint);
  2086. UnicodeString ShortHint;
  2087. UnicodeString LongHint;
  2088. SplitHint(HintControl, AHint, ShortHint, LongHint);
  2089. Canvas->Font->Assign(GetFont(HintControl, AHint));
  2090. // from XE6 Vcl.ScreenTips.pas, but absent in 11
  2091. const cScreenTipTextOnlyWidth = 210;
  2092. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  2093. int LongHintMargin = 0; // shut up
  2094. bool HasLongHint = !LongHint.IsEmpty();
  2095. if (HasLongHint)
  2096. {
  2097. // double-margin on the right
  2098. LongHintMargin = (3 * Margin);
  2099. MaxWidth = ScreenTipTextOnlyWidth - LongHintMargin;
  2100. }
  2101. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  2102. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  2103. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  2104. if (ShortHint.Pos(L"\n") > 0)
  2105. {
  2106. MaxWidth *= 2;
  2107. }
  2108. bool HintPopup = HasLabelHintPopup(HintControl, AHint);
  2109. if (HintPopup)
  2110. {
  2111. MaxWidth = HintControl->Width;
  2112. }
  2113. if (UseBoldShortHint(HintControl))
  2114. {
  2115. Canvas->Font->Style = TFontStyles() << fsBold;
  2116. }
  2117. TRect ShortRect(0, 0, MaxWidth, 0);
  2118. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  2119. Canvas->Font->Style = TFontStyles();
  2120. TRect Result;
  2121. if (!HasLongHint)
  2122. {
  2123. Result = ShortRect;
  2124. if (HintPopup)
  2125. {
  2126. Result.Right = MaxWidth + 2 * Margin;
  2127. }
  2128. else
  2129. {
  2130. Result.Right += 3 * Margin;
  2131. }
  2132. Result.Bottom += 2 * Margin;
  2133. }
  2134. else
  2135. {
  2136. const int LongIndentation = Margin * 3 / 2;
  2137. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  2138. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  2139. Result.Right = Max(ScreenTipTextOnlyWidth, LongRect.Right + LongIndentation + LongHintMargin);
  2140. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  2141. }
  2142. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  2143. Result.Bottom -= 4;
  2144. return Result;
  2145. }
  2146. //---------------------------------------------------------------------------
  2147. void __fastcall TScreenTipHintWindow::SplitHint(
  2148. TControl * HintControl, const UnicodeString & Hint, UnicodeString & ShortHint, UnicodeString & LongHint)
  2149. {
  2150. if (HasLabelHintPopup(HintControl, Hint))
  2151. {
  2152. ShortHint = HintControl->Hint;
  2153. }
  2154. else
  2155. {
  2156. ShortHint = GetShortHint(Hint);
  2157. LongHint = GetLongHintIfAny(Hint);
  2158. }
  2159. }
  2160. //---------------------------------------------------------------------------
  2161. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  2162. {
  2163. FHintControl = GetHintControl(AData);
  2164. SplitHint(FHintControl, AHint, FShortHint, FLongHint);
  2165. FMargin = GetMargin(FHintControl, AHint);
  2166. FHintPopup = HasLabelHintPopup(FHintControl, AHint);
  2167. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  2168. TRect Rect = ARect;
  2169. if (FHintPopup)
  2170. {
  2171. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  2172. }
  2173. if (IsPathLabel(FHintControl))
  2174. {
  2175. Rect.Offset(-FMargin, -FMargin);
  2176. }
  2177. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  2178. }
  2179. //---------------------------------------------------------------------------
  2180. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  2181. {
  2182. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  2183. }
  2184. //---------------------------------------------------------------------------
  2185. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  2186. {
  2187. UnicodeString Result;
  2188. int P = Pos(L"|", AHint);
  2189. if (P > 0)
  2190. {
  2191. Result = GetLongHint(AHint);
  2192. }
  2193. return Result;
  2194. }
  2195. //---------------------------------------------------------------------------
  2196. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  2197. {
  2198. TMessage * Message = static_cast<TMessage*>(AMessage);
  2199. switch (Message->Msg)
  2200. {
  2201. case WM_GETTEXTLENGTH:
  2202. if (FParentPainting)
  2203. {
  2204. // make THintWindow::Paint() not paint the Caption
  2205. Message->Result = 0;
  2206. }
  2207. else
  2208. {
  2209. THintWindow::Dispatch(AMessage);
  2210. }
  2211. break;
  2212. default:
  2213. THintWindow::Dispatch(AMessage);
  2214. break;
  2215. }
  2216. }
  2217. //---------------------------------------------------------------------------
  2218. void __fastcall TScreenTipHintWindow::Paint()
  2219. {
  2220. // paint frame/background
  2221. {
  2222. TAutoFlag ParentPaintingFlag(FParentPainting);
  2223. THintWindow::Paint();
  2224. }
  2225. const int Flags = GetTextFlags(this);
  2226. const int Margin = FMargin - 1; // 1 = border
  2227. TRect Rect = ClientRect;
  2228. Rect.Inflate(-Margin, -Margin);
  2229. if (!FHintPopup)
  2230. {
  2231. Rect.Right -= FMargin;
  2232. }
  2233. if (UseBoldShortHint(FHintControl))
  2234. {
  2235. Canvas->Font->Style = TFontStyles() << fsBold;
  2236. }
  2237. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  2238. TRect ShortRect = Rect;
  2239. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  2240. Canvas->Font->Style = TFontStyles();
  2241. if (!FLongHint.IsEmpty())
  2242. {
  2243. Rect.Left += FMargin * 3 / 2;
  2244. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  2245. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  2246. }
  2247. }
  2248. //---------------------------------------------------------------------------
  2249. //---------------------------------------------------------------------------
  2250. __fastcall TNewRichEdit::TNewRichEdit(TComponent * AOwner) :
  2251. TRichEdit(AOwner),
  2252. FLibrary(0)
  2253. {
  2254. }
  2255. //---------------------------------------------------------------------------
  2256. void __fastcall TNewRichEdit::CreateParams(TCreateParams & Params)
  2257. {
  2258. UnicodeString RichEditModuleName(L"MSFTEDIT.DLL");
  2259. long int OldError;
  2260. OldError = SetErrorMode(SEM_NOOPENFILEERRORBOX);
  2261. FLibrary = LoadLibrary(RichEditModuleName.c_str());
  2262. SetErrorMode(OldError);
  2263. // No fallback, MSFTEDIT.DLL is available since Windows XP
  2264. // https://learn.microsoft.com/en-us/archive/blogs/murrays/richedit-versions
  2265. if (FLibrary == 0)
  2266. {
  2267. throw Exception(FORMAT(L"Cannot load %s", (RichEditModuleName)));
  2268. }
  2269. TCustomMemo::CreateParams(Params);
  2270. // MSDN says that we should use MSFTEDIT_CLASS to load Rich Edit 4.1:
  2271. // https://learn.microsoft.com/en-us/windows/win32/controls/about-rich-edit-controls
  2272. // But MSFTEDIT_CLASS is defined as "RICHEDIT50W",
  2273. // so not sure what version we are loading.
  2274. // Seem to work on Windows XP SP3.
  2275. CreateSubClass(Params, MSFTEDIT_CLASS);
  2276. }
  2277. //---------------------------------------------------------------------------
  2278. void __fastcall TNewRichEdit::CreateWnd()
  2279. {
  2280. TRichEdit::CreateWnd();
  2281. SendMessage(Handle, EM_SETEDITSTYLEEX, 0, SES_EX_HANDLEFRIENDLYURL);
  2282. }
  2283. //---------------------------------------------------------------------------
  2284. void __fastcall TNewRichEdit::DestroyWnd()
  2285. {
  2286. TRichEdit::DestroyWnd();
  2287. if (FLibrary != 0)
  2288. {
  2289. FreeLibrary(FLibrary);
  2290. }
  2291. }
  2292. //---------------------------------------------------------------------------
  2293. static int HideAccelFlag(TControl * Control)
  2294. {
  2295. //ask the top level window about its UI state
  2296. while (Control->Parent != NULL)
  2297. {
  2298. Control = Control->Parent;
  2299. }
  2300. int Result;
  2301. if (FLAGSET(Control->Perform(WM_QUERYUISTATE, 0, 0), UISF_HIDEACCEL))
  2302. {
  2303. Result = DT_HIDEPREFIX;
  2304. }
  2305. else
  2306. {
  2307. Result = 0;
  2308. }
  2309. return Result;
  2310. }
  2311. //---------------------------------------------------------------------------
  2312. __fastcall TUIStateAwareLabel::TUIStateAwareLabel(TComponent * AOwner) :
  2313. TLabel(AOwner)
  2314. {
  2315. }
  2316. //---------------------------------------------------------------------------
  2317. void __fastcall TUIStateAwareLabel::DoDrawText(TRect & Rect, int Flags)
  2318. {
  2319. if (ShowAccelChar)
  2320. {
  2321. Flags = Flags | HideAccelFlag(this);
  2322. }
  2323. TLabel::DoDrawText(Rect, Flags);
  2324. }
  2325. //---------------------------------------------------------------------------
  2326. void __fastcall TUIStateAwareLabel::Dispatch(void * AMessage)
  2327. {
  2328. TMessage * Message = static_cast<TMessage*>(AMessage);
  2329. // WORKAROUND: Particularly when focusing csDropDownList-style combobox via label, there's no visual feedback
  2330. // that the combobox was selected (strangely, there is, when the previous focus was on TTreeView).
  2331. // For consistency, we enable focus display for all controls types (like checkboxes).
  2332. if (Message->Msg == CM_DIALOGCHAR)
  2333. {
  2334. bool WasFocused = (FocusControl != NULL) ? FocusControl->Focused() : false;
  2335. TLabel::Dispatch(AMessage);
  2336. if (!WasFocused && (FocusControl != NULL) && FocusControl->Focused())
  2337. {
  2338. TCustomForm * ParentForm = GetParentForm(this);
  2339. if (ParentForm != NULL)
  2340. {
  2341. ParentForm->Perform(WM_CHANGEUISTATE, MAKELONG(UIS_CLEAR, UISF_HIDEFOCUS), 0);
  2342. }
  2343. }
  2344. }
  2345. else
  2346. {
  2347. TLabel::Dispatch(AMessage);
  2348. }
  2349. }
  2350. //---------------------------------------------------------------------------
  2351. void __fastcall FindComponentClass(
  2352. void *, TReader *, const UnicodeString DebugUsedArg(ClassName), TComponentClass & ComponentClass)
  2353. {
  2354. if (ComponentClass == __classid(TLabel))
  2355. {
  2356. ComponentClass = __classid(TUIStateAwareLabel);
  2357. }
  2358. else if (ComponentClass == __classid(TComboBox))
  2359. {
  2360. ComponentClass = __classid(TUIStateAwareComboBox);
  2361. }
  2362. }
  2363. //---------------------------------------------------------------------------
  2364. bool CanShowTimeEstimate(TDateTime StartTime)
  2365. {
  2366. return (SecondsBetween(StartTime, Now()) >= 3);
  2367. }
  2368. //---------------------------------------------------------------------------
  2369. class TSystemRequiredThread : public TSignalThread
  2370. {
  2371. public:
  2372. TSystemRequiredThread();
  2373. void Required();
  2374. protected:
  2375. virtual bool __fastcall WaitForEvent();
  2376. virtual void __fastcall ProcessEvent();
  2377. private:
  2378. bool FRequired;
  2379. TDateTime FLastRequired;
  2380. };
  2381. //---------------------------------------------------------------------------
  2382. std::unique_ptr<TCriticalSection> SystemRequiredThreadSection(TraceInitPtr(new TCriticalSection()));
  2383. TSystemRequiredThread * SystemRequiredThread = NULL;
  2384. //---------------------------------------------------------------------------
  2385. TSystemRequiredThread::TSystemRequiredThread() :
  2386. TSignalThread(true), FRequired(false)
  2387. {
  2388. }
  2389. //---------------------------------------------------------------------------
  2390. void TSystemRequiredThread::Required()
  2391. {
  2392. // guarded in SystemRequired()
  2393. FLastRequired = Now();
  2394. TriggerEvent();
  2395. }
  2396. //---------------------------------------------------------------------------
  2397. bool __fastcall TSystemRequiredThread::WaitForEvent()
  2398. {
  2399. const int ExpireInterval = 5000;
  2400. bool Result = (TSignalThread::WaitForEvent(ExpireInterval) > 0);
  2401. if (!Result && !FTerminated)
  2402. {
  2403. TGuard Guard(SystemRequiredThreadSection.get());
  2404. if (!FTerminated && FRequired &&
  2405. (MilliSecondsBetween(Now(), FLastRequired) > ExpireInterval))
  2406. {
  2407. AppLog(L"System is not required");
  2408. SetThreadExecutionState(ES_CONTINUOUS);
  2409. FLastRequired = TDateTime();
  2410. FRequired = false;
  2411. }
  2412. }
  2413. return Result;
  2414. }
  2415. //---------------------------------------------------------------------------
  2416. void __fastcall TSystemRequiredThread::ProcessEvent()
  2417. {
  2418. TGuard Guard(SystemRequiredThreadSection.get());
  2419. if (!FRequired &&
  2420. (FLastRequired != TDateTime()))
  2421. {
  2422. AppLog(L"System is required");
  2423. SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
  2424. FRequired = true;
  2425. }
  2426. }
  2427. //---------------------------------------------------------------------------
  2428. void SystemRequired()
  2429. {
  2430. if (IsWin11())
  2431. {
  2432. TGuard Guard(SystemRequiredThreadSection.get());
  2433. if (SystemRequiredThread == NULL)
  2434. {
  2435. AppLog(L"Starting system required thread");
  2436. SystemRequiredThread = new TSystemRequiredThread();
  2437. SystemRequiredThread->Start();
  2438. }
  2439. SystemRequiredThread->Required();
  2440. }
  2441. else
  2442. {
  2443. SetThreadExecutionState(ES_SYSTEM_REQUIRED);
  2444. }
  2445. }
  2446. //---------------------------------------------------------------------------
  2447. void GUIFinalize()
  2448. {
  2449. TPuttyCleanupThread::Finalize();
  2450. TSystemRequiredThread * Thread;
  2451. {
  2452. TGuard Guard(SystemRequiredThreadSection.get());
  2453. Thread = SystemRequiredThread;
  2454. SystemRequiredThread = NULL;
  2455. }
  2456. if (Thread != NULL)
  2457. {
  2458. AppLog(L"Stopping system required thread");
  2459. Thread->Terminate();
  2460. Thread->WaitFor();
  2461. delete Thread;
  2462. }
  2463. }