GUITools.cpp 78 KB

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