GUITools.cpp 53 KB

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