GUITools.cpp 102 KB

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