GUITools.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlobj.h>
  5. #include <Common.h>
  6. #include "GUITools.h"
  7. #include "GUIConfiguration.h"
  8. #include <TextsCore.h>
  9. #include <CoreMain.h>
  10. #include <SessionData.h>
  11. #include <WinInterface.h>
  12. #include <TbxUtils.hpp>
  13. #include <Math.hpp>
  14. #include <WebBrowserEx.hpp>
  15. #include <Tools.h>
  16. #include "PngImageList.hpp"
  17. #include <StrUtils.hpp>
  18. #include <limits>
  19. #include <Glyphs.h>
  20. #include <PasTools.hpp>
  21. #include <VCLCommon.h>
  22. #include <WinApi.h>
  23. #include <Vcl.ScreenTips.hpp>
  24. #include "Animations96.h"
  25. #include "Animations120.h"
  26. #include "Animations144.h"
  27. #include "Animations192.h"
  28. //---------------------------------------------------------------------------
  29. #pragma package(smart_init)
  30. //---------------------------------------------------------------------------
  31. extern const UnicodeString PageantTool = L"pageant.exe";
  32. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  33. //---------------------------------------------------------------------------
  34. bool __fastcall FindFile(UnicodeString & Path)
  35. {
  36. bool Result = FileExists(ApiPath(Path));
  37. if (!Result)
  38. {
  39. UnicodeString ProgramFiles32 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramFiles"));
  40. UnicodeString ProgramFiles64 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramW6432"));
  41. if (!ProgramFiles32.IsEmpty() &&
  42. SameText(Path.SubString(1, ProgramFiles32.Length()), ProgramFiles32) &&
  43. !ProgramFiles64.IsEmpty())
  44. {
  45. UnicodeString Path64 =
  46. ProgramFiles64 + Path.SubString(ProgramFiles32.Length() + 1, Path.Length() - ProgramFiles32.Length());
  47. if (FileExists(ApiPath(Path64)))
  48. {
  49. Path = Path64;
  50. Result = true;
  51. }
  52. }
  53. }
  54. if (!Result)
  55. {
  56. UnicodeString Paths = GetEnvironmentVariable(L"PATH");
  57. if (!Paths.IsEmpty())
  58. {
  59. UnicodeString NewPath = FileSearch(ExtractFileName(Path), Paths);
  60. Result = !NewPath.IsEmpty();
  61. if (Result)
  62. {
  63. Path = NewPath;
  64. }
  65. }
  66. }
  67. return Result;
  68. }
  69. //---------------------------------------------------------------------------
  70. void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  71. TSessionData * SessionData)
  72. {
  73. UnicodeString Program, AParams, Dir;
  74. SplitCommand(PuttyPath, Program, AParams, Dir);
  75. Program = ExpandEnvironmentVariables(Program);
  76. if (FindFile(Program))
  77. {
  78. AParams = ExpandEnvironmentVariables(AParams);
  79. UnicodeString Password = GUIConfiguration->PuttyPassword ? SessionData->Password : UnicodeString();
  80. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  81. TRemoteCustomCommand RemoteCustomCommand(Data, SessionData->RemoteDirectory);
  82. TWinInteractiveCustomCommand InteractiveCustomCommand(
  83. &RemoteCustomCommand, L"PuTTY", UnicodeString());
  84. UnicodeString Params =
  85. RemoteCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  86. UnicodeString PuttyParams;
  87. if (!RemoteCustomCommand.IsSiteCommand(AParams))
  88. {
  89. {
  90. bool SessionList = false;
  91. std::unique_ptr<THierarchicalStorage> SourceHostKeyStorage(Configuration->CreateScpStorage(SessionList));
  92. std::unique_ptr<THierarchicalStorage> TargetHostKeyStorage(new TRegistryStorage(Configuration->PuttyRegistryStorageKey));
  93. TargetHostKeyStorage->Explicit = true;
  94. TargetHostKeyStorage->AccessMode = smReadWrite;
  95. std::unique_ptr<TStoredSessionList> HostKeySessionList(new TStoredSessionList());
  96. HostKeySessionList->OwnsObjects = false;
  97. HostKeySessionList->Add(SessionData);
  98. TStoredSessionList::ImportHostKeys(SourceHostKeyStorage.get(), TargetHostKeyStorage.get(), HostKeySessionList.get(), false);
  99. }
  100. if (IsUWP())
  101. {
  102. bool Telnet = (SessionData->FSProtocol == fsFTP) && GUIConfiguration->TelnetForFtpInPutty;
  103. if (Telnet)
  104. {
  105. AddToList(PuttyParams, L"-telnet", L" ");
  106. // PuTTY does not allow -pw for telnet
  107. Password = L"";
  108. }
  109. AddToList(PuttyParams, EscapePuttyCommandParam(SessionData->HostName), L" ");
  110. if (!SessionData->UserName.IsEmpty())
  111. {
  112. AddToList(PuttyParams, FORMAT(L"-l %s", (EscapePuttyCommandParam(SessionData->UserName))), L" ");
  113. }
  114. if ((SessionData->FSProtocol != fsFTP) && (SessionData->PortNumber != SshPortNumber))
  115. {
  116. AddToList(PuttyParams, FORMAT(L"-P %d", (SessionData->PortNumber)), L" ");
  117. }
  118. if (!Telnet)
  119. {
  120. if (!SessionData->PublicKeyFile.IsEmpty())
  121. {
  122. AddToList(PuttyParams, FORMAT(L"-i \"%s\"", (SessionData->PublicKeyFile)), L" ");
  123. }
  124. AddToList(PuttyParams, (SessionData->TryAgent ? L"-agent" : L"-noagent"), L" ");
  125. if (SessionData->TryAgent)
  126. {
  127. AddToList(PuttyParams, (SessionData->AgentFwd ? L"-A" : L"-a"), L" ");
  128. }
  129. if (SessionData->Compression)
  130. {
  131. AddToList(PuttyParams, L"-C", L" ");
  132. }
  133. AddToList(PuttyParams,
  134. ((SessionData->SshProt == ssh1only || SessionData->SshProt == ssh1deprecated) ? L"-1" : L"-2"), L" ");
  135. if (!SessionData->LogicalHostName.IsEmpty())
  136. {
  137. AddToList(PuttyParams, FORMAT(L"-loghost \"%s\"", (SessionData->LogicalHostName)), L" ");
  138. }
  139. }
  140. if (SessionData->AddressFamily == afIPv4)
  141. {
  142. AddToList(PuttyParams, L"-4", L" ");
  143. }
  144. else if (SessionData->AddressFamily == afIPv6)
  145. {
  146. AddToList(PuttyParams, L"-6", L" ");
  147. }
  148. }
  149. else
  150. {
  151. UnicodeString SessionName;
  152. TRegistryStorage * Storage = NULL;
  153. TSessionData * ExportData = NULL;
  154. TRegistryStorage * SourceStorage = NULL;
  155. try
  156. {
  157. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  158. Storage->AccessMode = smReadWrite;
  159. // make it compatible with putty
  160. Storage->MungeStringValues = false;
  161. Storage->ForceAnsi = true;
  162. if (Storage->OpenRootKey(true))
  163. {
  164. if (Storage->KeyExists(SessionData->StorageKey))
  165. {
  166. SessionName = SessionData->SessionName;
  167. }
  168. else
  169. {
  170. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  171. SourceStorage->MungeStringValues = false;
  172. SourceStorage->ForceAnsi = true;
  173. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  174. Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
  175. {
  176. Storage->Copy(SourceStorage);
  177. Storage->CloseSubKey();
  178. }
  179. ExportData = new TSessionData(L"");
  180. ExportData->Assign(SessionData);
  181. ExportData->Modified = true;
  182. ExportData->Name = GUIConfiguration->PuttySession;
  183. ExportData->WinTitle = SessionData->SessionName;
  184. ExportData->Password = L"";
  185. if (SessionData->FSProtocol == fsFTP)
  186. {
  187. if (GUIConfiguration->TelnetForFtpInPutty)
  188. {
  189. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  190. ExportData->PortNumber = TelnetPortNumber;
  191. // PuTTY does not allow -pw for telnet
  192. Password = L"";
  193. }
  194. else
  195. {
  196. ExportData->PuttyProtocol = PuttySshProtocol;
  197. ExportData->PortNumber = SshPortNumber;
  198. }
  199. }
  200. ExportData->Save(Storage, true);
  201. SessionName = GUIConfiguration->PuttySession;
  202. }
  203. }
  204. }
  205. __finally
  206. {
  207. delete Storage;
  208. delete ExportData;
  209. delete SourceStorage;
  210. }
  211. UnicodeString LoadSwitch = L"-load";
  212. int P = Params.LowerCase().Pos(LoadSwitch + L" ");
  213. if ((P == 0) || ((P > 1) && (Params[P - 1] != L' ')))
  214. {
  215. AddToList(PuttyParams, FORMAT(L"%s %s", (LoadSwitch, EscapePuttyCommandParam(SessionName))), L" ");
  216. }
  217. }
  218. }
  219. if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
  220. {
  221. Password = NormalizeString(Password); // if password is empty, we should quote it always
  222. AddToList(PuttyParams, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
  223. }
  224. AddToList(PuttyParams, Params, L" ");
  225. // PuTTY is started in its binary directory to allow relative paths in private key,
  226. // when opening PuTTY's own stored session.
  227. ExecuteShellChecked(Program, PuttyParams, true);
  228. }
  229. else
  230. {
  231. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  232. }
  233. }
  234. //---------------------------------------------------------------------------
  235. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  236. {
  237. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  238. Path = AppPath + Name;
  239. bool Result = true;
  240. if (!FileExists(ApiPath(Path)))
  241. {
  242. Path = AppPath + L"PuTTY\\" + Name;
  243. if (!FileExists(ApiPath(Path)))
  244. {
  245. Path = Name;
  246. if (!FindFile(Path))
  247. {
  248. Result = false;
  249. }
  250. }
  251. }
  252. return Result;
  253. }
  254. //---------------------------------------------------------------------------
  255. void __fastcall ExecuteTool(const UnicodeString & Name)
  256. {
  257. UnicodeString Path;
  258. if (!FindTool(Name, Path))
  259. {
  260. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Name)));
  261. }
  262. ExecuteShellChecked(Path, L"");
  263. }
  264. //---------------------------------------------------------------------------
  265. TObjectList * StartCreationDirectoryMonitorsOnEachDrive(unsigned int Filter, TFileChangedEvent OnChanged)
  266. {
  267. std::unique_ptr<TObjectList> Result(new TObjectList());
  268. for (char Drive = FirstDrive; Drive <= LastDrive; Drive++)
  269. {
  270. std::unique_ptr<TDirectoryMonitor> Monitor(new TDirectoryMonitor(Application));
  271. TDriveInfoRec * DriveInfoRec = DriveInfo->Get(Drive);
  272. if (DriveInfoRec->Valid &&
  273. (DriveInfoRec->DriveType != DRIVE_CDROM) &&
  274. ((DriveInfoRec->DriveType != DRIVE_REMOVABLE) || (Drive >= FirstFixedDrive)))
  275. {
  276. try
  277. {
  278. Monitor->Path = DriveInfo->GetDriveRoot(Drive);
  279. Monitor->WatchSubtree = true;
  280. Monitor->WatchFilters = Filter;
  281. Monitor->OnCreated = OnChanged;
  282. Monitor->OnModified = OnChanged;
  283. Monitor->Active = true;
  284. Result->Add(Monitor.release());
  285. }
  286. catch (Exception & E)
  287. {
  288. // Ignore errors watching not-ready drives
  289. }
  290. }
  291. }
  292. return Result.release();
  293. }
  294. //---------------------------------------------------------------------------
  295. bool __fastcall CopyCommandToClipboard(const UnicodeString & Command)
  296. {
  297. bool Result = UseAlternativeFunction() && IsKeyPressed(VK_CONTROL);
  298. if (Result)
  299. {
  300. TInstantOperationVisualizer Visualizer;
  301. CopyToClipboard(Command);
  302. }
  303. return Result;
  304. }
  305. //---------------------------------------------------------------------------
  306. static bool __fastcall DoExecuteShell(const UnicodeString Path, const UnicodeString Params,
  307. bool ChangeWorkingDirectory, HANDLE * Handle)
  308. {
  309. bool Result = CopyCommandToClipboard(FormatCommand(Path, Params));
  310. if (Result)
  311. {
  312. if (Handle != NULL)
  313. {
  314. *Handle = NULL;
  315. }
  316. }
  317. else
  318. {
  319. UnicodeString Directory = ExtractFilePath(Path);
  320. TShellExecuteInfoW ExecuteInfo;
  321. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  322. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  323. ExecuteInfo.fMask =
  324. SEE_MASK_FLAG_NO_UI |
  325. FLAGMASK((Handle != NULL), SEE_MASK_NOCLOSEPROCESS);
  326. ExecuteInfo.hwnd = Application->Handle;
  327. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  328. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  329. ExecuteInfo.lpDirectory = (ChangeWorkingDirectory ? Directory.c_str() : NULL);
  330. ExecuteInfo.nShow = SW_SHOW;
  331. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  332. if (Result)
  333. {
  334. if (Handle != NULL)
  335. {
  336. *Handle = ExecuteInfo.hProcess;
  337. }
  338. }
  339. }
  340. return Result;
  341. }
  342. //---------------------------------------------------------------------------
  343. void __fastcall ExecuteShellChecked(const UnicodeString Path, const UnicodeString Params, bool ChangeWorkingDirectory)
  344. {
  345. if (!DoExecuteShell(Path, Params, ChangeWorkingDirectory, NULL))
  346. {
  347. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Path)));
  348. }
  349. }
  350. //---------------------------------------------------------------------------
  351. void __fastcall ExecuteShellChecked(const UnicodeString Command)
  352. {
  353. UnicodeString Program, Params, Dir;
  354. SplitCommand(Command, Program, Params, Dir);
  355. ExecuteShellChecked(Program, Params);
  356. }
  357. //---------------------------------------------------------------------------
  358. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  359. HANDLE & Handle)
  360. {
  361. return DoExecuteShell(Path, Params, false, &Handle);
  362. }
  363. //---------------------------------------------------------------------------
  364. void __fastcall ExecuteShellCheckedAndWait(const UnicodeString Command,
  365. TProcessMessagesEvent ProcessMessages)
  366. {
  367. UnicodeString Program, Params, Dir;
  368. SplitCommand(Command, Program, Params, Dir);
  369. HANDLE ProcessHandle;
  370. bool Result = DoExecuteShell(Program, Params, false, &ProcessHandle);
  371. if (!Result)
  372. {
  373. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  374. }
  375. else
  376. {
  377. if (ProcessHandle != NULL) // only if command was copied to clipboard only
  378. {
  379. if (ProcessMessages != NULL)
  380. {
  381. unsigned long WaitResult;
  382. do
  383. {
  384. // Same as in ExecuteProcessAndReadOutput
  385. WaitResult = WaitForSingleObject(ProcessHandle, 200);
  386. if (WaitResult == WAIT_FAILED)
  387. {
  388. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  389. }
  390. ProcessMessages();
  391. }
  392. while (WaitResult == WAIT_TIMEOUT);
  393. }
  394. else
  395. {
  396. WaitForSingleObject(ProcessHandle, INFINITE);
  397. }
  398. }
  399. }
  400. }
  401. //---------------------------------------------------------------------------
  402. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  403. {
  404. LPITEMIDLIST Pidl;
  405. wchar_t Buf[256];
  406. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  407. SHGetPathFromIDList(Pidl, Buf))
  408. {
  409. Path = UnicodeString(Buf);
  410. return true;
  411. }
  412. return false;
  413. }
  414. //---------------------------------------------------------------------------
  415. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  416. bool Mask)
  417. {
  418. DebugAssert(!BaseDir.IsEmpty());
  419. UnicodeString TempDir;
  420. do
  421. {
  422. TempDir = IncludeTrailingBackslash(BaseDir) + Identity;
  423. if (Mask)
  424. {
  425. TempDir += L"?????";
  426. }
  427. else
  428. {
  429. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  430. }
  431. }
  432. while (!Mask && DirectoryExists(ApiPath(TempDir)));
  433. return TempDir;
  434. }
  435. //---------------------------------------------------------------------------
  436. bool __fastcall DeleteDirectory(const UnicodeString DirName)
  437. {
  438. TSearchRecChecked sr;
  439. bool retval = true;
  440. if (FindFirstUnchecked(DirName + L"\\*", faAnyFile, sr) == 0) // VCL Function
  441. {
  442. if (FLAGSET(sr.Attr, faDirectory))
  443. {
  444. if (sr.Name != L"." && sr.Name != L"..")
  445. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  446. }
  447. else
  448. {
  449. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  450. }
  451. if (retval)
  452. {
  453. while (FindNextChecked(sr) == 0)
  454. { // VCL Function
  455. if (FLAGSET(sr.Attr, faDirectory))
  456. {
  457. if (sr.Name != L"." && sr.Name != L"..")
  458. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  459. }
  460. else
  461. {
  462. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  463. }
  464. if (!retval) break;
  465. }
  466. }
  467. }
  468. FindClose(sr);
  469. if (retval) retval = RemoveDir(ApiPath(DirName)); // VCL function
  470. return retval;
  471. }
  472. //---------------------------------------------------------------------------
  473. void __fastcall AddSessionColorImage(
  474. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  475. {
  476. // This overly complex drawing is here to support color button on SiteAdvanced
  477. // dialog. There we use plain TImageList, instead of TPngImageList,
  478. // TButton does not work with transparent images
  479. // (not even TBitmap with Transparent = true)
  480. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  481. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  482. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  483. MaskImage->Assign(MaskBitmap.get());
  484. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  485. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  486. TColor TransparentColor = MaskTransparentColor;
  487. // Expecting that the color to be replaced is in the centre of the image (HACK)
  488. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  489. for (int Y = 0; Y < ImageList->Height; Y++)
  490. {
  491. for (int X = 0; X < ImageList->Width; X++)
  492. {
  493. TColor SourceColor = MaskImage->Pixels[X][Y];
  494. TColor DestColor;
  495. // this branch is pointless as long as MaskTransparentColor and
  496. // TransparentColor are the same
  497. if (SourceColor == MaskTransparentColor)
  498. {
  499. DestColor = TransparentColor;
  500. }
  501. else if (SourceColor == MaskColor)
  502. {
  503. DestColor = Color;
  504. }
  505. else
  506. {
  507. DestColor = SourceColor;
  508. }
  509. ColorImage->Pixels[X][Y] = DestColor;
  510. }
  511. }
  512. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  513. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  514. ColorImage->AssignTo(Bitmap.get());
  515. ImageList->AddMasked(Bitmap.get(), TransparentColor);
  516. }
  517. //---------------------------------------------------------------------------
  518. void __fastcall SetSubmenu(TTBXCustomItem * Item)
  519. {
  520. class TTBXPublicItem : public TTBXCustomItem
  521. {
  522. public:
  523. __property ItemStyle;
  524. };
  525. TTBXPublicItem * PublicItem = reinterpret_cast<TTBXPublicItem *>(Item);
  526. DebugAssert(PublicItem != NULL);
  527. // See TTBItemViewer.IsPtInButtonPart (called from TTBItemViewer.MouseDown)
  528. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  529. }
  530. //---------------------------------------------------------------------------
  531. bool __fastcall IsEligibleForApplyingTabs(
  532. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  533. {
  534. bool Result = false;
  535. TabPos = Line.Pos(L"\t");
  536. if (TabPos > 0)
  537. {
  538. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  539. // WORKAROUND
  540. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  541. // Delete these, so that the following check does not fail on this
  542. while (Remaining.SubString(1, 1) == L"\t")
  543. {
  544. Remaining.Delete(1, 1);
  545. }
  546. // We do not have, not support, mutiple tabs on a single line
  547. if (DebugAlwaysTrue(Remaining.Pos(L"\t") == 0))
  548. {
  549. Start = Line.SubString(1, TabPos - 1);
  550. // WORKAROUND
  551. // Previously we padded the string before tab with spaces,
  552. // to aling the contents across multiple lines
  553. Start = Start.TrimRight();
  554. // at least two normal spaces for separation
  555. Start += L" ";
  556. Result = true;
  557. }
  558. }
  559. return Result;
  560. }
  561. //---------------------------------------------------------------------------
  562. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  563. {
  564. return Text.Length();
  565. }
  566. //---------------------------------------------------------------------------
  567. void __fastcall ApplyTabs(
  568. UnicodeString & Text, wchar_t Padding,
  569. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  570. {
  571. if (CalculateWidth == NULL)
  572. {
  573. DebugAssert(CalculateWidthArg == NULL);
  574. CalculateWidth = CalculateWidthByLength;
  575. }
  576. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  577. int MaxWidth = -1;
  578. for (int Index = 0; Index < Lines->Count; Index++)
  579. {
  580. UnicodeString Line = Lines->Strings[Index];
  581. int TabPos;
  582. UnicodeString Start;
  583. UnicodeString Remaining;
  584. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  585. {
  586. int Width = CalculateWidth(Start, CalculateWidthArg);
  587. MaxWidth = Max(MaxWidth, Width);
  588. }
  589. }
  590. // Optimization and also to prevent potential regression for texts without tabs
  591. if (MaxWidth >= 0)
  592. {
  593. for (int Index = 0; Index < Lines->Count; Index++)
  594. {
  595. UnicodeString Line = Lines->Strings[Index];
  596. int TabPos;
  597. UnicodeString Start;
  598. UnicodeString Remaining;
  599. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  600. {
  601. int Width;
  602. int Iterations = 0;
  603. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  604. {
  605. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  606. // If padded string is wider than max width by more pixels
  607. // than non-padded string is shorter than max width
  608. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  609. {
  610. break;
  611. }
  612. Start += Padding;
  613. Iterations++;
  614. // In rare case a tab is zero-width with some strange font (like HYLE)
  615. if (Iterations > 100)
  616. {
  617. break;
  618. }
  619. }
  620. Lines->Strings[Index] = Start + Remaining;
  621. }
  622. }
  623. Text = Lines->Text;
  624. // remove trailing newline
  625. Text = Text.TrimRight();
  626. }
  627. }
  628. //---------------------------------------------------------------------------
  629. static void __fastcall DoSelectScaledImageList(TImageList * ImageList)
  630. {
  631. TImageList * MatchingList = NULL;
  632. int MachingPixelsPerInch = 0;
  633. int PixelsPerInch = GetComponentPixelsPerInch(ImageList);
  634. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  635. {
  636. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  637. if ((OtherList != NULL) &&
  638. (OtherList != ImageList) &&
  639. StartsStr(ImageList->Name, OtherList->Name))
  640. {
  641. UnicodeString OtherListPixelsPerInchStr =
  642. OtherList->Name.SubString(
  643. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  644. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  645. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  646. ((MatchingList == NULL) ||
  647. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  648. {
  649. MatchingList = OtherList;
  650. MachingPixelsPerInch = OtherListPixelsPerInch;
  651. }
  652. }
  653. }
  654. if (MatchingList != NULL)
  655. {
  656. UnicodeString ImageListBackupName = ImageList->Name + IntToStr(USER_DEFAULT_SCREEN_DPI);
  657. if (ImageList->Owner->FindComponent(ImageListBackupName) == NULL)
  658. {
  659. TImageList * ImageListBackup;
  660. TPngImageList * PngImageList = dynamic_cast<TPngImageList *>(ImageList);
  661. if (PngImageList != NULL)
  662. {
  663. ImageListBackup = new TPngImageList(ImageList->Owner);
  664. }
  665. else
  666. {
  667. ImageListBackup = new TImageList(ImageList->Owner);
  668. }
  669. ImageListBackup->Name = ImageListBackupName;
  670. ImageList->Owner->InsertComponent(ImageListBackup);
  671. CopyImageList(ImageListBackup, ImageList);
  672. }
  673. CopyImageList(ImageList, MatchingList);
  674. }
  675. }
  676. //---------------------------------------------------------------------------
  677. static void __fastcall ImageListRescale(TComponent * Sender, TObject * /*Token*/)
  678. {
  679. TImageList * ImageList = DebugNotNull(dynamic_cast<TImageList *>(Sender));
  680. DoSelectScaledImageList(ImageList);
  681. }
  682. //---------------------------------------------------------------------------
  683. void __fastcall SelectScaledImageList(TImageList * ImageList)
  684. {
  685. DoSelectScaledImageList(ImageList);
  686. SetRescaleFunction(ImageList, ImageListRescale);
  687. }
  688. //---------------------------------------------------------------------------
  689. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  690. {
  691. // Maybe this is not necessary, once the TPngImageList::Assign was fixed
  692. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  693. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  694. TargetList->Clear();
  695. TargetList->Height = SourceList->Height;
  696. TargetList->Width = SourceList->Width;
  697. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  698. {
  699. // AddImages won't copy the names and we need them for
  700. // LoadDialogImage and TFrameAnimation
  701. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  702. }
  703. else
  704. {
  705. TargetList->AddImages(SourceList);
  706. }
  707. }
  708. //---------------------------------------------------------------------------
  709. static bool __fastcall DoLoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  710. {
  711. bool Result = false;
  712. if (GlyphsModule != NULL)
  713. {
  714. TPngImageList * DialogImages = GetDialogImages(Image);
  715. int Index;
  716. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  717. {
  718. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  719. if (SameText(PngItem->Name, ImageName))
  720. {
  721. Image->Picture->Assign(PngItem->PngImage);
  722. break;
  723. }
  724. }
  725. DebugAssert(Index < DialogImages->PngImages->Count);
  726. Result = true;
  727. }
  728. // When showing an exception from wWinMain, the images are released already.
  729. // Non-existence of the glyphs module is just a good indication of that.
  730. // We expect errors only.
  731. else if (ImageName == L"Error")
  732. {
  733. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  734. }
  735. // For showing an information about trace files
  736. else if (DebugAlwaysTrue(ImageName == L"Information"))
  737. {
  738. Image->Picture->Icon->Handle = LoadIcon(0, IDI_APPLICATION);
  739. }
  740. return Result;
  741. }
  742. //---------------------------------------------------------------------------
  743. class TDialogImageName : public TObject
  744. {
  745. public:
  746. UnicodeString ImageName;
  747. };
  748. //---------------------------------------------------------------------------
  749. static void __fastcall DialogImageRescale(TComponent * Sender, TObject * Token)
  750. {
  751. TImage * Image = DebugNotNull(dynamic_cast<TImage *>(Sender));
  752. TDialogImageName * DialogImageName = DebugNotNull(dynamic_cast<TDialogImageName *>(Token));
  753. DoLoadDialogImage(Image, DialogImageName->ImageName);
  754. }
  755. //---------------------------------------------------------------------------
  756. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  757. {
  758. if (DoLoadDialogImage(Image, ImageName))
  759. {
  760. TDialogImageName * DialogImageName = new TDialogImageName();
  761. DialogImageName->ImageName = ImageName;
  762. SetRescaleFunction(Image, DialogImageRescale, DialogImageName, true);
  763. }
  764. }
  765. //---------------------------------------------------------------------------
  766. int __fastcall DialogImageSize(TForm * Form)
  767. {
  768. return ScaleByPixelsPerInch(32, Form);
  769. }
  770. //---------------------------------------------------------------------------
  771. void __fastcall HideComponentsPanel(TForm * Form)
  772. {
  773. TComponent * Component = DebugNotNull(Form->FindComponent(L"ComponentsPanel"));
  774. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Component));
  775. DebugAssert(Panel->Align == alBottom);
  776. int Offset = Panel->Height;
  777. Panel->Visible = false;
  778. Panel->Height = 0;
  779. Form->Height -= Offset;
  780. for (int Index = 0; Index < Form->ControlCount; Index++)
  781. {
  782. TControl * Control = Form->Controls[Index];
  783. // Shift back bottom-anchored controls
  784. // (needed for toolbar panel on Progress window and buttons on Preferences dialog),
  785. if ((Control->Align == alNone) &&
  786. Control->Anchors.Contains(akBottom) &&
  787. !Control->Anchors.Contains(akTop))
  788. {
  789. Control->Top += Offset;
  790. }
  791. // Resize back all-anchored controls
  792. // (needed for main panel on Preferences dialog),
  793. if (Control->Anchors.Contains(akBottom) &&
  794. Control->Anchors.Contains(akTop))
  795. {
  796. Control->Height += Offset;
  797. }
  798. }
  799. }
  800. //---------------------------------------------------------------------------
  801. class TBrowserViewer : public TWebBrowserEx
  802. {
  803. public:
  804. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  805. void __fastcall AddLinkHandler(
  806. const UnicodeString & Url, TNotifyEvent Handler);
  807. void __fastcall NavigateToUrl(const UnicodeString & Url);
  808. TControl * LoadingPanel;
  809. protected:
  810. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  811. void __fastcall DocumentComplete(
  812. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  813. void __fastcall BeforeNavigate2(
  814. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  815. const OleVariant & Flags, const OleVariant & TargetFrameName,
  816. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  817. bool FComplete;
  818. std::map<UnicodeString, TNotifyEvent> FHandlers;
  819. };
  820. //---------------------------------------------------------------------------
  821. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  822. TWebBrowserEx(AOwner)
  823. {
  824. FComplete = false;
  825. OnDocumentComplete = DocumentComplete;
  826. OnBeforeNavigate2 = BeforeNavigate2;
  827. LoadingPanel = NULL;
  828. }
  829. //---------------------------------------------------------------------------
  830. void __fastcall TBrowserViewer::AddLinkHandler(
  831. const UnicodeString & Url, TNotifyEvent Handler)
  832. {
  833. FHandlers.insert(std::make_pair(Url, Handler));
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  837. {
  838. // suppress built-in context menu
  839. Handled = true;
  840. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  841. }
  842. //---------------------------------------------------------------------------
  843. void __fastcall TBrowserViewer::DocumentComplete(
  844. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  845. {
  846. SetBrowserDesignModeOff(this);
  847. FComplete = true;
  848. if (LoadingPanel != NULL)
  849. {
  850. LoadingPanel->Visible = false;
  851. }
  852. }
  853. //---------------------------------------------------------------------------
  854. void __fastcall TBrowserViewer::BeforeNavigate2(
  855. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  856. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  857. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  858. {
  859. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  860. // opened using TWebBrowserEx::Navigate(), allow it.
  861. // Otherwise it's user navigating, block that and open link
  862. // in an external browser, possibly adding campaign parameters on the way.
  863. if (FComplete)
  864. {
  865. Cancel = 1;
  866. UnicodeString URL = AURL;
  867. if (FHandlers.count(URL) > 0)
  868. {
  869. FHandlers[URL](this);
  870. }
  871. else
  872. {
  873. OpenBrowser(URL);
  874. }
  875. }
  876. }
  877. //---------------------------------------------------------------------------
  878. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  879. {
  880. FComplete = false;
  881. Navigate(Url.c_str());
  882. }
  883. //---------------------------------------------------------------------------
  884. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  885. {
  886. TPanel * Result = CreateBlankPanel(Parent);
  887. Result->Parent = Parent;
  888. Result->Align = alClient;
  889. Result->Caption = Label;
  890. return Result;
  891. }
  892. //---------------------------------------------------------------------------
  893. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  894. {
  895. TBrowserViewer * Result = new TBrowserViewer(Parent);
  896. // TWebBrowserEx has its own unrelated Name and Parent properties.
  897. // The name is used in DownloadUpdate().
  898. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  899. static_cast<TWinControl *>(Result)->Parent = Parent;
  900. Result->Align = alClient;
  901. Result->ControlBorder = cbNone;
  902. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  903. return Result;
  904. }
  905. //---------------------------------------------------------------------------
  906. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  907. {
  908. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  909. {
  910. WebBrowser->Document2->designMode = L"Off";
  911. }
  912. }
  913. //---------------------------------------------------------------------------
  914. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  915. const UnicodeString & Url, TNotifyEvent Handler)
  916. {
  917. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  918. if (DebugAlwaysTrue(BrowserViewer != NULL))
  919. {
  920. BrowserViewer->AddLinkHandler(Url, Handler);
  921. }
  922. }
  923. //---------------------------------------------------------------------------
  924. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  925. {
  926. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  927. if (DebugAlwaysTrue(BrowserViewer != NULL))
  928. {
  929. BrowserViewer->NavigateToUrl(Url);
  930. }
  931. }
  932. //---------------------------------------------------------------------------
  933. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  934. {
  935. for (int Index = 0; Index < Root->ComponentCount; Index++)
  936. {
  937. TComponent * Component = Root->Components[Index];
  938. if (CompareText(Component->Name, Name) == 0)
  939. {
  940. return Component;
  941. }
  942. Component = FindComponentRecursively(Component, Name);
  943. if (Component != NULL)
  944. {
  945. return Component;
  946. }
  947. }
  948. return NULL;
  949. }
  950. //---------------------------------------------------------------------------
  951. TLocalCustomCommand::TLocalCustomCommand()
  952. {
  953. }
  954. //---------------------------------------------------------------------------
  955. TLocalCustomCommand::TLocalCustomCommand(
  956. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  957. TFileCustomCommand(Data, RemotePath)
  958. {
  959. FLocalPath = LocalPath;
  960. }
  961. //---------------------------------------------------------------------------
  962. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  963. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  964. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  965. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  966. {
  967. FLocalPath = LocalPath;
  968. FLocalFileName = LocalFileName;
  969. }
  970. //---------------------------------------------------------------------------
  971. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  972. {
  973. int Len;
  974. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  975. {
  976. Len = 2;
  977. }
  978. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  979. {
  980. Len = 3;
  981. }
  982. else
  983. {
  984. Len = TFileCustomCommand::PatternLen(Command, Index);
  985. }
  986. return Len;
  987. }
  988. //---------------------------------------------------------------------------
  989. bool __fastcall TLocalCustomCommand::PatternReplacement(
  990. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  991. {
  992. bool Result;
  993. if (Pattern == L"!\\")
  994. {
  995. // When used as "!\" in an argument to PowerShell, the trailing \ would escpae the ",
  996. // so we exclude it
  997. Replacement = ExcludeTrailingBackslash(FLocalPath);
  998. Result = true;
  999. }
  1000. else if (Pattern == L"!^!")
  1001. {
  1002. Replacement = FLocalFileName;
  1003. Result = true;
  1004. }
  1005. else
  1006. {
  1007. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  1008. }
  1009. return Result;
  1010. }
  1011. //---------------------------------------------------------------------------
  1012. void __fastcall TLocalCustomCommand::DelimitReplacement(
  1013. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  1014. {
  1015. // never delimit local commands
  1016. }
  1017. //---------------------------------------------------------------------------
  1018. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  1019. {
  1020. return FindPattern(Command, L'^');
  1021. }
  1022. //---------------------------------------------------------------------------
  1023. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  1024. {
  1025. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  1026. }
  1027. //---------------------------------------------------------------------------
  1028. //---------------------------------------------------------------------------
  1029. typedef std::set<TDataModule *> TImagesModules;
  1030. static TImagesModules ImagesModules;
  1031. static std::map<int, TPngImageList *> AnimationsImages;
  1032. static std::map<int, TImageList *> ButtonImages;
  1033. static std::map<int, TPngImageList *> DialogImages;
  1034. //---------------------------------------------------------------------------
  1035. int __fastcall NormalizePixelsPerInch(int PixelsPerInch)
  1036. {
  1037. if (PixelsPerInch >= 192)
  1038. {
  1039. PixelsPerInch = 192;
  1040. }
  1041. else if (PixelsPerInch >= 144)
  1042. {
  1043. PixelsPerInch = 144;
  1044. }
  1045. else if (PixelsPerInch >= 120)
  1046. {
  1047. PixelsPerInch = 120;
  1048. }
  1049. else
  1050. {
  1051. PixelsPerInch = 96;
  1052. }
  1053. return PixelsPerInch;
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. static int __fastcall NeedImagesModule(TControl * Control)
  1057. {
  1058. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  1059. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  1060. {
  1061. TDataModule * ImagesModule;
  1062. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  1063. try
  1064. {
  1065. if (PixelsPerInch == 192)
  1066. {
  1067. ImagesModule = new TAnimations192Module(Application);
  1068. }
  1069. else if (PixelsPerInch == 144)
  1070. {
  1071. ImagesModule = new TAnimations144Module(Application);
  1072. }
  1073. else if (PixelsPerInch == 120)
  1074. {
  1075. ImagesModule = new TAnimations120Module(Application);
  1076. }
  1077. else
  1078. {
  1079. DebugAssert(PixelsPerInch == 96);
  1080. ImagesModule = new TAnimations96Module(Application);
  1081. }
  1082. ImagesModules.insert(ImagesModule);
  1083. TPngImageList * AAnimationImages =
  1084. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  1085. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  1086. TImageList * AButtonImages =
  1087. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  1088. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  1089. TPngImageList * ADialogImages =
  1090. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  1091. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  1092. }
  1093. __finally
  1094. {
  1095. GUIConfiguration->ChangeResourceModule(ResourceModule);
  1096. }
  1097. }
  1098. return PixelsPerInch;
  1099. }
  1100. //---------------------------------------------------------------------------
  1101. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  1102. {
  1103. int PixelsPerInch = NeedImagesModule(Control);
  1104. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  1105. }
  1106. //---------------------------------------------------------------------------
  1107. TImageList * __fastcall GetButtonImages(TControl * Control)
  1108. {
  1109. int PixelsPerInch = NeedImagesModule(Control);
  1110. return DebugNotNull(ButtonImages[PixelsPerInch]);
  1111. }
  1112. //---------------------------------------------------------------------------
  1113. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  1114. {
  1115. int PixelsPerInch = NeedImagesModule(Control);
  1116. return DebugNotNull(DialogImages[PixelsPerInch]);
  1117. }
  1118. //---------------------------------------------------------------------------
  1119. void __fastcall ReleaseImagesModules()
  1120. {
  1121. TImagesModules::iterator i = ImagesModules.begin();
  1122. while (i != ImagesModules.end())
  1123. {
  1124. delete (*i);
  1125. i++;
  1126. }
  1127. ImagesModules.clear();
  1128. }
  1129. //---------------------------------------------------------------------------
  1130. __fastcall TFrameAnimation::TFrameAnimation()
  1131. {
  1132. FFirstFrame = -1;
  1133. }
  1134. //---------------------------------------------------------------------------
  1135. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1136. {
  1137. FName = Name;
  1138. FPaintBox = PaintBox;
  1139. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1140. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1141. FPaintBox->OnPaint = PaintBoxPaint;
  1142. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1143. DoInit();
  1144. }
  1145. //---------------------------------------------------------------------------
  1146. void __fastcall TFrameAnimation::DoInit()
  1147. {
  1148. FImageList = GetAnimationsImages(FPaintBox);
  1149. FFirstFrame = -1;
  1150. FFirstLoopFrame = -1;
  1151. FPaintBox->Width = FImageList->Width;
  1152. FPaintBox->Height = FImageList->Height;
  1153. if (!FName.IsEmpty())
  1154. {
  1155. int Frame = 0;
  1156. while (Frame < FImageList->PngImages->Count)
  1157. {
  1158. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1159. UnicodeString FrameName;
  1160. FrameName = CutToChar(FrameData, L'_', false);
  1161. if (SameText(FName, FrameName))
  1162. {
  1163. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1164. if (FFirstFrame < 0)
  1165. {
  1166. FFirstFrame = Frame;
  1167. }
  1168. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1169. {
  1170. FFirstLoopFrame = Frame;
  1171. }
  1172. FLastFrame = Frame;
  1173. }
  1174. else
  1175. {
  1176. if (FFirstFrame >= 0)
  1177. {
  1178. // optimization
  1179. break;
  1180. }
  1181. }
  1182. Frame++;
  1183. }
  1184. DebugAssert(FFirstFrame >= 0);
  1185. DebugAssert(FFirstLoopFrame >= 0);
  1186. }
  1187. Stop();
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1191. {
  1192. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1193. FrameAnimation->Rescale();
  1194. }
  1195. //---------------------------------------------------------------------------
  1196. void __fastcall TFrameAnimation::Rescale()
  1197. {
  1198. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1199. DoInit();
  1200. if (Started)
  1201. {
  1202. Start();
  1203. }
  1204. }
  1205. //---------------------------------------------------------------------------
  1206. void __fastcall TFrameAnimation::Start()
  1207. {
  1208. if (FFirstFrame >= 0)
  1209. {
  1210. FNextFrameTick = GetTickCount();
  1211. CalculateNextFrameTick();
  1212. if (FTimer == NULL)
  1213. {
  1214. FTimer = new TTimer(GetParentForm(FPaintBox));
  1215. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1216. FTimer->OnTimer = Timer;
  1217. }
  1218. else
  1219. {
  1220. // reset timer
  1221. FTimer->Enabled = false;
  1222. FTimer->Enabled = true;
  1223. }
  1224. }
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1228. {
  1229. Animate();
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1233. {
  1234. if (FFirstFrame >= 0)
  1235. {
  1236. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1237. DebugUsedParam(Sender);
  1238. DebugAssert(FPaintBox == Sender);
  1239. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1240. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1241. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1242. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1243. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1244. Bitmap->Canvas->FillRect(Rect);
  1245. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1246. DebugAssert(Graphic->Width == FPaintBox->Width);
  1247. DebugAssert(Graphic->Height == FPaintBox->Height);
  1248. Bitmap->Canvas->Draw(0, 0, Graphic);
  1249. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1250. }
  1251. FPainted = true;
  1252. }
  1253. //---------------------------------------------------------------------------
  1254. void __fastcall TFrameAnimation::Repaint()
  1255. {
  1256. FPainted = false;
  1257. // If the form is not showing yet, the Paint() is not even called
  1258. FPaintBox->Repaint();
  1259. if (!FPainted)
  1260. {
  1261. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  1262. // See also a hack in TAuthenticateForm::Log.
  1263. FPaintBox->Invalidate();
  1264. }
  1265. }
  1266. //---------------------------------------------------------------------------
  1267. void __fastcall TFrameAnimation::Stop()
  1268. {
  1269. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1270. FCurrentFrame = FFirstFrame;
  1271. Repaint();
  1272. if (FTimer != NULL)
  1273. {
  1274. FTimer->Enabled = false;
  1275. }
  1276. }
  1277. //---------------------------------------------------------------------------
  1278. void __fastcall TFrameAnimation::Animate()
  1279. {
  1280. if (FFirstFrame >= 0)
  1281. {
  1282. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1283. DWORD TickCount = GetTickCount();
  1284. // Keep in sync with an opposite condition at the end of the loop.
  1285. // We may skip some frames if we got stalled for a while
  1286. while (TickCount >= FNextFrameTick)
  1287. {
  1288. if (FCurrentFrame >= FLastFrame)
  1289. {
  1290. FCurrentFrame = FFirstLoopFrame;
  1291. }
  1292. else
  1293. {
  1294. FCurrentFrame++;
  1295. }
  1296. CalculateNextFrameTick();
  1297. Repaint();
  1298. }
  1299. }
  1300. }
  1301. //---------------------------------------------------------------------------
  1302. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1303. {
  1304. return FImageList->PngImages->Items[FCurrentFrame];
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1308. {
  1309. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1310. UnicodeString Duration = ImageItem->Name;
  1311. CutToChar(Duration, L'_', false);
  1312. // skip index (is not really used)
  1313. CutToChar(Duration, L'_', false);
  1314. // This should overflow, when tick count wraps.
  1315. FNextFrameTick += StrToInt(Duration) * 10;
  1316. }
  1317. //---------------------------------------------------------------------------
  1318. //---------------------------------------------------------------------------
  1319. // Hints use:
  1320. // - Cleanup list tooltip (multi line)
  1321. // - Combo edit button
  1322. // - Transfer settings label (multi line, follows label size and font)
  1323. // - HintLabel (hint and persistent hint, multipline)
  1324. // - status bar hints
  1325. //---------------------------------------------------------------------------
  1326. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  1327. THintWindow(Owner)
  1328. {
  1329. FParentPainting = false;
  1330. }
  1331. //---------------------------------------------------------------------------
  1332. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  1333. {
  1334. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  1335. }
  1336. //---------------------------------------------------------------------------
  1337. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  1338. {
  1339. return
  1340. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  1341. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL);
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  1345. {
  1346. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  1347. }
  1348. //---------------------------------------------------------------------------
  1349. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  1350. {
  1351. int Result;
  1352. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1353. {
  1354. Result = 3;
  1355. }
  1356. else
  1357. {
  1358. Result = 6;
  1359. }
  1360. Result = ScaleByTextHeight(HintControl, Result);
  1361. return Result;
  1362. }
  1363. //---------------------------------------------------------------------------
  1364. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  1365. {
  1366. TFont * Result;
  1367. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1368. {
  1369. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  1370. }
  1371. else
  1372. {
  1373. FScaledHintFont.reset(new TFont());
  1374. FScaledHintFont->Assign(Screen->HintFont);
  1375. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  1376. Result = FScaledHintFont.get();
  1377. }
  1378. return Result;
  1379. }
  1380. //---------------------------------------------------------------------------
  1381. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  1382. {
  1383. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  1384. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  1388. {
  1389. TControl * HintControl = GetHintControl(AData);
  1390. int Margin = GetMargin(HintControl, AHint);
  1391. UnicodeString ShortHint;
  1392. UnicodeString LongHint;
  1393. SplitHint(HintControl, AHint, ShortHint, LongHint);
  1394. Canvas->Font->Assign(GetFont(HintControl, AHint));
  1395. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  1396. if (!LongHint.IsEmpty())
  1397. {
  1398. // double-margin on the right
  1399. MaxWidth = ScreenTipTextOnlyWidth - (3 * Margin);
  1400. }
  1401. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  1402. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  1403. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  1404. if (ShortHint.Pos(L"\n") > 0)
  1405. {
  1406. MaxWidth *= 2;
  1407. }
  1408. bool HintPopup = HasLabelHintPopup(HintControl, AHint);
  1409. if (HintPopup)
  1410. {
  1411. MaxWidth = HintControl->Width;
  1412. }
  1413. if (UseBoldShortHint(HintControl))
  1414. {
  1415. Canvas->Font->Style = TFontStyles() << fsBold;
  1416. }
  1417. TRect ShortRect(0, 0, MaxWidth, 0);
  1418. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  1419. Canvas->Font->Style = TFontStyles();
  1420. TRect Result;
  1421. if (LongHint.IsEmpty())
  1422. {
  1423. Result = ShortRect;
  1424. if (HintPopup)
  1425. {
  1426. Result.Right = MaxWidth + 2 * Margin;
  1427. }
  1428. else
  1429. {
  1430. Result.Right += 3 * Margin;
  1431. }
  1432. Result.Bottom += 2 * Margin;
  1433. }
  1434. else
  1435. {
  1436. const int LongIndentation = Margin * 3 / 2;
  1437. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  1438. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  1439. Result.Right = ScreenTipTextOnlyWidth;
  1440. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  1441. }
  1442. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  1443. Result.Bottom -= 4;
  1444. return Result;
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. void __fastcall TScreenTipHintWindow::SplitHint(
  1448. TControl * HintControl, const UnicodeString & Hint, UnicodeString & ShortHint, UnicodeString & LongHint)
  1449. {
  1450. if (HasLabelHintPopup(HintControl, Hint))
  1451. {
  1452. ShortHint = HintControl->Hint;
  1453. }
  1454. else
  1455. {
  1456. ShortHint = GetShortHint(Hint);
  1457. LongHint = GetLongHintIfAny(Hint);
  1458. }
  1459. }
  1460. //---------------------------------------------------------------------------
  1461. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  1462. {
  1463. FHintControl = GetHintControl(AData);
  1464. SplitHint(FHintControl, AHint, FShortHint, FLongHint);
  1465. FMargin = GetMargin(FHintControl, AHint);
  1466. FHintPopup = HasLabelHintPopup(FHintControl, AHint);
  1467. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  1468. TRect Rect = ARect;
  1469. if (FHintPopup)
  1470. {
  1471. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  1472. }
  1473. if (IsPathLabel(FHintControl))
  1474. {
  1475. Rect.Offset(-FMargin, -FMargin);
  1476. }
  1477. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  1478. }
  1479. //---------------------------------------------------------------------------
  1480. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  1481. {
  1482. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  1483. }
  1484. //---------------------------------------------------------------------------
  1485. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  1486. {
  1487. UnicodeString Result;
  1488. int P = Pos(L"|", AHint);
  1489. if (P > 0)
  1490. {
  1491. Result = GetLongHint(AHint);
  1492. }
  1493. return Result;
  1494. }
  1495. //---------------------------------------------------------------------------
  1496. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  1497. {
  1498. TMessage * Message = static_cast<TMessage*>(AMessage);
  1499. switch (Message->Msg)
  1500. {
  1501. case WM_GETTEXTLENGTH:
  1502. if (FParentPainting)
  1503. {
  1504. // make THintWindow::Paint() not paint the Caption
  1505. Message->Result = 0;
  1506. }
  1507. else
  1508. {
  1509. THintWindow::Dispatch(AMessage);
  1510. }
  1511. break;
  1512. default:
  1513. THintWindow::Dispatch(AMessage);
  1514. break;
  1515. }
  1516. }
  1517. //---------------------------------------------------------------------------
  1518. void __fastcall TScreenTipHintWindow::Paint()
  1519. {
  1520. // paint frame/background
  1521. {
  1522. TAutoFlag ParentPaintingFlag(FParentPainting);
  1523. THintWindow::Paint();
  1524. }
  1525. const int Flags = GetTextFlags(this);
  1526. const int Margin = FMargin - 1; // 1 = border
  1527. TRect Rect = ClientRect;
  1528. Rect.Inflate(-Margin, -Margin);
  1529. if (!FHintPopup)
  1530. {
  1531. Rect.Right -= FMargin;
  1532. }
  1533. if (UseBoldShortHint(FHintControl))
  1534. {
  1535. Canvas->Font->Style = TFontStyles() << fsBold;
  1536. }
  1537. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  1538. TRect ShortRect = Rect;
  1539. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  1540. Canvas->Font->Style = TFontStyles();
  1541. if (!FLongHint.IsEmpty())
  1542. {
  1543. Rect.Left += FMargin * 3 / 2;
  1544. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  1545. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  1546. }
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. //---------------------------------------------------------------------------
  1550. __fastcall TNewRichEdit::TNewRichEdit(TComponent * AOwner) :
  1551. TRichEdit(AOwner),
  1552. FLibrary(0)
  1553. {
  1554. }
  1555. //---------------------------------------------------------------------------
  1556. void __fastcall TNewRichEdit::CreateParams(TCreateParams & Params)
  1557. {
  1558. UnicodeString RichEditModuleName(L"MSFTEDIT.DLL");
  1559. long int OldError;
  1560. OldError = SetErrorMode(SEM_NOOPENFILEERRORBOX);
  1561. FLibrary = LoadLibrary(RichEditModuleName.c_str());
  1562. SetErrorMode(OldError);
  1563. // No fallback, MSFTEDIT.DLL is available since Windows XP
  1564. // https://blogs.msdn.microsoft.com/murrays/2006/10/13/richedit-versions/
  1565. if (FLibrary == 0)
  1566. {
  1567. throw Exception(FORMAT(L"Cannot load %s", (RichEditModuleName)));
  1568. }
  1569. TCustomMemo::CreateParams(Params);
  1570. // MSDN says that we should use MSFTEDIT_CLASS to load Rich Edit 4.1:
  1571. // https://docs.microsoft.com/en-us/windows/desktop/controls/about-rich-edit-controls
  1572. // But MSFTEDIT_CLASS is defined as "RICHEDIT50W",
  1573. // so not sure what version we are loading.
  1574. // Seem to work on Windows XP SP3.
  1575. CreateSubClass(Params, MSFTEDIT_CLASS);
  1576. }
  1577. //---------------------------------------------------------------------------
  1578. void __fastcall TNewRichEdit::CreateWnd()
  1579. {
  1580. TRichEdit::CreateWnd();
  1581. SendMessage(Handle, EM_SETEDITSTYLEEX, 0, SES_EX_HANDLEFRIENDLYURL);
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. void __fastcall TNewRichEdit::DestroyWnd()
  1585. {
  1586. TRichEdit::DestroyWnd();
  1587. if (FLibrary != 0)
  1588. {
  1589. FreeLibrary(FLibrary);
  1590. }
  1591. }