GUITools.cpp 83 KB

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