GUITools.cpp 99 KB

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