GUITools.cpp 54 KB

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