GUITools.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397
  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. UnicodeString GenerateAppHtmlPage(TFont * Font, TPanel * Parent, const UnicodeString & Body, bool Seamless)
  1348. {
  1349. UnicodeString Result =
  1350. L"<!DOCTYPE html>\n"
  1351. L"<meta charset=\"utf-8\">\n"
  1352. L"<html>\n"
  1353. L"<head>\n"
  1354. L"<style>\n"
  1355. L"\n"
  1356. L"body\n"
  1357. L"{\n"
  1358. L" font-family: '" + Font->Name + L"';\n"
  1359. L" margin: " + UnicodeString(Seamless ? L"0" : L"0.5em") + L";\n"
  1360. L" background-color: " + ColorToWebColorStr(Parent->Color) + L";\n" +
  1361. UnicodeString(Seamless ? L" overflow: hidden;\n" : L"") +
  1362. L"}\n"
  1363. L"\n"
  1364. L"body\n"
  1365. L"{\n"
  1366. L" font-size: " + IntToStr(Font->Size) + L"pt;\n"
  1367. L"}\n"
  1368. L"\n"
  1369. L"p\n"
  1370. L"{\n"
  1371. L" margin-top: 0;\n"
  1372. L" margin-bottom: 1em;\n"
  1373. L"}\n"
  1374. L"\n"
  1375. L"a, a:visited, a:hover, a:visited, a:current\n"
  1376. L"{\n"
  1377. L" color: " + ColorToWebColorStr(LinkColor) + L";\n"
  1378. L"}\n"
  1379. L"</style>\n"
  1380. L"</head>\n"
  1381. L"<body>\n" +
  1382. Body +
  1383. L"</body>\n"
  1384. L"</html>\n";
  1385. return Result;
  1386. }
  1387. //---------------------------------------------------------------------------
  1388. void LoadBrowserDocument(TWebBrowserEx * WebBrowser, const UnicodeString & Document)
  1389. {
  1390. std::unique_ptr<TMemoryStream> DocumentStream(new TMemoryStream());
  1391. UTF8String DocumentUTF8 = UTF8String(Document);
  1392. DocumentStream->Write(DocumentUTF8.c_str(), DocumentUTF8.Length());
  1393. DocumentStream->Seek(0, 0);
  1394. // For stream-loaded document, when set only after loading from OnDocumentComplete,
  1395. // browser stops working
  1396. SetBrowserDesignModeOff(WebBrowser);
  1397. TStreamAdapter * DocumentStreamAdapter = new TStreamAdapter(DocumentStream.get(), soReference);
  1398. IPersistStreamInit * PersistStreamInit = NULL;
  1399. if (DebugAlwaysTrue(WebBrowser->Document != NULL) &&
  1400. SUCCEEDED(WebBrowser->Document->QueryInterface(IID_IPersistStreamInit, (void **)&PersistStreamInit)) &&
  1401. DebugAlwaysTrue(PersistStreamInit != NULL))
  1402. {
  1403. PersistStreamInit->Load(static_cast<_di_IStream>(*DocumentStreamAdapter));
  1404. }
  1405. }
  1406. //---------------------------------------------------------------------------
  1407. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  1408. {
  1409. for (int Index = 0; Index < Root->ComponentCount; Index++)
  1410. {
  1411. TComponent * Component = Root->Components[Index];
  1412. if (CompareText(Component->Name, Name) == 0)
  1413. {
  1414. return Component;
  1415. }
  1416. Component = FindComponentRecursively(Component, Name);
  1417. if (Component != NULL)
  1418. {
  1419. return Component;
  1420. }
  1421. }
  1422. return NULL;
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. void __fastcall GetInstrutionsTheme(
  1426. TColor & MainInstructionColor, HFONT & MainInstructionFont, HFONT & InstructionFont)
  1427. {
  1428. MainInstructionColor = Graphics::clNone;
  1429. MainInstructionFont = 0;
  1430. InstructionFont = 0;
  1431. HTHEME Theme = OpenThemeData(0, L"TEXTSTYLE");
  1432. if (Theme != NULL)
  1433. {
  1434. LOGFONT AFont;
  1435. COLORREF AColor;
  1436. memset(&AFont, 0, sizeof(AFont));
  1437. // Using Canvas->Handle in the 2nd argument we can get scaled font,
  1438. // but at this point the form is sometime not scaled yet (difference is particularly for standalone messages like
  1439. // /UninstallCleanup), so the results are inconsistent.
  1440. if (GetThemeFont(Theme, NULL, TEXT_MAININSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1441. {
  1442. MainInstructionFont = CreateFontIndirect(&AFont);
  1443. }
  1444. if (GetThemeColor(Theme, TEXT_MAININSTRUCTION, 0, TMT_TEXTCOLOR, &AColor) == S_OK)
  1445. {
  1446. MainInstructionColor = (TColor)AColor;
  1447. }
  1448. memset(&AFont, 0, sizeof(AFont));
  1449. if (GetThemeFont(Theme, NULL, TEXT_INSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1450. {
  1451. InstructionFont = CreateFontIndirect(&AFont);
  1452. }
  1453. CloseThemeData(Theme);
  1454. }
  1455. }
  1456. //---------------------------------------------------------------------------
  1457. TLocalCustomCommand::TLocalCustomCommand()
  1458. {
  1459. }
  1460. //---------------------------------------------------------------------------
  1461. TLocalCustomCommand::TLocalCustomCommand(
  1462. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  1463. TFileCustomCommand(Data, RemotePath)
  1464. {
  1465. FLocalPath = LocalPath;
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  1469. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  1470. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  1471. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  1472. {
  1473. FLocalPath = LocalPath;
  1474. FLocalFileName = LocalFileName;
  1475. }
  1476. //---------------------------------------------------------------------------
  1477. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  1478. {
  1479. int Len;
  1480. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  1481. {
  1482. Len = 2;
  1483. }
  1484. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  1485. {
  1486. Len = 3;
  1487. }
  1488. else
  1489. {
  1490. Len = TFileCustomCommand::PatternLen(Command, Index);
  1491. }
  1492. return Len;
  1493. }
  1494. //---------------------------------------------------------------------------
  1495. bool __fastcall TLocalCustomCommand::PatternReplacement(
  1496. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  1497. {
  1498. bool Result;
  1499. if (Pattern == L"!\\")
  1500. {
  1501. // When used as "!\" in an argument to PowerShell, the trailing \ would escape the ",
  1502. // so we exclude it
  1503. Replacement = ExcludeTrailingBackslash(FLocalPath);
  1504. Result = true;
  1505. }
  1506. else if (Pattern == L"!^!")
  1507. {
  1508. Replacement = FLocalFileName;
  1509. Result = true;
  1510. }
  1511. else
  1512. {
  1513. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  1514. }
  1515. return Result;
  1516. }
  1517. //---------------------------------------------------------------------------
  1518. void __fastcall TLocalCustomCommand::DelimitReplacement(
  1519. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  1520. {
  1521. // never delimit local commands
  1522. }
  1523. //---------------------------------------------------------------------------
  1524. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  1525. {
  1526. return FindPattern(Command, L'^');
  1527. }
  1528. //---------------------------------------------------------------------------
  1529. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  1530. {
  1531. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  1532. }
  1533. //---------------------------------------------------------------------------
  1534. //---------------------------------------------------------------------------
  1535. typedef std::set<TDataModule *> TImagesModules;
  1536. static TImagesModules ImagesModules;
  1537. static std::map<int, TPngImageList *> AnimationsImages;
  1538. static std::map<int, TImageList *> ButtonImages;
  1539. static std::map<int, TPngImageList *> DialogImages;
  1540. //---------------------------------------------------------------------------
  1541. int __fastcall NormalizePixelsPerInch(int PixelsPerInch)
  1542. {
  1543. if (PixelsPerInch >= 192)
  1544. {
  1545. PixelsPerInch = 192;
  1546. }
  1547. else if (PixelsPerInch >= 144)
  1548. {
  1549. PixelsPerInch = 144;
  1550. }
  1551. else if (PixelsPerInch >= 120)
  1552. {
  1553. PixelsPerInch = 120;
  1554. }
  1555. else
  1556. {
  1557. PixelsPerInch = 96;
  1558. }
  1559. return PixelsPerInch;
  1560. }
  1561. //---------------------------------------------------------------------------
  1562. static int __fastcall NeedImagesModule(TControl * Control)
  1563. {
  1564. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  1565. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  1566. {
  1567. TDataModule * ImagesModule;
  1568. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  1569. try
  1570. {
  1571. if (PixelsPerInch == 192)
  1572. {
  1573. ImagesModule = new TAnimations192Module(Application);
  1574. }
  1575. else if (PixelsPerInch == 144)
  1576. {
  1577. ImagesModule = new TAnimations144Module(Application);
  1578. }
  1579. else if (PixelsPerInch == 120)
  1580. {
  1581. ImagesModule = new TAnimations120Module(Application);
  1582. }
  1583. else
  1584. {
  1585. DebugAssert(PixelsPerInch == 96);
  1586. ImagesModule = new TAnimations96Module(Application);
  1587. }
  1588. ImagesModules.insert(ImagesModule);
  1589. TPngImageList * AAnimationImages =
  1590. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  1591. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  1592. TImageList * AButtonImages =
  1593. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  1594. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  1595. TPngImageList * ADialogImages =
  1596. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  1597. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  1598. }
  1599. __finally
  1600. {
  1601. GUIConfiguration->ChangeResourceModule(ResourceModule);
  1602. }
  1603. }
  1604. return PixelsPerInch;
  1605. }
  1606. //---------------------------------------------------------------------------
  1607. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  1608. {
  1609. int PixelsPerInch = NeedImagesModule(Control);
  1610. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  1611. }
  1612. //---------------------------------------------------------------------------
  1613. TImageList * __fastcall GetButtonImages(TControl * Control)
  1614. {
  1615. int PixelsPerInch = NeedImagesModule(Control);
  1616. return DebugNotNull(ButtonImages[PixelsPerInch]);
  1617. }
  1618. //---------------------------------------------------------------------------
  1619. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  1620. {
  1621. int PixelsPerInch = NeedImagesModule(Control);
  1622. return DebugNotNull(DialogImages[PixelsPerInch]);
  1623. }
  1624. //---------------------------------------------------------------------------
  1625. void __fastcall ReleaseImagesModules()
  1626. {
  1627. TImagesModules::iterator i = ImagesModules.begin();
  1628. while (i != ImagesModules.end())
  1629. {
  1630. delete (*i);
  1631. i++;
  1632. }
  1633. ImagesModules.clear();
  1634. }
  1635. //---------------------------------------------------------------------------
  1636. __fastcall TFrameAnimation::TFrameAnimation()
  1637. {
  1638. FFirstFrame = -1;
  1639. }
  1640. //---------------------------------------------------------------------------
  1641. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1642. {
  1643. FName = Name;
  1644. FPaintBox = PaintBox;
  1645. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1646. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1647. FPaintBox->OnPaint = PaintBoxPaint;
  1648. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1649. DoInit();
  1650. }
  1651. //---------------------------------------------------------------------------
  1652. void __fastcall TFrameAnimation::DoInit()
  1653. {
  1654. FImageList = GetAnimationsImages(FPaintBox);
  1655. FFirstFrame = -1;
  1656. FFirstLoopFrame = -1;
  1657. FPaintBox->Width = FImageList->Width;
  1658. FPaintBox->Height = FImageList->Height;
  1659. if (!FName.IsEmpty())
  1660. {
  1661. int Frame = 0;
  1662. while (Frame < FImageList->PngImages->Count)
  1663. {
  1664. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1665. UnicodeString FrameName;
  1666. FrameName = CutToChar(FrameData, L'_', false);
  1667. if (SameText(FName, FrameName))
  1668. {
  1669. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1670. if (FFirstFrame < 0)
  1671. {
  1672. FFirstFrame = Frame;
  1673. }
  1674. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1675. {
  1676. FFirstLoopFrame = Frame;
  1677. }
  1678. FLastFrame = Frame;
  1679. }
  1680. else
  1681. {
  1682. if (FFirstFrame >= 0)
  1683. {
  1684. // optimization
  1685. break;
  1686. }
  1687. }
  1688. Frame++;
  1689. }
  1690. DebugAssert(FFirstFrame >= 0);
  1691. DebugAssert(FFirstLoopFrame >= 0);
  1692. }
  1693. Stop();
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1697. {
  1698. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1699. FrameAnimation->Rescale();
  1700. }
  1701. //---------------------------------------------------------------------------
  1702. void __fastcall TFrameAnimation::Rescale()
  1703. {
  1704. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1705. DoInit();
  1706. if (Started)
  1707. {
  1708. Start();
  1709. }
  1710. }
  1711. //---------------------------------------------------------------------------
  1712. void __fastcall TFrameAnimation::Start()
  1713. {
  1714. if (FFirstFrame >= 0)
  1715. {
  1716. FNextFrameTick = GetTickCount();
  1717. CalculateNextFrameTick();
  1718. if (FTimer == NULL)
  1719. {
  1720. FTimer = new TTimer(GetParentForm(FPaintBox));
  1721. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1722. FTimer->OnTimer = Timer;
  1723. }
  1724. else
  1725. {
  1726. // reset timer
  1727. FTimer->Enabled = false;
  1728. FTimer->Enabled = true;
  1729. }
  1730. }
  1731. }
  1732. //---------------------------------------------------------------------------
  1733. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1734. {
  1735. Animate();
  1736. }
  1737. //---------------------------------------------------------------------------
  1738. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1739. {
  1740. if (FFirstFrame >= 0)
  1741. {
  1742. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1743. DebugUsedParam(Sender);
  1744. DebugAssert(FPaintBox == Sender);
  1745. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1746. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1747. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1748. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1749. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1750. Bitmap->Canvas->FillRect(Rect);
  1751. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1752. DebugAssert(Graphic->Width == FPaintBox->Width);
  1753. DebugAssert(Graphic->Height == FPaintBox->Height);
  1754. Bitmap->Canvas->Draw(0, 0, Graphic);
  1755. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1756. }
  1757. FPainted = true;
  1758. }
  1759. //---------------------------------------------------------------------------
  1760. void __fastcall TFrameAnimation::Repaint()
  1761. {
  1762. FPainted = false;
  1763. // If the form is not showing yet, the Paint() is not even called
  1764. FPaintBox->Repaint();
  1765. if (!FPainted)
  1766. {
  1767. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  1768. // See also a hack in TAuthenticateForm::Log.
  1769. FPaintBox->Invalidate();
  1770. }
  1771. }
  1772. //---------------------------------------------------------------------------
  1773. void __fastcall TFrameAnimation::Stop()
  1774. {
  1775. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1776. FCurrentFrame = FFirstFrame;
  1777. Repaint();
  1778. if (FTimer != NULL)
  1779. {
  1780. FTimer->Enabled = false;
  1781. }
  1782. }
  1783. //---------------------------------------------------------------------------
  1784. void __fastcall TFrameAnimation::Animate()
  1785. {
  1786. if (FFirstFrame >= 0)
  1787. {
  1788. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1789. DWORD TickCount = GetTickCount();
  1790. // Keep in sync with an opposite condition at the end of the loop.
  1791. // We may skip some frames if we got stalled for a while
  1792. while (TickCount >= FNextFrameTick)
  1793. {
  1794. if (FCurrentFrame >= FLastFrame)
  1795. {
  1796. FCurrentFrame = FFirstLoopFrame;
  1797. }
  1798. else
  1799. {
  1800. FCurrentFrame++;
  1801. }
  1802. CalculateNextFrameTick();
  1803. Repaint();
  1804. }
  1805. }
  1806. }
  1807. //---------------------------------------------------------------------------
  1808. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1809. {
  1810. return FImageList->PngImages->Items[FCurrentFrame];
  1811. }
  1812. //---------------------------------------------------------------------------
  1813. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1814. {
  1815. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1816. UnicodeString Duration = ImageItem->Name;
  1817. CutToChar(Duration, L'_', false);
  1818. // skip index (is not really used)
  1819. CutToChar(Duration, L'_', false);
  1820. // This should overflow, when tick count wraps.
  1821. FNextFrameTick += StrToInt(Duration) * 10;
  1822. }
  1823. //---------------------------------------------------------------------------
  1824. //---------------------------------------------------------------------------
  1825. // Hints use:
  1826. // - Cleanup list tooltip (multi line)
  1827. // - Combo edit button
  1828. // - Transfer settings label (multi line, follows label size and font)
  1829. // - HintLabel (hint and persistent hint, multi line)
  1830. // - status bar hints
  1831. //---------------------------------------------------------------------------
  1832. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  1833. THintWindow(Owner)
  1834. {
  1835. FParentPainting = false;
  1836. }
  1837. //---------------------------------------------------------------------------
  1838. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  1839. {
  1840. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  1841. }
  1842. //---------------------------------------------------------------------------
  1843. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  1844. {
  1845. return
  1846. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  1847. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL) ||
  1848. (HintControl->Perform(WM_WANTS_SCREEN_TIPS, 0, 0) == 1);
  1849. }
  1850. //---------------------------------------------------------------------------
  1851. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  1852. {
  1853. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  1854. }
  1855. //---------------------------------------------------------------------------
  1856. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  1857. {
  1858. int Result;
  1859. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1860. {
  1861. Result = 3;
  1862. }
  1863. else
  1864. {
  1865. Result = 6;
  1866. }
  1867. Result = ScaleByTextHeight(HintControl, Result);
  1868. return Result;
  1869. }
  1870. //---------------------------------------------------------------------------
  1871. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  1872. {
  1873. TFont * Result;
  1874. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1875. {
  1876. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  1877. }
  1878. else
  1879. {
  1880. FScaledHintFont.reset(new TFont());
  1881. FScaledHintFont->Assign(Screen->HintFont);
  1882. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  1883. Result = FScaledHintFont.get();
  1884. }
  1885. return Result;
  1886. }
  1887. //---------------------------------------------------------------------------
  1888. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  1889. {
  1890. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  1891. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  1892. }
  1893. //---------------------------------------------------------------------------
  1894. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  1895. {
  1896. TControl * HintControl = GetHintControl(AData);
  1897. int Margin = GetMargin(HintControl, AHint);
  1898. UnicodeString ShortHint;
  1899. UnicodeString LongHint;
  1900. SplitHint(HintControl, AHint, ShortHint, LongHint);
  1901. Canvas->Font->Assign(GetFont(HintControl, AHint));
  1902. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  1903. int LongHintMargin = 0; // shut up
  1904. bool HasLongHint = !LongHint.IsEmpty();
  1905. if (HasLongHint)
  1906. {
  1907. // double-margin on the right
  1908. LongHintMargin = (3 * Margin);
  1909. MaxWidth = ScreenTipTextOnlyWidth - LongHintMargin;
  1910. }
  1911. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  1912. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  1913. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  1914. if (ShortHint.Pos(L"\n") > 0)
  1915. {
  1916. MaxWidth *= 2;
  1917. }
  1918. bool HintPopup = HasLabelHintPopup(HintControl, AHint);
  1919. if (HintPopup)
  1920. {
  1921. MaxWidth = HintControl->Width;
  1922. }
  1923. if (UseBoldShortHint(HintControl))
  1924. {
  1925. Canvas->Font->Style = TFontStyles() << fsBold;
  1926. }
  1927. TRect ShortRect(0, 0, MaxWidth, 0);
  1928. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  1929. Canvas->Font->Style = TFontStyles();
  1930. TRect Result;
  1931. if (!HasLongHint)
  1932. {
  1933. Result = ShortRect;
  1934. if (HintPopup)
  1935. {
  1936. Result.Right = MaxWidth + 2 * Margin;
  1937. }
  1938. else
  1939. {
  1940. Result.Right += 3 * Margin;
  1941. }
  1942. Result.Bottom += 2 * Margin;
  1943. }
  1944. else
  1945. {
  1946. const int LongIndentation = Margin * 3 / 2;
  1947. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  1948. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  1949. Result.Right = Max(ScreenTipTextOnlyWidth, LongRect.Right + LongIndentation + LongHintMargin);
  1950. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  1951. }
  1952. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  1953. Result.Bottom -= 4;
  1954. return Result;
  1955. }
  1956. //---------------------------------------------------------------------------
  1957. void __fastcall TScreenTipHintWindow::SplitHint(
  1958. TControl * HintControl, const UnicodeString & Hint, UnicodeString & ShortHint, UnicodeString & LongHint)
  1959. {
  1960. if (HasLabelHintPopup(HintControl, Hint))
  1961. {
  1962. ShortHint = HintControl->Hint;
  1963. }
  1964. else
  1965. {
  1966. ShortHint = GetShortHint(Hint);
  1967. LongHint = GetLongHintIfAny(Hint);
  1968. }
  1969. }
  1970. //---------------------------------------------------------------------------
  1971. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  1972. {
  1973. FHintControl = GetHintControl(AData);
  1974. SplitHint(FHintControl, AHint, FShortHint, FLongHint);
  1975. FMargin = GetMargin(FHintControl, AHint);
  1976. FHintPopup = HasLabelHintPopup(FHintControl, AHint);
  1977. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  1978. TRect Rect = ARect;
  1979. if (FHintPopup)
  1980. {
  1981. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  1982. }
  1983. if (IsPathLabel(FHintControl))
  1984. {
  1985. Rect.Offset(-FMargin, -FMargin);
  1986. }
  1987. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  1988. }
  1989. //---------------------------------------------------------------------------
  1990. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  1991. {
  1992. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  1993. }
  1994. //---------------------------------------------------------------------------
  1995. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  1996. {
  1997. UnicodeString Result;
  1998. int P = Pos(L"|", AHint);
  1999. if (P > 0)
  2000. {
  2001. Result = GetLongHint(AHint);
  2002. }
  2003. return Result;
  2004. }
  2005. //---------------------------------------------------------------------------
  2006. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  2007. {
  2008. TMessage * Message = static_cast<TMessage*>(AMessage);
  2009. switch (Message->Msg)
  2010. {
  2011. case WM_GETTEXTLENGTH:
  2012. if (FParentPainting)
  2013. {
  2014. // make THintWindow::Paint() not paint the Caption
  2015. Message->Result = 0;
  2016. }
  2017. else
  2018. {
  2019. THintWindow::Dispatch(AMessage);
  2020. }
  2021. break;
  2022. default:
  2023. THintWindow::Dispatch(AMessage);
  2024. break;
  2025. }
  2026. }
  2027. //---------------------------------------------------------------------------
  2028. void __fastcall TScreenTipHintWindow::Paint()
  2029. {
  2030. // paint frame/background
  2031. {
  2032. TAutoFlag ParentPaintingFlag(FParentPainting);
  2033. THintWindow::Paint();
  2034. }
  2035. const int Flags = GetTextFlags(this);
  2036. const int Margin = FMargin - 1; // 1 = border
  2037. TRect Rect = ClientRect;
  2038. Rect.Inflate(-Margin, -Margin);
  2039. if (!FHintPopup)
  2040. {
  2041. Rect.Right -= FMargin;
  2042. }
  2043. if (UseBoldShortHint(FHintControl))
  2044. {
  2045. Canvas->Font->Style = TFontStyles() << fsBold;
  2046. }
  2047. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  2048. TRect ShortRect = Rect;
  2049. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  2050. Canvas->Font->Style = TFontStyles();
  2051. if (!FLongHint.IsEmpty())
  2052. {
  2053. Rect.Left += FMargin * 3 / 2;
  2054. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  2055. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  2056. }
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. //---------------------------------------------------------------------------
  2060. __fastcall TNewRichEdit::TNewRichEdit(TComponent * AOwner) :
  2061. TRichEdit(AOwner),
  2062. FLibrary(0)
  2063. {
  2064. }
  2065. //---------------------------------------------------------------------------
  2066. void __fastcall TNewRichEdit::CreateParams(TCreateParams & Params)
  2067. {
  2068. UnicodeString RichEditModuleName(L"MSFTEDIT.DLL");
  2069. long int OldError;
  2070. OldError = SetErrorMode(SEM_NOOPENFILEERRORBOX);
  2071. FLibrary = LoadLibrary(RichEditModuleName.c_str());
  2072. SetErrorMode(OldError);
  2073. // No fallback, MSFTEDIT.DLL is available since Windows XP
  2074. // https://learn.microsoft.com/en-us/archive/blogs/murrays/richedit-versions
  2075. if (FLibrary == 0)
  2076. {
  2077. throw Exception(FORMAT(L"Cannot load %s", (RichEditModuleName)));
  2078. }
  2079. TCustomMemo::CreateParams(Params);
  2080. // MSDN says that we should use MSFTEDIT_CLASS to load Rich Edit 4.1:
  2081. // https://learn.microsoft.com/en-us/windows/win32/controls/about-rich-edit-controls
  2082. // But MSFTEDIT_CLASS is defined as "RICHEDIT50W",
  2083. // so not sure what version we are loading.
  2084. // Seem to work on Windows XP SP3.
  2085. CreateSubClass(Params, MSFTEDIT_CLASS);
  2086. }
  2087. //---------------------------------------------------------------------------
  2088. void __fastcall TNewRichEdit::CreateWnd()
  2089. {
  2090. TRichEdit::CreateWnd();
  2091. SendMessage(Handle, EM_SETEDITSTYLEEX, 0, SES_EX_HANDLEFRIENDLYURL);
  2092. }
  2093. //---------------------------------------------------------------------------
  2094. void __fastcall TNewRichEdit::DestroyWnd()
  2095. {
  2096. TRichEdit::DestroyWnd();
  2097. if (FLibrary != 0)
  2098. {
  2099. FreeLibrary(FLibrary);
  2100. }
  2101. }
  2102. //---------------------------------------------------------------------------
  2103. static int HideAccelFlag(TControl * Control)
  2104. {
  2105. //ask the top level window about its UI state
  2106. while (Control->Parent != NULL)
  2107. {
  2108. Control = Control->Parent;
  2109. }
  2110. int Result;
  2111. if (FLAGSET(Control->Perform(WM_QUERYUISTATE, 0, 0), UISF_HIDEACCEL))
  2112. {
  2113. Result = DT_HIDEPREFIX;
  2114. }
  2115. else
  2116. {
  2117. Result = 0;
  2118. }
  2119. return Result;
  2120. }
  2121. //---------------------------------------------------------------------------
  2122. void __fastcall TUIStateAwareLabel::DoDrawText(TRect & Rect, int Flags)
  2123. {
  2124. if (ShowAccelChar)
  2125. {
  2126. Flags = Flags | HideAccelFlag(this);
  2127. }
  2128. TLabel::DoDrawText(Rect, Flags);
  2129. }
  2130. //---------------------------------------------------------------------------
  2131. void __fastcall FindComponentClass(
  2132. void *, TReader *, const UnicodeString DebugUsedArg(ClassName), TComponentClass & ComponentClass)
  2133. {
  2134. if (ComponentClass == __classid(TLabel))
  2135. {
  2136. ComponentClass = __classid(TUIStateAwareLabel);
  2137. }
  2138. else if (ComponentClass == __classid(TComboBox))
  2139. {
  2140. ComponentClass = __classid(TUIStateAwareComboBox);
  2141. }
  2142. }
  2143. //---------------------------------------------------------------------------
  2144. bool CanShowTimeEstimate(TDateTime StartTime)
  2145. {
  2146. return (SecondsBetween(StartTime, Now()) >= 3);
  2147. }
  2148. //---------------------------------------------------------------------------
  2149. class TSystemRequiredThread : public TSignalThread
  2150. {
  2151. public:
  2152. TSystemRequiredThread();
  2153. void Required();
  2154. protected:
  2155. virtual bool __fastcall WaitForEvent();
  2156. virtual void __fastcall ProcessEvent();
  2157. private:
  2158. bool FRequired;
  2159. TDateTime FLastRequired;
  2160. };
  2161. //---------------------------------------------------------------------------
  2162. std::unique_ptr<TCriticalSection> SystemRequiredThreadSection(TraceInitPtr(new TCriticalSection()));
  2163. TSystemRequiredThread * SystemRequiredThread = NULL;
  2164. //---------------------------------------------------------------------------
  2165. TSystemRequiredThread::TSystemRequiredThread() :
  2166. TSignalThread(true), FRequired(false)
  2167. {
  2168. }
  2169. //---------------------------------------------------------------------------
  2170. void TSystemRequiredThread::Required()
  2171. {
  2172. // guarded in SystemRequired()
  2173. FLastRequired = Now();
  2174. TriggerEvent();
  2175. }
  2176. //---------------------------------------------------------------------------
  2177. bool __fastcall TSystemRequiredThread::WaitForEvent()
  2178. {
  2179. const int ExpireInterval = 5000;
  2180. bool Result = (TSignalThread::WaitForEvent(ExpireInterval) > 0);
  2181. if (!Result && !FTerminated)
  2182. {
  2183. TGuard Guard(SystemRequiredThreadSection.get());
  2184. if (!FTerminated && FRequired &&
  2185. (MilliSecondsBetween(Now(), FLastRequired) > ExpireInterval))
  2186. {
  2187. AppLog("System is not required");
  2188. SetThreadExecutionState(ES_CONTINUOUS);
  2189. FLastRequired = TDateTime();
  2190. FRequired = false;
  2191. }
  2192. }
  2193. return Result;
  2194. }
  2195. //---------------------------------------------------------------------------
  2196. void __fastcall TSystemRequiredThread::ProcessEvent()
  2197. {
  2198. TGuard Guard(SystemRequiredThreadSection.get());
  2199. if (!FRequired &&
  2200. (FLastRequired != TDateTime()))
  2201. {
  2202. AppLog("System is required");
  2203. SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
  2204. FRequired = true;
  2205. }
  2206. }
  2207. //---------------------------------------------------------------------------
  2208. void SystemRequired()
  2209. {
  2210. if (IsWin11())
  2211. {
  2212. TGuard Guard(SystemRequiredThreadSection.get());
  2213. if (SystemRequiredThread == NULL)
  2214. {
  2215. AppLog("Starting system required thread");
  2216. SystemRequiredThread = new TSystemRequiredThread();
  2217. SystemRequiredThread->Start();
  2218. }
  2219. SystemRequiredThread->Required();
  2220. }
  2221. else
  2222. {
  2223. SetThreadExecutionState(ES_SYSTEM_REQUIRED);
  2224. }
  2225. }
  2226. //---------------------------------------------------------------------------
  2227. void GUIFinalize()
  2228. {
  2229. TPuttyCleanupThread::Finalize();
  2230. TSystemRequiredThread * Thread;
  2231. {
  2232. TGuard Guard(SystemRequiredThreadSection.get());
  2233. Thread = SystemRequiredThread;
  2234. SystemRequiredThread = NULL;
  2235. }
  2236. if (Thread != NULL)
  2237. {
  2238. AppLog("Stopping system required thread");
  2239. Thread->Terminate();
  2240. Thread->WaitFor();
  2241. delete Thread;
  2242. }
  2243. }