GUITools.cpp 52 KB

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