GUITools.cpp 91 KB

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