GUITools.cpp 46 KB

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