GUITools.cpp 84 KB

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