GUITools.cpp 45 KB

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