GUITools.cpp 77 KB

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