GUITools.cpp 45 KB

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