GUITools.cpp 100 KB

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